blob: 4ec374332173a510a2df8eda54884e5ff937862c [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnaye79ae182018-01-06 19:23:37 -08009//! Tokens representing Rust punctuation, keywords, and delimiters.
Alex Crichton954046c2017-05-30 21:49:42 -070010//!
David Tolnaye79ae182018-01-06 19:23:37 -080011//! The type names in this module can be difficult to keep straight, so we
12//! prefer to use the [`Token!`] macro instead. This is a type-macro that
13//! expands to the token type of the given token.
14//!
15//! [`Token!`]: ../macro.Token.html
16//!
17//! # Example
18//!
19//! The [`ItemStatic`] syntax tree node is defined like this.
20//!
21//! [`ItemStatic`]: ../struct.ItemStatic.html
22//!
23//! ```
24//! # #[macro_use]
25//! # extern crate syn;
26//! #
David Tolnaye303b7c2018-05-20 16:46:35 -070027//! # use syn::{Attribute, Visibility, Ident, Type, Expr};
David Tolnaye79ae182018-01-06 19:23:37 -080028//! #
29//! pub struct ItemStatic {
30//! pub attrs: Vec<Attribute>,
31//! pub vis: Visibility,
32//! pub static_token: Token![static],
33//! pub mutability: Option<Token![mut]>,
34//! pub ident: Ident,
35//! pub colon_token: Token![:],
36//! pub ty: Box<Type>,
37//! pub eq_token: Token![=],
38//! pub expr: Box<Expr>,
39//! pub semi_token: Token![;],
40//! }
41//! #
42//! # fn main() {}
43//! ```
44//!
45//! # Parsing
46//!
47//! These tokens can be parsed using the [`Synom`] trait and the parser
48//! combinator macros [`punct!`], [`keyword!`], [`parens!`], [`braces!`], and
49//! [`brackets!`].
50//!
51//! [`Synom`]: ../synom/trait.Synom.html
52//! [`punct!`]: ../macro.punct.html
53//! [`keyword!`]: ../macro.keyword.html
54//! [`parens!`]: ../macro.parens.html
55//! [`braces!`]: ../macro.braces.html
56//! [`brackets!`]: ../macro.brackets.html
57//!
58//! ```
59//! #[macro_use]
60//! extern crate syn;
61//!
62//! use syn::synom::Synom;
David Tolnaye303b7c2018-05-20 16:46:35 -070063//! use syn::{Attribute, Visibility, Ident, Type, Expr};
David Tolnaye79ae182018-01-06 19:23:37 -080064//! #
65//! # struct ItemStatic;
66//! # use syn::ItemStatic as SynItemStatic;
67//!
68//! // Parse the ItemStatic struct shown above.
69//! impl Synom for ItemStatic {
70//! named!(parse -> Self, do_parse!(
71//! # (ItemStatic)
72//! # ));
73//! # }
74//! #
75//! # mod example {
76//! # use super::*;
77//! # use super::SynItemStatic as ItemStatic;
78//! #
79//! # named!(parse -> ItemStatic, do_parse!(
80//! attrs: many0!(Attribute::parse_outer) >>
81//! vis: syn!(Visibility) >>
82//! static_token: keyword!(static) >>
83//! mutability: option!(keyword!(mut)) >>
84//! ident: syn!(Ident) >>
85//! colon_token: punct!(:) >>
86//! ty: syn!(Type) >>
87//! eq_token: punct!(=) >>
88//! expr: syn!(Expr) >>
89//! semi_token: punct!(;) >>
90//! (ItemStatic {
91//! attrs, vis, static_token, mutability, ident, colon_token,
92//! ty: Box::new(ty), eq_token, expr: Box::new(expr), semi_token,
93//! })
94//! ));
95//! }
96//! #
97//! # fn main() {}
98//! ```
Alex Crichton954046c2017-05-30 21:49:42 -070099
David Tolnay65fb5662018-05-20 20:02:28 -0700100use proc_macro2::{Ident, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700101
102macro_rules! tokens {
103 (
David Tolnay73c98de2017-12-31 15:56:56 -0500104 punct: {
105 $($punct:tt pub struct $punct_name:ident/$len:tt #[$punct_doc:meta])*
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700106 }
David Tolnay73c98de2017-12-31 15:56:56 -0500107 delimiter: {
108 $($delimiter:tt pub struct $delimiter_name:ident #[$delimiter_doc:meta])*
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700109 }
David Tolnay73c98de2017-12-31 15:56:56 -0500110 keyword: {
111 $($keyword:tt pub struct $keyword_name:ident #[$keyword_doc:meta])*
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700112 }
113 ) => (
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700114 $(token_punct_def! { #[$punct_doc] pub struct $punct_name/$len })*
David Tolnay7ac699c2018-08-24 14:00:58 -0400115 $(token_punct_parser! { $punct pub struct $punct_name/$len })*
David Tolnay73c98de2017-12-31 15:56:56 -0500116 $(token_delimiter! { #[$delimiter_doc] $delimiter pub struct $delimiter_name })*
117 $(token_keyword! { #[$keyword_doc] $keyword pub struct $keyword_name })*
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700118 )
119}
120
Sergio Benitezd14d5362018-04-28 15:38:25 -0700121macro_rules! token_punct_def {
David Tolnay65fb5662018-05-20 20:02:28 -0700122 (#[$doc:meta]pub struct $name:ident / $len:tt) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700123 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500124 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800125 ///
126 /// Don't try to remember the name of this type -- use the [`Token!`]
127 /// macro instead.
128 ///
129 /// [`Token!`]: index.html
David Tolnay7ac699c2018-08-24 14:00:58 -0400130 pub struct $name {
131 pub spans: [Span; $len],
132 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700133
David Tolnay7ac699c2018-08-24 14:00:58 -0400134 #[doc(hidden)]
135 #[allow(non_snake_case)]
136 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
David Tolnayd17b64f2018-08-24 16:46:10 -0400137 $name {
138 spans: spans.into_spans(),
139 }
David Tolnay0bdb0552017-12-27 21:31:51 -0500140 }
141
David Tolnay66bb8d52018-01-08 08:22:31 -0800142 impl ::std::default::Default for $name {
143 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700144 $name([Span::call_site(); $len])
David Tolnay66bb8d52018-01-08 08:22:31 -0800145 }
146 }
147
Nika Layzelld73a3652017-10-24 08:57:05 -0400148 #[cfg(feature = "extra-traits")]
149 impl ::std::fmt::Debug for $name {
150 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
David Tolnay98942562017-12-26 21:24:35 -0500151 f.write_str(stringify!($name))
Nika Layzelld73a3652017-10-24 08:57:05 -0400152 }
153 }
154
David Tolnay98942562017-12-26 21:24:35 -0500155 #[cfg(feature = "extra-traits")]
156 impl ::std::cmp::Eq for $name {}
157
158 #[cfg(feature = "extra-traits")]
159 impl ::std::cmp::PartialEq for $name {
160 fn eq(&self, _other: &$name) -> bool {
161 true
162 }
163 }
164
165 #[cfg(feature = "extra-traits")]
166 impl ::std::hash::Hash for $name {
167 fn hash<H>(&self, _state: &mut H)
David Tolnay94d2b792018-04-29 12:26:10 -0700168 where
169 H: ::std::hash::Hasher,
170 {
171 }
David Tolnay98942562017-12-26 21:24:35 -0500172 }
173
Sergio Benitezd14d5362018-04-28 15:38:25 -0700174 impl From<Span> for $name {
175 fn from(span: Span) -> Self {
176 $name([span; $len])
177 }
178 }
David Tolnay94d2b792018-04-29 12:26:10 -0700179 };
Sergio Benitezd14d5362018-04-28 15:38:25 -0700180}
181
182macro_rules! token_punct_parser {
David Tolnay7ac699c2018-08-24 14:00:58 -0400183 ($s:tt pub struct $name:ident/$len:tt) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700184 #[cfg(feature = "printing")]
185 impl ::quote::ToTokens for $name {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700186 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
David Tolnay7ac699c2018-08-24 14:00:58 -0400187 printing::punct($s, &self.spans, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700188 }
189 }
190
191 #[cfg(feature = "parsing")]
192 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800193 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay7ac699c2018-08-24 14:00:58 -0400194 parsing::punct($s, tokens, $name::<[Span; $len]>)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700195 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800196
197 fn description() -> Option<&'static str> {
198 Some(concat!("`", $s, "`"))
199 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700200 }
David Tolnay94d2b792018-04-29 12:26:10 -0700201 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700202}
203
David Tolnay73c98de2017-12-31 15:56:56 -0500204macro_rules! token_keyword {
David Tolnay5a20f632017-12-26 22:11:28 -0500205 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700206 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500207 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800208 ///
209 /// Don't try to remember the name of this type -- use the [`Token!`]
210 /// macro instead.
211 ///
212 /// [`Token!`]: index.html
David Tolnay7ac699c2018-08-24 14:00:58 -0400213 pub struct $name {
214 pub span: Span,
215 }
216
217 #[doc(hidden)]
218 #[allow(non_snake_case)]
219 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
David Tolnayd17b64f2018-08-24 16:46:10 -0400220 $name {
221 span: span.into_spans()[0],
222 }
David Tolnay7ac699c2018-08-24 14:00:58 -0400223 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700224
David Tolnay66bb8d52018-01-08 08:22:31 -0800225 impl ::std::default::Default for $name {
226 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700227 $name(Span::call_site())
David Tolnay66bb8d52018-01-08 08:22:31 -0800228 }
229 }
230
David Tolnay98942562017-12-26 21:24:35 -0500231 #[cfg(feature = "extra-traits")]
232 impl ::std::fmt::Debug for $name {
233 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
234 f.write_str(stringify!($name))
235 }
236 }
237
238 #[cfg(feature = "extra-traits")]
239 impl ::std::cmp::Eq for $name {}
240
241 #[cfg(feature = "extra-traits")]
242 impl ::std::cmp::PartialEq for $name {
243 fn eq(&self, _other: &$name) -> bool {
244 true
245 }
246 }
247
248 #[cfg(feature = "extra-traits")]
249 impl ::std::hash::Hash for $name {
250 fn hash<H>(&self, _state: &mut H)
David Tolnay94d2b792018-04-29 12:26:10 -0700251 where
252 H: ::std::hash::Hasher,
253 {
254 }
David Tolnay98942562017-12-26 21:24:35 -0500255 }
256
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700257 #[cfg(feature = "printing")]
258 impl ::quote::ToTokens for $name {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700259 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
David Tolnay7ac699c2018-08-24 14:00:58 -0400260 printing::keyword($s, &self.span, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700261 }
262 }
263
264 #[cfg(feature = "parsing")]
265 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800266 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500267 parsing::keyword($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700268 }
David Tolnay79777332018-01-07 10:04:42 -0800269
270 fn description() -> Option<&'static str> {
271 Some(concat!("`", $s, "`"))
272 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700273 }
강동윤d5229da2018-01-12 13:11:33 +0900274
275 impl From<Span> for $name {
276 fn from(span: Span) -> Self {
277 $name(span)
278 }
279 }
David Tolnay94d2b792018-04-29 12:26:10 -0700280 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700281}
282
David Tolnay73c98de2017-12-31 15:56:56 -0500283macro_rules! token_delimiter {
David Tolnay5a20f632017-12-26 22:11:28 -0500284 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700285 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500286 #[$doc]
David Tolnay7ac699c2018-08-24 14:00:58 -0400287 pub struct $name {
288 pub span: Span,
289 }
290
291 #[doc(hidden)]
292 #[allow(non_snake_case)]
293 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
David Tolnayd17b64f2018-08-24 16:46:10 -0400294 $name {
295 span: span.into_spans()[0],
296 }
David Tolnay7ac699c2018-08-24 14:00:58 -0400297 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700298
David Tolnay66bb8d52018-01-08 08:22:31 -0800299 impl ::std::default::Default for $name {
300 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700301 $name(Span::call_site())
David Tolnay66bb8d52018-01-08 08:22:31 -0800302 }
303 }
304
David Tolnay98942562017-12-26 21:24:35 -0500305 #[cfg(feature = "extra-traits")]
306 impl ::std::fmt::Debug for $name {
307 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
308 f.write_str(stringify!($name))
309 }
310 }
311
312 #[cfg(feature = "extra-traits")]
313 impl ::std::cmp::Eq for $name {}
314
315 #[cfg(feature = "extra-traits")]
316 impl ::std::cmp::PartialEq for $name {
317 fn eq(&self, _other: &$name) -> bool {
318 true
319 }
320 }
321
322 #[cfg(feature = "extra-traits")]
323 impl ::std::hash::Hash for $name {
324 fn hash<H>(&self, _state: &mut H)
David Tolnay94d2b792018-04-29 12:26:10 -0700325 where
326 H: ::std::hash::Hasher,
327 {
328 }
David Tolnay98942562017-12-26 21:24:35 -0500329 }
330
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700331 impl $name {
332 #[cfg(feature = "printing")]
Alex Crichtona74a1c82018-05-16 10:20:44 -0700333 pub fn surround<F>(&self, tokens: &mut ::proc_macro2::TokenStream, f: F)
David Tolnay94d2b792018-04-29 12:26:10 -0700334 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700335 F: FnOnce(&mut ::proc_macro2::TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700336 {
David Tolnay7ac699c2018-08-24 14:00:58 -0400337 printing::delim($s, &self.span, tokens, f);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700338 }
339
340 #[cfg(feature = "parsing")]
David Tolnay94d2b792018-04-29 12:26:10 -0700341 pub fn parse<F, R>(
342 tokens: $crate::buffer::Cursor,
343 f: F,
344 ) -> $crate::synom::PResult<($name, R)>
345 where
346 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700347 {
348 parsing::delim($s, tokens, $name, f)
349 }
350 }
강동윤d5229da2018-01-12 13:11:33 +0900351
352 impl From<Span> for $name {
353 fn from(span: Span) -> Self {
354 $name(span)
355 }
356 }
David Tolnay94d2b792018-04-29 12:26:10 -0700357 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700358}
359
Sergio Benitezd14d5362018-04-28 15:38:25 -0700360token_punct_def! {
361 /// `_`
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700362 pub struct Underscore/1
Sergio Benitezd14d5362018-04-28 15:38:25 -0700363}
364
365#[cfg(feature = "printing")]
366impl ::quote::ToTokens for Underscore {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700367 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
368 use quote::TokenStreamExt;
David Tolnay7ac699c2018-08-24 14:00:58 -0400369 tokens.append(::proc_macro2::Ident::new("_", self.spans[0]));
Sergio Benitezd14d5362018-04-28 15:38:25 -0700370 }
371}
372
373#[cfg(feature = "parsing")]
374impl ::Synom for Underscore {
375 fn parse(input: ::buffer::Cursor) -> ::synom::PResult<Underscore> {
David Tolnay55a5f3a2018-05-20 18:00:51 -0700376 match input.ident() {
David Tolnaya4319b72018-06-02 00:49:15 -0700377 Some((ident, rest)) => {
378 if ident == "_" {
379 Ok((Underscore([ident.span()]), rest))
Alex Crichtona74a1c82018-05-16 10:20:44 -0700380 } else {
381 ::parse_error()
382 }
383 }
David Tolnay7ac699c2018-08-24 14:00:58 -0400384 None => parsing::punct("_", input, Underscore::<[Span; 1]>),
Sergio Benitezd14d5362018-04-28 15:38:25 -0700385 }
386 }
387
388 fn description() -> Option<&'static str> {
389 Some("`_`")
390 }
391}
392
Alex Crichton131308c2018-05-18 14:00:24 -0700393token_punct_def! {
394 /// `'`
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700395 pub struct Apostrophe/1
Alex Crichton131308c2018-05-18 14:00:24 -0700396}
397
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700398// Implement Clone anyway because it is required for cloning Lifetime.
399#[cfg(not(feature = "clone-impls"))]
400impl Clone for Apostrophe {
401 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400402 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700403 }
404}
405
Alex Crichton131308c2018-05-18 14:00:24 -0700406#[cfg(feature = "printing")]
407impl ::quote::ToTokens for Apostrophe {
408 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
409 use quote::TokenStreamExt;
410 let mut token = ::proc_macro2::Punct::new('\'', ::proc_macro2::Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400411 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700412 tokens.append(token);
413 }
414}
415
416#[cfg(feature = "parsing")]
417impl ::Synom for Apostrophe {
418 fn parse(input: ::buffer::Cursor) -> ::synom::PResult<Apostrophe> {
David Tolnay55a5f3a2018-05-20 18:00:51 -0700419 match input.punct() {
Alex Crichton131308c2018-05-18 14:00:24 -0700420 Some((op, rest)) => {
421 if op.as_char() == '\'' && op.spacing() == ::proc_macro2::Spacing::Joint {
422 Ok((Apostrophe([op.span()]), rest))
423 } else {
424 ::parse_error()
425 }
426 }
David Tolnay65fb5662018-05-20 20:02:28 -0700427 None => ::parse_error(),
Alex Crichton131308c2018-05-18 14:00:24 -0700428 }
429 }
430
431 fn description() -> Option<&'static str> {
432 Some("`'`")
433 }
434}
435
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700436tokens! {
David Tolnay73c98de2017-12-31 15:56:56 -0500437 punct: {
David Tolnaybb82ef02018-08-24 20:15:45 -0400438 "+" pub struct Add/1 /// `+`
439 "+=" pub struct AddEq/2 /// `+=`
440 "&" pub struct And/1 /// `&`
441 "&&" pub struct AndAnd/2 /// `&&`
442 "&=" pub struct AndEq/2 /// `&=`
443 "@" pub struct At/1 /// `@`
444 "!" pub struct Bang/1 /// `!`
445 "^" pub struct Caret/1 /// `^`
446 "^=" pub struct CaretEq/2 /// `^=`
447 ":" pub struct Colon/1 /// `:`
448 "::" pub struct Colon2/2 /// `::`
449 "," pub struct Comma/1 /// `,`
450 "/" pub struct Div/1 /// `/`
451 "/=" pub struct DivEq/2 /// `/=`
452 "$" pub struct Dollar/1 /// `$`
453 "." pub struct Dot/1 /// `.`
454 ".." pub struct Dot2/2 /// `..`
455 "..." pub struct Dot3/3 /// `...`
456 "..=" pub struct DotDotEq/3 /// `..=`
457 "=" pub struct Eq/1 /// `=`
458 "==" pub struct EqEq/2 /// `==`
459 ">=" pub struct Ge/2 /// `>=`
460 ">" pub struct Gt/1 /// `>`
461 "<=" pub struct Le/2 /// `<=`
462 "<" pub struct Lt/1 /// `<`
463 "*=" pub struct MulEq/2 /// `*=`
464 "!=" pub struct Ne/2 /// `!=`
465 "|" pub struct Or/1 /// `|`
466 "|=" pub struct OrEq/2 /// `|=`
467 "||" pub struct OrOr/2 /// `||`
468 "#" pub struct Pound/1 /// `#`
469 "?" pub struct Question/1 /// `?`
470 "->" pub struct RArrow/2 /// `->`
471 "<-" pub struct LArrow/2 /// `<-`
472 "%" pub struct Rem/1 /// `%`
473 "%=" pub struct RemEq/2 /// `%=`
474 "=>" pub struct FatArrow/2 /// `=>`
475 ";" pub struct Semi/1 /// `;`
476 "<<" pub struct Shl/2 /// `<<`
477 "<<=" pub struct ShlEq/3 /// `<<=`
478 ">>" pub struct Shr/2 /// `>>`
479 ">>=" pub struct ShrEq/3 /// `>>=`
480 "*" pub struct Star/1 /// `*`
481 "-" pub struct Sub/1 /// `-`
482 "-=" pub struct SubEq/2 /// `-=`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700483 }
David Tolnay73c98de2017-12-31 15:56:56 -0500484 delimiter: {
David Tolnaybb82ef02018-08-24 20:15:45 -0400485 "{" pub struct Brace /// `{...}`
486 "[" pub struct Bracket /// `[...]`
487 "(" pub struct Paren /// `(...)`
488 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700489 }
David Tolnay73c98de2017-12-31 15:56:56 -0500490 keyword: {
David Tolnaybb82ef02018-08-24 20:15:45 -0400491 "as" pub struct As /// `as`
492 "async" pub struct Async /// `async`
493 "auto" pub struct Auto /// `auto`
494 "box" pub struct Box /// `box`
495 "break" pub struct Break /// `break`
496 "Self" pub struct CapSelf /// `Self`
497 "const" pub struct Const /// `const`
498 "continue" pub struct Continue /// `continue`
499 "crate" pub struct Crate /// `crate`
500 "default" pub struct Default /// `default`
501 "dyn" pub struct Dyn /// `dyn`
502 "else" pub struct Else /// `else`
503 "enum" pub struct Enum /// `enum`
504 "existential" pub struct Existential /// `existential`
505 "extern" pub struct Extern /// `extern`
506 "fn" pub struct Fn /// `fn`
507 "for" pub struct For /// `for`
508 "if" pub struct If /// `if`
509 "impl" pub struct Impl /// `impl`
510 "in" pub struct In /// `in`
511 "let" pub struct Let /// `let`
512 "loop" pub struct Loop /// `loop`
513 "macro" pub struct Macro /// `macro`
514 "match" pub struct Match /// `match`
515 "mod" pub struct Mod /// `mod`
516 "move" pub struct Move /// `move`
517 "mut" pub struct Mut /// `mut`
518 "pub" pub struct Pub /// `pub`
519 "ref" pub struct Ref /// `ref`
520 "return" pub struct Return /// `return`
521 "self" pub struct Self_ /// `self`
522 "static" pub struct Static /// `static`
523 "struct" pub struct Struct /// `struct`
524 "super" pub struct Super /// `super`
525 "trait" pub struct Trait /// `trait`
526 "try" pub struct Try /// `try`
527 "type" pub struct Type /// `type`
528 "union" pub struct Union /// `union`
529 "unsafe" pub struct Unsafe /// `unsafe`
530 "use" pub struct Use /// `use`
531 "where" pub struct Where /// `where`
532 "while" pub struct While /// `while`
533 "yield" pub struct Yield /// `yield`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700534 }
535}
536
David Tolnayf005f962018-01-06 21:19:41 -0800537/// A type-macro that expands to the name of the Rust type representation of a
538/// given token.
539///
540/// See the [token module] documentation for details and examples.
541///
542/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800543// Unfortunate duplication due to a rustdoc bug.
544// https://github.com/rust-lang/rust/issues/45939
545#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700546#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800547macro_rules! Token {
David Tolnaybb82ef02018-08-24 20:15:45 -0400548 (+) => { $crate::token::Add };
549 (+=) => { $crate::token::AddEq };
550 (&) => { $crate::token::And };
551 (&&) => { $crate::token::AndAnd };
552 (&=) => { $crate::token::AndEq };
553 (@) => { $crate::token::At };
554 (!) => { $crate::token::Bang };
555 (^) => { $crate::token::Caret };
556 (^=) => { $crate::token::CaretEq };
557 (:) => { $crate::token::Colon };
558 (::) => { $crate::token::Colon2 };
559 (,) => { $crate::token::Comma };
560 (/) => { $crate::token::Div };
561 (/=) => { $crate::token::DivEq };
562 (.) => { $crate::token::Dot };
563 (..) => { $crate::token::Dot2 };
564 (...) => { $crate::token::Dot3 };
565 (..=) => { $crate::token::DotDotEq };
566 (=) => { $crate::token::Eq };
567 (==) => { $crate::token::EqEq };
568 (>=) => { $crate::token::Ge };
569 (>) => { $crate::token::Gt };
570 (<=) => { $crate::token::Le };
571 (<) => { $crate::token::Lt };
572 (*=) => { $crate::token::MulEq };
573 (!=) => { $crate::token::Ne };
574 (|) => { $crate::token::Or };
575 (|=) => { $crate::token::OrEq };
576 (||) => { $crate::token::OrOr };
577 (#) => { $crate::token::Pound };
578 (?) => { $crate::token::Question };
579 (->) => { $crate::token::RArrow };
580 (<-) => { $crate::token::LArrow };
581 (%) => { $crate::token::Rem };
582 (%=) => { $crate::token::RemEq };
583 (=>) => { $crate::token::FatArrow };
584 (;) => { $crate::token::Semi };
585 (<<) => { $crate::token::Shl };
586 (<<=) => { $crate::token::ShlEq };
587 (>>) => { $crate::token::Shr };
588 (>>=) => { $crate::token::ShrEq };
589 (*) => { $crate::token::Star };
590 (-) => { $crate::token::Sub };
591 (-=) => { $crate::token::SubEq };
592 (_) => { $crate::token::Underscore };
593 (as) => { $crate::token::As };
594 (async) => { $crate::token::Async };
595 (auto) => { $crate::token::Auto };
596 (box) => { $crate::token::Box };
597 (break) => { $crate::token::Break };
598 (Self) => { $crate::token::CapSelf };
599 (const) => { $crate::token::Const };
600 (continue) => { $crate::token::Continue };
601 (crate) => { $crate::token::Crate };
602 (default) => { $crate::token::Default };
603 (dyn) => { $crate::token::Dyn };
604 (else) => { $crate::token::Else };
605 (enum) => { $crate::token::Enum };
606 (existential) => { $crate::token::Existential };
607 (extern) => { $crate::token::Extern };
608 (fn) => { $crate::token::Fn };
609 (for) => { $crate::token::For };
610 (if) => { $crate::token::If };
611 (impl) => { $crate::token::Impl };
612 (in) => { $crate::token::In };
613 (let) => { $crate::token::Let };
614 (loop) => { $crate::token::Loop };
615 (macro) => { $crate::token::Macro };
616 (match) => { $crate::token::Match };
617 (mod) => { $crate::token::Mod };
618 (move) => { $crate::token::Move };
619 (mut) => { $crate::token::Mut };
620 (pub) => { $crate::token::Pub };
621 (ref) => { $crate::token::Ref };
622 (return) => { $crate::token::Return };
623 (self) => { $crate::token::Self_ };
624 (static) => { $crate::token::Static };
625 (struct) => { $crate::token::Struct };
626 (super) => { $crate::token::Super };
627 (trait) => { $crate::token::Trait };
628 (try) => { $crate::token::Try };
629 (type) => { $crate::token::Type };
630 (union) => { $crate::token::Union };
631 (unsafe) => { $crate::token::Unsafe };
632 (use) => { $crate::token::Use };
633 (where) => { $crate::token::Where };
634 (while) => { $crate::token::While };
635 (yield) => { $crate::token::Yield };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800636}
637
David Tolnayf005f962018-01-06 21:19:41 -0800638/// Parse a single Rust punctuation token.
639///
640/// See the [token module] documentation for details and examples.
641///
642/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800643///
644/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500645#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800646#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700647#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800648macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500649 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
650 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
651 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
652 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
653 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
654 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
655 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
656 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
657 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
658 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
659 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
660 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
661 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
662 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
663 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
664 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
665 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
666 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
667 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
668 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
669 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
670 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
671 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
672 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
673 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
674 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
675 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
676 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
677 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
678 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
679 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
680 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
681 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
682 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
683 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200684 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500685 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
686 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
687 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
688 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
689 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
690 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
691 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
692 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
693 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800694}
695
David Tolnayf005f962018-01-06 21:19:41 -0800696/// Parse a single Rust keyword token.
697///
698/// See the [token module] documentation for details and examples.
699///
700/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800701///
702/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500703#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800704#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700705#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800706macro_rules! keyword {
David Tolnaybb82ef02018-08-24 20:15:45 -0400707 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
708 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
709 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
710 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
711 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
712 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
713 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
714 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
715 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
716 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
717 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
718 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
719 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
720 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
721 ($i:expr, existential) => { call!($i, <$crate::token::Existential as $crate::synom::Synom>::parse) };
722 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
723 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
724 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
725 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
726 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
727 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
728 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
729 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
730 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
731 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
732 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
733 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
734 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
735 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
736 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
737 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
738 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
739 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
740 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
741 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
742 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
743 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
744 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
745 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
746 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
747 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
748 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
749 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800750}
751
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700752macro_rules! ident_from_token {
753 ($token:ident) => {
754 impl From<Token![$token]> for Ident {
755 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400756 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700757 }
758 }
759 };
760}
761
762ident_from_token!(self);
763ident_from_token!(Self);
764ident_from_token!(super);
765ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700766ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700767
David Tolnay7ac699c2018-08-24 14:00:58 -0400768// Not public API.
769#[doc(hidden)]
770pub trait IntoSpans<S> {
771 fn into_spans(self) -> S;
772}
773
774impl IntoSpans<[Span; 1]> for Span {
775 fn into_spans(self) -> [Span; 1] {
776 [self]
777 }
778}
779
780impl IntoSpans<[Span; 2]> for Span {
781 fn into_spans(self) -> [Span; 2] {
782 [self, self]
783 }
784}
785
786impl IntoSpans<[Span; 3]> for Span {
787 fn into_spans(self) -> [Span; 3] {
788 [self, self, self]
789 }
790}
791
792impl IntoSpans<Self> for [Span; 1] {
793 fn into_spans(self) -> Self {
794 self
795 }
796}
797
798impl IntoSpans<Self> for [Span; 2] {
799 fn into_spans(self) -> Self {
800 self
801 }
802}
803
804impl IntoSpans<Self> for [Span; 3] {
805 fn into_spans(self) -> Self {
806 self
807 }
808}
809
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700810#[cfg(feature = "parsing")]
811mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500812 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700813
David Tolnaydfc886b2018-01-06 08:03:09 -0800814 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500815 use parse_error;
816 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700817
818 pub trait FromSpans: Sized {
819 fn from_spans(spans: &[Span]) -> Self;
820 }
821
822 impl FromSpans for [Span; 1] {
823 fn from_spans(spans: &[Span]) -> Self {
824 [spans[0]]
825 }
826 }
827
828 impl FromSpans for [Span; 2] {
829 fn from_spans(spans: &[Span]) -> Self {
830 [spans[0], spans[1]]
831 }
832 }
833
834 impl FromSpans for [Span; 3] {
835 fn from_spans(spans: &[Span]) -> Self {
836 [spans[0], spans[1], spans[2]]
837 }
838 }
839
David Tolnay2b069542018-05-09 12:59:36 -0700840 pub fn punct<'a, T, R>(s: &str, mut tokens: Cursor<'a>, new: fn(T) -> R) -> PResult<'a, R>
David Tolnay51382052017-12-27 13:46:21 -0500841 where
842 T: FromSpans,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700843 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700844 let mut spans = [Span::call_site(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700845 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700846 let chars = s.chars();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700847
Alex Crichton954046c2017-05-30 21:49:42 -0700848 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
David Tolnay55a5f3a2018-05-20 18:00:51 -0700849 match tokens.punct() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700850 Some((op, rest)) => {
851 if op.as_char() == ch {
852 if i != s.len() - 1 {
853 match op.spacing() {
854 Spacing::Joint => {}
855 _ => return parse_error(),
856 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400857 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700858 *slot = op.span();
859 tokens = rest;
860 } else {
David Tolnay65fb5662018-05-20 20:02:28 -0700861 return parse_error();
Michael Layzell0a1a6632017-06-02 18:07:43 -0400862 }
Alex Crichton954046c2017-05-30 21:49:42 -0700863 }
David Tolnay51382052017-12-27 13:46:21 -0500864 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700865 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700866 }
David Tolnay2b069542018-05-09 12:59:36 -0700867 Ok((new(T::from_spans(&spans)), tokens))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700868 }
869
David Tolnay65fb5662018-05-20 20:02:28 -0700870 pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> {
David Tolnaya4319b72018-06-02 00:49:15 -0700871 if let Some((ident, rest)) = tokens.ident() {
872 if ident == keyword {
873 return Ok((new(ident.span()), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400874 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700875 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400876 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700877 }
878
David Tolnay51382052017-12-27 13:46:21 -0500879 pub fn delim<'a, F, R, T>(
880 delim: &str,
881 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700882 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500883 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500884 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500885 where
886 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700887 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400888 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700889 let delim = match delim {
890 "(" => Delimiter::Parenthesis,
891 "{" => Delimiter::Brace,
892 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400893 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700894 _ => panic!("unknown delimiter: {}", delim),
895 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700896
David Tolnay65729482017-12-31 16:14:50 -0500897 if let Some((inside, span, rest)) = tokens.group(delim) {
898 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500899 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400900 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700901 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400902 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700903 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400904 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700905 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700906 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400907 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700908 }
909}
910
911#[cfg(feature = "printing")]
912mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700913 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700914 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700915
Alex Crichtona74a1c82018-05-16 10:20:44 -0700916 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700917 assert_eq!(s.len(), spans.len());
918
919 let mut chars = s.chars();
920 let mut spans = spans.iter();
921 let ch = chars.next_back().unwrap();
922 let span = spans.next_back().unwrap();
923 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700924 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700925 op.set_span(*span);
926 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700927 }
928
Alex Crichtona74a1c82018-05-16 10:20:44 -0700929 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700930 op.set_span(*span);
931 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700932 }
933
Alex Crichtona74a1c82018-05-16 10:20:44 -0700934 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
935 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700936 }
937
Alex Crichtona74a1c82018-05-16 10:20:44 -0700938 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500939 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700940 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700941 {
David Tolnay00ab6982017-12-31 18:15:06 -0500942 let delim = match s {
943 "(" => Delimiter::Parenthesis,
944 "[" => Delimiter::Bracket,
945 "{" => Delimiter::Brace,
946 " " => Delimiter::None,
947 _ => panic!("unknown delimiter: {}", s),
948 };
hcplaa511792018-05-29 07:13:01 +0300949 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500950 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700951 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700952 g.set_span(*span);
953 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700954 }
955}