blob: aa098c7d67033942e5f591f2e78151457183a27f [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 {
137 $name { spans: spans.into_spans() }
David Tolnay0bdb0552017-12-27 21:31:51 -0500138 }
139
David Tolnay66bb8d52018-01-08 08:22:31 -0800140 impl ::std::default::Default for $name {
141 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700142 $name([Span::call_site(); $len])
David Tolnay66bb8d52018-01-08 08:22:31 -0800143 }
144 }
145
Nika Layzelld73a3652017-10-24 08:57:05 -0400146 #[cfg(feature = "extra-traits")]
147 impl ::std::fmt::Debug for $name {
148 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
David Tolnay98942562017-12-26 21:24:35 -0500149 f.write_str(stringify!($name))
Nika Layzelld73a3652017-10-24 08:57:05 -0400150 }
151 }
152
David Tolnay98942562017-12-26 21:24:35 -0500153 #[cfg(feature = "extra-traits")]
154 impl ::std::cmp::Eq for $name {}
155
156 #[cfg(feature = "extra-traits")]
157 impl ::std::cmp::PartialEq for $name {
158 fn eq(&self, _other: &$name) -> bool {
159 true
160 }
161 }
162
163 #[cfg(feature = "extra-traits")]
164 impl ::std::hash::Hash for $name {
165 fn hash<H>(&self, _state: &mut H)
David Tolnay94d2b792018-04-29 12:26:10 -0700166 where
167 H: ::std::hash::Hasher,
168 {
169 }
David Tolnay98942562017-12-26 21:24:35 -0500170 }
171
Sergio Benitezd14d5362018-04-28 15:38:25 -0700172 impl From<Span> for $name {
173 fn from(span: Span) -> Self {
174 $name([span; $len])
175 }
176 }
David Tolnay94d2b792018-04-29 12:26:10 -0700177 };
Sergio Benitezd14d5362018-04-28 15:38:25 -0700178}
179
180macro_rules! token_punct_parser {
David Tolnay7ac699c2018-08-24 14:00:58 -0400181 ($s:tt pub struct $name:ident/$len:tt) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700182 #[cfg(feature = "printing")]
183 impl ::quote::ToTokens for $name {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700184 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
David Tolnay7ac699c2018-08-24 14:00:58 -0400185 printing::punct($s, &self.spans, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700186 }
187 }
188
189 #[cfg(feature = "parsing")]
190 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800191 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay7ac699c2018-08-24 14:00:58 -0400192 parsing::punct($s, tokens, $name::<[Span; $len]>)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700193 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800194
195 fn description() -> Option<&'static str> {
196 Some(concat!("`", $s, "`"))
197 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700198 }
David Tolnay94d2b792018-04-29 12:26:10 -0700199 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700200}
201
David Tolnay73c98de2017-12-31 15:56:56 -0500202macro_rules! token_keyword {
David Tolnay5a20f632017-12-26 22:11:28 -0500203 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700204 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500205 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800206 ///
207 /// Don't try to remember the name of this type -- use the [`Token!`]
208 /// macro instead.
209 ///
210 /// [`Token!`]: index.html
David Tolnay7ac699c2018-08-24 14:00:58 -0400211 pub struct $name {
212 pub span: Span,
213 }
214
215 #[doc(hidden)]
216 #[allow(non_snake_case)]
217 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
218 $name { span: span.into_spans()[0] }
219 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700220
David Tolnay66bb8d52018-01-08 08:22:31 -0800221 impl ::std::default::Default for $name {
222 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700223 $name(Span::call_site())
David Tolnay66bb8d52018-01-08 08:22:31 -0800224 }
225 }
226
David Tolnay98942562017-12-26 21:24:35 -0500227 #[cfg(feature = "extra-traits")]
228 impl ::std::fmt::Debug for $name {
229 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
230 f.write_str(stringify!($name))
231 }
232 }
233
234 #[cfg(feature = "extra-traits")]
235 impl ::std::cmp::Eq for $name {}
236
237 #[cfg(feature = "extra-traits")]
238 impl ::std::cmp::PartialEq for $name {
239 fn eq(&self, _other: &$name) -> bool {
240 true
241 }
242 }
243
244 #[cfg(feature = "extra-traits")]
245 impl ::std::hash::Hash for $name {
246 fn hash<H>(&self, _state: &mut H)
David Tolnay94d2b792018-04-29 12:26:10 -0700247 where
248 H: ::std::hash::Hasher,
249 {
250 }
David Tolnay98942562017-12-26 21:24:35 -0500251 }
252
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700253 #[cfg(feature = "printing")]
254 impl ::quote::ToTokens for $name {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700255 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
David Tolnay7ac699c2018-08-24 14:00:58 -0400256 printing::keyword($s, &self.span, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700257 }
258 }
259
260 #[cfg(feature = "parsing")]
261 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800262 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500263 parsing::keyword($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700264 }
David Tolnay79777332018-01-07 10:04:42 -0800265
266 fn description() -> Option<&'static str> {
267 Some(concat!("`", $s, "`"))
268 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700269 }
강동윤d5229da2018-01-12 13:11:33 +0900270
271 impl From<Span> for $name {
272 fn from(span: Span) -> Self {
273 $name(span)
274 }
275 }
David Tolnay94d2b792018-04-29 12:26:10 -0700276 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700277}
278
David Tolnay73c98de2017-12-31 15:56:56 -0500279macro_rules! token_delimiter {
David Tolnay5a20f632017-12-26 22:11:28 -0500280 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700281 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500282 #[$doc]
David Tolnay7ac699c2018-08-24 14:00:58 -0400283 pub struct $name {
284 pub span: Span,
285 }
286
287 #[doc(hidden)]
288 #[allow(non_snake_case)]
289 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
290 $name { span: span.into_spans()[0] }
291 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700292
David Tolnay66bb8d52018-01-08 08:22:31 -0800293 impl ::std::default::Default for $name {
294 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700295 $name(Span::call_site())
David Tolnay66bb8d52018-01-08 08:22:31 -0800296 }
297 }
298
David Tolnay98942562017-12-26 21:24:35 -0500299 #[cfg(feature = "extra-traits")]
300 impl ::std::fmt::Debug for $name {
301 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
302 f.write_str(stringify!($name))
303 }
304 }
305
306 #[cfg(feature = "extra-traits")]
307 impl ::std::cmp::Eq for $name {}
308
309 #[cfg(feature = "extra-traits")]
310 impl ::std::cmp::PartialEq for $name {
311 fn eq(&self, _other: &$name) -> bool {
312 true
313 }
314 }
315
316 #[cfg(feature = "extra-traits")]
317 impl ::std::hash::Hash for $name {
318 fn hash<H>(&self, _state: &mut H)
David Tolnay94d2b792018-04-29 12:26:10 -0700319 where
320 H: ::std::hash::Hasher,
321 {
322 }
David Tolnay98942562017-12-26 21:24:35 -0500323 }
324
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700325 impl $name {
326 #[cfg(feature = "printing")]
Alex Crichtona74a1c82018-05-16 10:20:44 -0700327 pub fn surround<F>(&self, tokens: &mut ::proc_macro2::TokenStream, f: F)
David Tolnay94d2b792018-04-29 12:26:10 -0700328 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700329 F: FnOnce(&mut ::proc_macro2::TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700330 {
David Tolnay7ac699c2018-08-24 14:00:58 -0400331 printing::delim($s, &self.span, tokens, f);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700332 }
333
334 #[cfg(feature = "parsing")]
David Tolnay94d2b792018-04-29 12:26:10 -0700335 pub fn parse<F, R>(
336 tokens: $crate::buffer::Cursor,
337 f: F,
338 ) -> $crate::synom::PResult<($name, R)>
339 where
340 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700341 {
342 parsing::delim($s, tokens, $name, f)
343 }
344 }
강동윤d5229da2018-01-12 13:11:33 +0900345
346 impl From<Span> for $name {
347 fn from(span: Span) -> Self {
348 $name(span)
349 }
350 }
David Tolnay94d2b792018-04-29 12:26:10 -0700351 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700352}
353
Sergio Benitezd14d5362018-04-28 15:38:25 -0700354token_punct_def! {
355 /// `_`
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700356 pub struct Underscore/1
Sergio Benitezd14d5362018-04-28 15:38:25 -0700357}
358
359#[cfg(feature = "printing")]
360impl ::quote::ToTokens for Underscore {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700361 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
362 use quote::TokenStreamExt;
David Tolnay7ac699c2018-08-24 14:00:58 -0400363 tokens.append(::proc_macro2::Ident::new("_", self.spans[0]));
Sergio Benitezd14d5362018-04-28 15:38:25 -0700364 }
365}
366
367#[cfg(feature = "parsing")]
368impl ::Synom for Underscore {
369 fn parse(input: ::buffer::Cursor) -> ::synom::PResult<Underscore> {
David Tolnay55a5f3a2018-05-20 18:00:51 -0700370 match input.ident() {
David Tolnaya4319b72018-06-02 00:49:15 -0700371 Some((ident, rest)) => {
372 if ident == "_" {
373 Ok((Underscore([ident.span()]), rest))
Alex Crichtona74a1c82018-05-16 10:20:44 -0700374 } else {
375 ::parse_error()
376 }
377 }
David Tolnay7ac699c2018-08-24 14:00:58 -0400378 None => parsing::punct("_", input, Underscore::<[Span; 1]>),
Sergio Benitezd14d5362018-04-28 15:38:25 -0700379 }
380 }
381
382 fn description() -> Option<&'static str> {
383 Some("`_`")
384 }
385}
386
Alex Crichton131308c2018-05-18 14:00:24 -0700387token_punct_def! {
388 /// `'`
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700389 pub struct Apostrophe/1
Alex Crichton131308c2018-05-18 14:00:24 -0700390}
391
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700392// Implement Clone anyway because it is required for cloning Lifetime.
393#[cfg(not(feature = "clone-impls"))]
394impl Clone for Apostrophe {
395 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400396 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700397 }
398}
399
Alex Crichton131308c2018-05-18 14:00:24 -0700400#[cfg(feature = "printing")]
401impl ::quote::ToTokens for Apostrophe {
402 fn to_tokens(&self, tokens: &mut ::proc_macro2::TokenStream) {
403 use quote::TokenStreamExt;
404 let mut token = ::proc_macro2::Punct::new('\'', ::proc_macro2::Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400405 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700406 tokens.append(token);
407 }
408}
409
410#[cfg(feature = "parsing")]
411impl ::Synom for Apostrophe {
412 fn parse(input: ::buffer::Cursor) -> ::synom::PResult<Apostrophe> {
David Tolnay55a5f3a2018-05-20 18:00:51 -0700413 match input.punct() {
Alex Crichton131308c2018-05-18 14:00:24 -0700414 Some((op, rest)) => {
415 if op.as_char() == '\'' && op.spacing() == ::proc_macro2::Spacing::Joint {
416 Ok((Apostrophe([op.span()]), rest))
417 } else {
418 ::parse_error()
419 }
420 }
David Tolnay65fb5662018-05-20 20:02:28 -0700421 None => ::parse_error(),
Alex Crichton131308c2018-05-18 14:00:24 -0700422 }
423 }
424
425 fn description() -> Option<&'static str> {
426 Some("`'`")
427 }
428}
429
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700430tokens! {
David Tolnay73c98de2017-12-31 15:56:56 -0500431 punct: {
David Tolnay5a20f632017-12-26 22:11:28 -0500432 "+" pub struct Add/1 /// `+`
433 "+=" pub struct AddEq/2 /// `+=`
434 "&" pub struct And/1 /// `&`
435 "&&" pub struct AndAnd/2 /// `&&`
436 "&=" pub struct AndEq/2 /// `&=`
437 "@" pub struct At/1 /// `@`
438 "!" pub struct Bang/1 /// `!`
439 "^" pub struct Caret/1 /// `^`
David Tolnay32954ef2017-12-26 22:43:16 -0500440 "^=" pub struct CaretEq/2 /// `^=`
David Tolnay5a20f632017-12-26 22:11:28 -0500441 ":" pub struct Colon/1 /// `:`
442 "::" pub struct Colon2/2 /// `::`
443 "," pub struct Comma/1 /// `,`
444 "/" pub struct Div/1 /// `/`
445 "/=" pub struct DivEq/2 /// `/=`
MSleepyPandaf5137d72018-05-05 18:57:10 +0200446 "$" pub struct Dollar/1 /// `$`
David Tolnay5a20f632017-12-26 22:11:28 -0500447 "." pub struct Dot/1 /// `.`
448 ".." pub struct Dot2/2 /// `..`
449 "..." pub struct Dot3/3 /// `...`
450 "..=" pub struct DotDotEq/3 /// `..=`
451 "=" pub struct Eq/1 /// `=`
452 "==" pub struct EqEq/2 /// `==`
453 ">=" pub struct Ge/2 /// `>=`
454 ">" pub struct Gt/1 /// `>`
455 "<=" pub struct Le/2 /// `<=`
456 "<" pub struct Lt/1 /// `<`
457 "*=" pub struct MulEq/2 /// `*=`
458 "!=" pub struct Ne/2 /// `!=`
459 "|" pub struct Or/1 /// `|`
460 "|=" pub struct OrEq/2 /// `|=`
461 "||" pub struct OrOr/2 /// `||`
462 "#" pub struct Pound/1 /// `#`
463 "?" pub struct Question/1 /// `?`
464 "->" pub struct RArrow/2 /// `->`
465 "<-" pub struct LArrow/2 /// `<-`
466 "%" pub struct Rem/1 /// `%`
467 "%=" pub struct RemEq/2 /// `%=`
David Tolnay17624152018-03-31 18:11:40 +0200468 "=>" pub struct FatArrow/2 /// `=>`
David Tolnay5a20f632017-12-26 22:11:28 -0500469 ";" pub struct Semi/1 /// `;`
470 "<<" pub struct Shl/2 /// `<<`
471 "<<=" pub struct ShlEq/3 /// `<<=`
472 ">>" pub struct Shr/2 /// `>>`
473 ">>=" pub struct ShrEq/3 /// `>>=`
474 "*" pub struct Star/1 /// `*`
475 "-" pub struct Sub/1 /// `-`
476 "-=" pub struct SubEq/2 /// `-=`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700477 }
David Tolnay73c98de2017-12-31 15:56:56 -0500478 delimiter: {
David Tolnay5a20f632017-12-26 22:11:28 -0500479 "{" pub struct Brace /// `{...}`
480 "[" pub struct Bracket /// `[...]`
481 "(" pub struct Paren /// `(...)`
482 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700483 }
David Tolnay73c98de2017-12-31 15:56:56 -0500484 keyword: {
David Tolnay5a20f632017-12-26 22:11:28 -0500485 "as" pub struct As /// `as`
David Tolnayac740722018-07-31 22:08:58 -0700486 "async" pub struct Async /// `async`
David Tolnay5a20f632017-12-26 22:11:28 -0500487 "auto" pub struct Auto /// `auto`
488 "box" pub struct Box /// `box`
489 "break" pub struct Break /// `break`
490 "Self" pub struct CapSelf /// `Self`
491 "catch" pub struct Catch /// `catch`
492 "const" pub struct Const /// `const`
493 "continue" pub struct Continue /// `continue`
494 "crate" pub struct Crate /// `crate`
495 "default" pub struct Default /// `default`
496 "do" pub struct Do /// `do`
497 "dyn" pub struct Dyn /// `dyn`
498 "else" pub struct Else /// `else`
499 "enum" pub struct Enum /// `enum`
500 "extern" pub struct Extern /// `extern`
501 "fn" pub struct Fn /// `fn`
502 "for" pub struct For /// `for`
503 "if" pub struct If /// `if`
504 "impl" pub struct Impl /// `impl`
505 "in" pub struct In /// `in`
506 "let" pub struct Let /// `let`
507 "loop" pub struct Loop /// `loop`
508 "macro" pub struct Macro /// `macro`
509 "match" pub struct Match /// `match`
510 "mod" pub struct Mod /// `mod`
511 "move" pub struct Move /// `move`
512 "mut" pub struct Mut /// `mut`
513 "pub" pub struct Pub /// `pub`
514 "ref" pub struct Ref /// `ref`
515 "return" pub struct Return /// `return`
516 "self" pub struct Self_ /// `self`
517 "static" pub struct Static /// `static`
518 "struct" pub struct Struct /// `struct`
519 "super" pub struct Super /// `super`
520 "trait" pub struct Trait /// `trait`
David Tolnayf7177052018-08-24 15:31:50 -0400521 "try" pub struct Try /// `try`
David Tolnay5a20f632017-12-26 22:11:28 -0500522 "type" pub struct Type /// `type`
523 "union" pub struct Union /// `union`
524 "unsafe" pub struct Unsafe /// `unsafe`
525 "use" pub struct Use /// `use`
526 "where" pub struct Where /// `where`
527 "while" pub struct While /// `while`
528 "yield" pub struct Yield /// `yield`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700529 }
530}
531
David Tolnayf005f962018-01-06 21:19:41 -0800532/// A type-macro that expands to the name of the Rust type representation of a
533/// given token.
534///
535/// See the [token module] documentation for details and examples.
536///
537/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800538// Unfortunate duplication due to a rustdoc bug.
539// https://github.com/rust-lang/rust/issues/45939
540#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700541#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800542macro_rules! Token {
David Tolnay32954ef2017-12-26 22:43:16 -0500543 (+) => { $crate::token::Add };
544 (+=) => { $crate::token::AddEq };
545 (&) => { $crate::token::And };
546 (&&) => { $crate::token::AndAnd };
547 (&=) => { $crate::token::AndEq };
548 (@) => { $crate::token::At };
549 (!) => { $crate::token::Bang };
550 (^) => { $crate::token::Caret };
551 (^=) => { $crate::token::CaretEq };
552 (:) => { $crate::token::Colon };
553 (::) => { $crate::token::Colon2 };
554 (,) => { $crate::token::Comma };
555 (/) => { $crate::token::Div };
556 (/=) => { $crate::token::DivEq };
557 (.) => { $crate::token::Dot };
558 (..) => { $crate::token::Dot2 };
559 (...) => { $crate::token::Dot3 };
560 (..=) => { $crate::token::DotDotEq };
561 (=) => { $crate::token::Eq };
562 (==) => { $crate::token::EqEq };
563 (>=) => { $crate::token::Ge };
564 (>) => { $crate::token::Gt };
565 (<=) => { $crate::token::Le };
566 (<) => { $crate::token::Lt };
567 (*=) => { $crate::token::MulEq };
568 (!=) => { $crate::token::Ne };
569 (|) => { $crate::token::Or };
570 (|=) => { $crate::token::OrEq };
571 (||) => { $crate::token::OrOr };
572 (#) => { $crate::token::Pound };
573 (?) => { $crate::token::Question };
574 (->) => { $crate::token::RArrow };
575 (<-) => { $crate::token::LArrow };
576 (%) => { $crate::token::Rem };
577 (%=) => { $crate::token::RemEq };
David Tolnay17624152018-03-31 18:11:40 +0200578 (=>) => { $crate::token::FatArrow };
David Tolnay32954ef2017-12-26 22:43:16 -0500579 (;) => { $crate::token::Semi };
580 (<<) => { $crate::token::Shl };
581 (<<=) => { $crate::token::ShlEq };
582 (>>) => { $crate::token::Shr };
583 (>>=) => { $crate::token::ShrEq };
584 (*) => { $crate::token::Star };
585 (-) => { $crate::token::Sub };
586 (-=) => { $crate::token::SubEq };
587 (_) => { $crate::token::Underscore };
588 (as) => { $crate::token::As };
David Tolnayac740722018-07-31 22:08:58 -0700589 (async) => { $crate::token::Async };
David Tolnay32954ef2017-12-26 22:43:16 -0500590 (auto) => { $crate::token::Auto };
591 (box) => { $crate::token::Box };
592 (break) => { $crate::token::Break };
593 (Self) => { $crate::token::CapSelf };
594 (catch) => { $crate::token::Catch };
595 (const) => { $crate::token::Const };
596 (continue) => { $crate::token::Continue };
597 (crate) => { $crate::token::Crate };
598 (default) => { $crate::token::Default };
599 (do) => { $crate::token::Do };
600 (dyn) => { $crate::token::Dyn };
601 (else) => { $crate::token::Else };
602 (enum) => { $crate::token::Enum };
603 (extern) => { $crate::token::Extern };
604 (fn) => { $crate::token::Fn };
605 (for) => { $crate::token::For };
606 (if) => { $crate::token::If };
607 (impl) => { $crate::token::Impl };
608 (in) => { $crate::token::In };
609 (let) => { $crate::token::Let };
610 (loop) => { $crate::token::Loop };
611 (macro) => { $crate::token::Macro };
612 (match) => { $crate::token::Match };
613 (mod) => { $crate::token::Mod };
614 (move) => { $crate::token::Move };
615 (mut) => { $crate::token::Mut };
616 (pub) => { $crate::token::Pub };
617 (ref) => { $crate::token::Ref };
618 (return) => { $crate::token::Return };
619 (self) => { $crate::token::Self_ };
620 (static) => { $crate::token::Static };
621 (struct) => { $crate::token::Struct };
622 (super) => { $crate::token::Super };
623 (trait) => { $crate::token::Trait };
David Tolnayf7177052018-08-24 15:31:50 -0400624 (try) => { $crate::token::Try };
David Tolnay32954ef2017-12-26 22:43:16 -0500625 (type) => { $crate::token::Type };
626 (union) => { $crate::token::Union };
627 (unsafe) => { $crate::token::Unsafe };
628 (use) => { $crate::token::Use };
629 (where) => { $crate::token::Where };
630 (while) => { $crate::token::While };
631 (yield) => { $crate::token::Yield };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800632}
633
David Tolnayf005f962018-01-06 21:19:41 -0800634/// Parse a single Rust punctuation token.
635///
636/// See the [token module] documentation for details and examples.
637///
638/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800639///
640/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500641#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800642#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700643#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800644macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500645 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
646 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
647 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
648 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
649 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
650 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
651 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
652 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
653 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
654 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
655 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
656 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
657 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
658 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
659 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
660 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
661 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
662 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
663 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
664 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
665 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
666 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
667 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
668 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
669 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
670 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
671 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
672 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
673 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
674 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
675 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
676 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
677 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
678 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
679 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200680 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500681 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
682 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
683 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
684 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
685 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
686 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
687 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
688 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
689 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800690}
691
David Tolnayf005f962018-01-06 21:19:41 -0800692/// Parse a single Rust keyword token.
693///
694/// See the [token module] documentation for details and examples.
695///
696/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800697///
698/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500699#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800700#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700701#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800702macro_rules! keyword {
David Tolnay32954ef2017-12-26 22:43:16 -0500703 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
David Tolnayac740722018-07-31 22:08:58 -0700704 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500705 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
706 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
707 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
708 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
709 ($i:expr, catch) => { call!($i, <$crate::token::Catch as $crate::synom::Synom>::parse) };
710 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
711 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
712 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
713 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
714 ($i:expr, do) => { call!($i, <$crate::token::Do as $crate::synom::Synom>::parse) };
715 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
716 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
717 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
718 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
719 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
720 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
721 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
722 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
723 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
724 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
725 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
726 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
727 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
728 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
729 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
730 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
731 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
732 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
733 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
734 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
735 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
736 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
737 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
738 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
David Tolnayf7177052018-08-24 15:31:50 -0400739 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500740 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
741 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
742 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
743 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
744 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
745 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
746 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800747}
748
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700749macro_rules! ident_from_token {
750 ($token:ident) => {
751 impl From<Token![$token]> for Ident {
752 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400753 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700754 }
755 }
756 };
757}
758
759ident_from_token!(self);
760ident_from_token!(Self);
761ident_from_token!(super);
762ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700763ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700764
David Tolnay7ac699c2018-08-24 14:00:58 -0400765// Not public API.
766#[doc(hidden)]
767pub trait IntoSpans<S> {
768 fn into_spans(self) -> S;
769}
770
771impl IntoSpans<[Span; 1]> for Span {
772 fn into_spans(self) -> [Span; 1] {
773 [self]
774 }
775}
776
777impl IntoSpans<[Span; 2]> for Span {
778 fn into_spans(self) -> [Span; 2] {
779 [self, self]
780 }
781}
782
783impl IntoSpans<[Span; 3]> for Span {
784 fn into_spans(self) -> [Span; 3] {
785 [self, self, self]
786 }
787}
788
789impl IntoSpans<Self> for [Span; 1] {
790 fn into_spans(self) -> Self {
791 self
792 }
793}
794
795impl IntoSpans<Self> for [Span; 2] {
796 fn into_spans(self) -> Self {
797 self
798 }
799}
800
801impl IntoSpans<Self> for [Span; 3] {
802 fn into_spans(self) -> Self {
803 self
804 }
805}
806
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700807#[cfg(feature = "parsing")]
808mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500809 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700810
David Tolnaydfc886b2018-01-06 08:03:09 -0800811 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500812 use parse_error;
813 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700814
815 pub trait FromSpans: Sized {
816 fn from_spans(spans: &[Span]) -> Self;
817 }
818
819 impl FromSpans for [Span; 1] {
820 fn from_spans(spans: &[Span]) -> Self {
821 [spans[0]]
822 }
823 }
824
825 impl FromSpans for [Span; 2] {
826 fn from_spans(spans: &[Span]) -> Self {
827 [spans[0], spans[1]]
828 }
829 }
830
831 impl FromSpans for [Span; 3] {
832 fn from_spans(spans: &[Span]) -> Self {
833 [spans[0], spans[1], spans[2]]
834 }
835 }
836
David Tolnay2b069542018-05-09 12:59:36 -0700837 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 -0500838 where
839 T: FromSpans,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700840 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700841 let mut spans = [Span::call_site(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700842 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700843 let chars = s.chars();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700844
Alex Crichton954046c2017-05-30 21:49:42 -0700845 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
David Tolnay55a5f3a2018-05-20 18:00:51 -0700846 match tokens.punct() {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700847 Some((op, rest)) => {
848 if op.as_char() == ch {
849 if i != s.len() - 1 {
850 match op.spacing() {
851 Spacing::Joint => {}
852 _ => return parse_error(),
853 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400854 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700855 *slot = op.span();
856 tokens = rest;
857 } else {
David Tolnay65fb5662018-05-20 20:02:28 -0700858 return parse_error();
Michael Layzell0a1a6632017-06-02 18:07:43 -0400859 }
Alex Crichton954046c2017-05-30 21:49:42 -0700860 }
David Tolnay51382052017-12-27 13:46:21 -0500861 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700862 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700863 }
David Tolnay2b069542018-05-09 12:59:36 -0700864 Ok((new(T::from_spans(&spans)), tokens))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700865 }
866
David Tolnay65fb5662018-05-20 20:02:28 -0700867 pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> {
David Tolnaya4319b72018-06-02 00:49:15 -0700868 if let Some((ident, rest)) = tokens.ident() {
869 if ident == keyword {
870 return Ok((new(ident.span()), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400871 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700872 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400873 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700874 }
875
David Tolnay51382052017-12-27 13:46:21 -0500876 pub fn delim<'a, F, R, T>(
877 delim: &str,
878 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700879 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500880 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500881 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500882 where
883 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700884 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400885 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700886 let delim = match delim {
887 "(" => Delimiter::Parenthesis,
888 "{" => Delimiter::Brace,
889 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400890 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700891 _ => panic!("unknown delimiter: {}", delim),
892 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700893
David Tolnay65729482017-12-31 16:14:50 -0500894 if let Some((inside, span, rest)) = tokens.group(delim) {
895 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500896 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400897 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700898 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400899 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700900 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400901 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700902 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700903 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400904 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700905 }
906}
907
908#[cfg(feature = "printing")]
909mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700910 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700911 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700912
Alex Crichtona74a1c82018-05-16 10:20:44 -0700913 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700914 assert_eq!(s.len(), spans.len());
915
916 let mut chars = s.chars();
917 let mut spans = spans.iter();
918 let ch = chars.next_back().unwrap();
919 let span = spans.next_back().unwrap();
920 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700921 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700922 op.set_span(*span);
923 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700924 }
925
Alex Crichtona74a1c82018-05-16 10:20:44 -0700926 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700927 op.set_span(*span);
928 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700929 }
930
Alex Crichtona74a1c82018-05-16 10:20:44 -0700931 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
932 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700933 }
934
Alex Crichtona74a1c82018-05-16 10:20:44 -0700935 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500936 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700937 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700938 {
David Tolnay00ab6982017-12-31 18:15:06 -0500939 let delim = match s {
940 "(" => Delimiter::Parenthesis,
941 "[" => Delimiter::Bracket,
942 "{" => Delimiter::Brace,
943 " " => Delimiter::None,
944 _ => panic!("unknown delimiter: {}", s),
945 };
hcplaa511792018-05-29 07:13:01 +0300946 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500947 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700948 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700949 g.set_span(*span);
950 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700951 }
952}