blob: 081ae1e2ef2c3da5562182f586f59cac23224931 [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//! #
27//! # use syn::{Attribute, Visibility, Ident, Type, Expr};
28//! #
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;
63//! use syn::{Attribute, Visibility, Ident, Type, Expr};
64//! #
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 Tolnay98942562017-12-26 21:24:35 -0500100use proc_macro2::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 ) => (
Sergio Benitezd14d5362018-04-28 15:38:25 -0700114 $(token_punct_def! { #[$punct_doc] $punct pub struct $punct_name/$len })*
115 $(token_punct_parser! { $punct pub struct $punct_name })*
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 Tolnay5a20f632017-12-26 22:11:28 -0500122 (#[$doc:meta] $s:tt 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 Tolnay5a20f632017-12-26 22:11:28 -0500130 pub struct $name(pub [Span; $len]);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700131
David Tolnay0bdb0552017-12-27 21:31:51 -0500132 impl $name {
133 pub fn new(span: Span) -> Self {
134 $name([span; $len])
135 }
136 }
137
David Tolnay66bb8d52018-01-08 08:22:31 -0800138 impl ::std::default::Default for $name {
139 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700140 $name([Span::call_site(); $len])
David Tolnay66bb8d52018-01-08 08:22:31 -0800141 }
142 }
143
Nika Layzelld73a3652017-10-24 08:57:05 -0400144 #[cfg(feature = "extra-traits")]
145 impl ::std::fmt::Debug for $name {
146 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
David Tolnay98942562017-12-26 21:24:35 -0500147 f.write_str(stringify!($name))
Nika Layzelld73a3652017-10-24 08:57:05 -0400148 }
149 }
150
David Tolnay98942562017-12-26 21:24:35 -0500151 #[cfg(feature = "extra-traits")]
152 impl ::std::cmp::Eq for $name {}
153
154 #[cfg(feature = "extra-traits")]
155 impl ::std::cmp::PartialEq for $name {
156 fn eq(&self, _other: &$name) -> bool {
157 true
158 }
159 }
160
161 #[cfg(feature = "extra-traits")]
162 impl ::std::hash::Hash for $name {
163 fn hash<H>(&self, _state: &mut H)
164 where H: ::std::hash::Hasher
165 {}
166 }
167
Sergio Benitezd14d5362018-04-28 15:38:25 -0700168 impl From<Span> for $name {
169 fn from(span: Span) -> Self {
170 $name([span; $len])
171 }
172 }
173 }
174}
175
176macro_rules! token_punct_parser {
177 ($s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700178 #[cfg(feature = "printing")]
179 impl ::quote::ToTokens for $name {
180 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500181 printing::punct($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700182 }
183 }
184
185 #[cfg(feature = "parsing")]
186 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800187 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500188 parsing::punct($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700189 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800190
191 fn description() -> Option<&'static str> {
192 Some(concat!("`", $s, "`"))
193 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700194 }
195 }
196}
197
David Tolnay73c98de2017-12-31 15:56:56 -0500198macro_rules! token_keyword {
David Tolnay5a20f632017-12-26 22:11:28 -0500199 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700200 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500201 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800202 ///
203 /// Don't try to remember the name of this type -- use the [`Token!`]
204 /// macro instead.
205 ///
206 /// [`Token!`]: index.html
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700207 pub struct $name(pub Span);
208
David Tolnay66bb8d52018-01-08 08:22:31 -0800209 impl ::std::default::Default for $name {
210 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700211 $name(Span::call_site())
David Tolnay66bb8d52018-01-08 08:22:31 -0800212 }
213 }
214
David Tolnay98942562017-12-26 21:24:35 -0500215 #[cfg(feature = "extra-traits")]
216 impl ::std::fmt::Debug for $name {
217 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
218 f.write_str(stringify!($name))
219 }
220 }
221
222 #[cfg(feature = "extra-traits")]
223 impl ::std::cmp::Eq for $name {}
224
225 #[cfg(feature = "extra-traits")]
226 impl ::std::cmp::PartialEq for $name {
227 fn eq(&self, _other: &$name) -> bool {
228 true
229 }
230 }
231
232 #[cfg(feature = "extra-traits")]
233 impl ::std::hash::Hash for $name {
234 fn hash<H>(&self, _state: &mut H)
235 where H: ::std::hash::Hasher
236 {}
237 }
238
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700239 #[cfg(feature = "printing")]
240 impl ::quote::ToTokens for $name {
241 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500242 printing::keyword($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700243 }
244 }
245
246 #[cfg(feature = "parsing")]
247 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800248 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500249 parsing::keyword($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700250 }
David Tolnay79777332018-01-07 10:04:42 -0800251
252 fn description() -> Option<&'static str> {
253 Some(concat!("`", $s, "`"))
254 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700255 }
강동윤d5229da2018-01-12 13:11:33 +0900256
257 impl From<Span> for $name {
258 fn from(span: Span) -> Self {
259 $name(span)
260 }
261 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700262 }
263}
264
David Tolnay73c98de2017-12-31 15:56:56 -0500265macro_rules! token_delimiter {
David Tolnay5a20f632017-12-26 22:11:28 -0500266 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700267 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500268 #[$doc]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700269 pub struct $name(pub Span);
270
David Tolnay66bb8d52018-01-08 08:22:31 -0800271 impl ::std::default::Default for $name {
272 fn default() -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700273 $name(Span::call_site())
David Tolnay66bb8d52018-01-08 08:22:31 -0800274 }
275 }
276
David Tolnay98942562017-12-26 21:24:35 -0500277 #[cfg(feature = "extra-traits")]
278 impl ::std::fmt::Debug for $name {
279 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
280 f.write_str(stringify!($name))
281 }
282 }
283
284 #[cfg(feature = "extra-traits")]
285 impl ::std::cmp::Eq for $name {}
286
287 #[cfg(feature = "extra-traits")]
288 impl ::std::cmp::PartialEq for $name {
289 fn eq(&self, _other: &$name) -> bool {
290 true
291 }
292 }
293
294 #[cfg(feature = "extra-traits")]
295 impl ::std::hash::Hash for $name {
296 fn hash<H>(&self, _state: &mut H)
297 where H: ::std::hash::Hasher
298 {}
299 }
300
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700301 impl $name {
302 #[cfg(feature = "printing")]
303 pub fn surround<F>(&self,
304 tokens: &mut ::quote::Tokens,
305 f: F)
306 where F: FnOnce(&mut ::quote::Tokens)
307 {
308 printing::delim($s, &self.0, tokens, f);
309 }
310
311 #[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800312 pub fn parse<F, R>(tokens: $crate::buffer::Cursor, f: F) -> $crate::synom::PResult<($name, R)>
313 where F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700314 {
315 parsing::delim($s, tokens, $name, f)
316 }
317 }
강동윤d5229da2018-01-12 13:11:33 +0900318
319 impl From<Span> for $name {
320 fn from(span: Span) -> Self {
321 $name(span)
322 }
323 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700324 }
325}
326
Sergio Benitezd14d5362018-04-28 15:38:25 -0700327token_punct_def! {
328 /// `_`
329 "_" pub struct Underscore/1
330}
331
332#[cfg(feature = "printing")]
333impl ::quote::ToTokens for Underscore {
334 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
335 // FIXME: This should really be the following (see #408):
336 // tokens.append(::proc_macro2::Term::new("_", self.0[0]));
337 printing::punct("_", &self.0, tokens);
338 }
339}
340
341#[cfg(feature = "parsing")]
342impl ::Synom for Underscore {
343 fn parse(input: ::buffer::Cursor) -> ::synom::PResult<Underscore> {
344 match input.term() {
345 Some((term, rest)) if term.as_str() == "_" => {
346 Ok((Underscore([term.span()]), rest))
347 }
348 Some(_) => ::parse_error(),
349 None => parsing::punct("_", input, Underscore)
350 }
351 }
352
353 fn description() -> Option<&'static str> {
354 Some("`_`")
355 }
356}
357
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700358tokens! {
David Tolnay73c98de2017-12-31 15:56:56 -0500359 punct: {
David Tolnay5a20f632017-12-26 22:11:28 -0500360 "+" pub struct Add/1 /// `+`
361 "+=" pub struct AddEq/2 /// `+=`
362 "&" pub struct And/1 /// `&`
363 "&&" pub struct AndAnd/2 /// `&&`
364 "&=" pub struct AndEq/2 /// `&=`
365 "@" pub struct At/1 /// `@`
366 "!" pub struct Bang/1 /// `!`
367 "^" pub struct Caret/1 /// `^`
David Tolnay32954ef2017-12-26 22:43:16 -0500368 "^=" pub struct CaretEq/2 /// `^=`
David Tolnay5a20f632017-12-26 22:11:28 -0500369 ":" pub struct Colon/1 /// `:`
370 "::" pub struct Colon2/2 /// `::`
371 "," pub struct Comma/1 /// `,`
372 "/" pub struct Div/1 /// `/`
373 "/=" pub struct DivEq/2 /// `/=`
374 "." pub struct Dot/1 /// `.`
375 ".." pub struct Dot2/2 /// `..`
376 "..." pub struct Dot3/3 /// `...`
377 "..=" pub struct DotDotEq/3 /// `..=`
378 "=" pub struct Eq/1 /// `=`
379 "==" pub struct EqEq/2 /// `==`
380 ">=" pub struct Ge/2 /// `>=`
381 ">" pub struct Gt/1 /// `>`
382 "<=" pub struct Le/2 /// `<=`
383 "<" pub struct Lt/1 /// `<`
384 "*=" pub struct MulEq/2 /// `*=`
385 "!=" pub struct Ne/2 /// `!=`
386 "|" pub struct Or/1 /// `|`
387 "|=" pub struct OrEq/2 /// `|=`
388 "||" pub struct OrOr/2 /// `||`
389 "#" pub struct Pound/1 /// `#`
390 "?" pub struct Question/1 /// `?`
391 "->" pub struct RArrow/2 /// `->`
392 "<-" pub struct LArrow/2 /// `<-`
393 "%" pub struct Rem/1 /// `%`
394 "%=" pub struct RemEq/2 /// `%=`
David Tolnay17624152018-03-31 18:11:40 +0200395 "=>" pub struct FatArrow/2 /// `=>`
David Tolnay5a20f632017-12-26 22:11:28 -0500396 ";" pub struct Semi/1 /// `;`
397 "<<" pub struct Shl/2 /// `<<`
398 "<<=" pub struct ShlEq/3 /// `<<=`
399 ">>" pub struct Shr/2 /// `>>`
400 ">>=" pub struct ShrEq/3 /// `>>=`
401 "*" pub struct Star/1 /// `*`
402 "-" pub struct Sub/1 /// `-`
403 "-=" pub struct SubEq/2 /// `-=`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700404 }
David Tolnay73c98de2017-12-31 15:56:56 -0500405 delimiter: {
David Tolnay5a20f632017-12-26 22:11:28 -0500406 "{" pub struct Brace /// `{...}`
407 "[" pub struct Bracket /// `[...]`
408 "(" pub struct Paren /// `(...)`
409 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700410 }
David Tolnay73c98de2017-12-31 15:56:56 -0500411 keyword: {
David Tolnay5a20f632017-12-26 22:11:28 -0500412 "as" pub struct As /// `as`
413 "auto" pub struct Auto /// `auto`
414 "box" pub struct Box /// `box`
415 "break" pub struct Break /// `break`
416 "Self" pub struct CapSelf /// `Self`
417 "catch" pub struct Catch /// `catch`
418 "const" pub struct Const /// `const`
419 "continue" pub struct Continue /// `continue`
420 "crate" pub struct Crate /// `crate`
421 "default" pub struct Default /// `default`
422 "do" pub struct Do /// `do`
423 "dyn" pub struct Dyn /// `dyn`
424 "else" pub struct Else /// `else`
425 "enum" pub struct Enum /// `enum`
426 "extern" pub struct Extern /// `extern`
427 "fn" pub struct Fn /// `fn`
428 "for" pub struct For /// `for`
429 "if" pub struct If /// `if`
430 "impl" pub struct Impl /// `impl`
431 "in" pub struct In /// `in`
432 "let" pub struct Let /// `let`
433 "loop" pub struct Loop /// `loop`
434 "macro" pub struct Macro /// `macro`
435 "match" pub struct Match /// `match`
436 "mod" pub struct Mod /// `mod`
437 "move" pub struct Move /// `move`
438 "mut" pub struct Mut /// `mut`
439 "pub" pub struct Pub /// `pub`
440 "ref" pub struct Ref /// `ref`
441 "return" pub struct Return /// `return`
442 "self" pub struct Self_ /// `self`
443 "static" pub struct Static /// `static`
444 "struct" pub struct Struct /// `struct`
445 "super" pub struct Super /// `super`
446 "trait" pub struct Trait /// `trait`
447 "type" pub struct Type /// `type`
448 "union" pub struct Union /// `union`
449 "unsafe" pub struct Unsafe /// `unsafe`
450 "use" pub struct Use /// `use`
451 "where" pub struct Where /// `where`
452 "while" pub struct While /// `while`
453 "yield" pub struct Yield /// `yield`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700454 }
455}
456
David Tolnayf005f962018-01-06 21:19:41 -0800457/// A type-macro that expands to the name of the Rust type representation of a
458/// given token.
459///
460/// See the [token module] documentation for details and examples.
461///
462/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800463// Unfortunate duplication due to a rustdoc bug.
464// https://github.com/rust-lang/rust/issues/45939
465#[macro_export]
466macro_rules! Token {
David Tolnay32954ef2017-12-26 22:43:16 -0500467 (+) => { $crate::token::Add };
468 (+=) => { $crate::token::AddEq };
469 (&) => { $crate::token::And };
470 (&&) => { $crate::token::AndAnd };
471 (&=) => { $crate::token::AndEq };
472 (@) => { $crate::token::At };
473 (!) => { $crate::token::Bang };
474 (^) => { $crate::token::Caret };
475 (^=) => { $crate::token::CaretEq };
476 (:) => { $crate::token::Colon };
477 (::) => { $crate::token::Colon2 };
478 (,) => { $crate::token::Comma };
479 (/) => { $crate::token::Div };
480 (/=) => { $crate::token::DivEq };
481 (.) => { $crate::token::Dot };
482 (..) => { $crate::token::Dot2 };
483 (...) => { $crate::token::Dot3 };
484 (..=) => { $crate::token::DotDotEq };
485 (=) => { $crate::token::Eq };
486 (==) => { $crate::token::EqEq };
487 (>=) => { $crate::token::Ge };
488 (>) => { $crate::token::Gt };
489 (<=) => { $crate::token::Le };
490 (<) => { $crate::token::Lt };
491 (*=) => { $crate::token::MulEq };
492 (!=) => { $crate::token::Ne };
493 (|) => { $crate::token::Or };
494 (|=) => { $crate::token::OrEq };
495 (||) => { $crate::token::OrOr };
496 (#) => { $crate::token::Pound };
497 (?) => { $crate::token::Question };
498 (->) => { $crate::token::RArrow };
499 (<-) => { $crate::token::LArrow };
500 (%) => { $crate::token::Rem };
501 (%=) => { $crate::token::RemEq };
David Tolnay17624152018-03-31 18:11:40 +0200502 (=>) => { $crate::token::FatArrow };
David Tolnay32954ef2017-12-26 22:43:16 -0500503 (;) => { $crate::token::Semi };
504 (<<) => { $crate::token::Shl };
505 (<<=) => { $crate::token::ShlEq };
506 (>>) => { $crate::token::Shr };
507 (>>=) => { $crate::token::ShrEq };
508 (*) => { $crate::token::Star };
509 (-) => { $crate::token::Sub };
510 (-=) => { $crate::token::SubEq };
511 (_) => { $crate::token::Underscore };
512 (as) => { $crate::token::As };
513 (auto) => { $crate::token::Auto };
514 (box) => { $crate::token::Box };
515 (break) => { $crate::token::Break };
516 (Self) => { $crate::token::CapSelf };
517 (catch) => { $crate::token::Catch };
518 (const) => { $crate::token::Const };
519 (continue) => { $crate::token::Continue };
520 (crate) => { $crate::token::Crate };
521 (default) => { $crate::token::Default };
522 (do) => { $crate::token::Do };
523 (dyn) => { $crate::token::Dyn };
524 (else) => { $crate::token::Else };
525 (enum) => { $crate::token::Enum };
526 (extern) => { $crate::token::Extern };
527 (fn) => { $crate::token::Fn };
528 (for) => { $crate::token::For };
529 (if) => { $crate::token::If };
530 (impl) => { $crate::token::Impl };
531 (in) => { $crate::token::In };
532 (let) => { $crate::token::Let };
533 (loop) => { $crate::token::Loop };
534 (macro) => { $crate::token::Macro };
535 (match) => { $crate::token::Match };
536 (mod) => { $crate::token::Mod };
537 (move) => { $crate::token::Move };
538 (mut) => { $crate::token::Mut };
539 (pub) => { $crate::token::Pub };
540 (ref) => { $crate::token::Ref };
541 (return) => { $crate::token::Return };
542 (self) => { $crate::token::Self_ };
543 (static) => { $crate::token::Static };
544 (struct) => { $crate::token::Struct };
545 (super) => { $crate::token::Super };
546 (trait) => { $crate::token::Trait };
547 (type) => { $crate::token::Type };
548 (union) => { $crate::token::Union };
549 (unsafe) => { $crate::token::Unsafe };
550 (use) => { $crate::token::Use };
551 (where) => { $crate::token::Where };
552 (while) => { $crate::token::While };
553 (yield) => { $crate::token::Yield };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800554}
555
David Tolnayf005f962018-01-06 21:19:41 -0800556/// Parse a single Rust punctuation token.
557///
558/// See the [token module] documentation for details and examples.
559///
560/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800561///
562/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500563#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800564#[macro_export]
565macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500566 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
567 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
568 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
569 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
570 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
571 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
572 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
573 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
574 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
575 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
576 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
577 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
578 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
579 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
580 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
581 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
582 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
583 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
584 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
585 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
586 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
587 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
588 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
589 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
590 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
591 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
592 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
593 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
594 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
595 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
596 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
597 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
598 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
599 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
600 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200601 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500602 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
603 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
604 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
605 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
606 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
607 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
608 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
609 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
610 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800611}
612
David Tolnayf005f962018-01-06 21:19:41 -0800613/// Parse a single Rust keyword token.
614///
615/// See the [token module] documentation for details and examples.
616///
617/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800618///
619/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500620#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800621#[macro_export]
622macro_rules! keyword {
David Tolnay32954ef2017-12-26 22:43:16 -0500623 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
624 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
625 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
626 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
627 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
628 ($i:expr, catch) => { call!($i, <$crate::token::Catch as $crate::synom::Synom>::parse) };
629 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
630 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
631 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
632 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
633 ($i:expr, do) => { call!($i, <$crate::token::Do as $crate::synom::Synom>::parse) };
634 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
635 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
636 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
637 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
638 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
639 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
640 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
641 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
642 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
643 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
644 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
645 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
646 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
647 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
648 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
649 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
650 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
651 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
652 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
653 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
654 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
655 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
656 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
657 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
658 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
659 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
660 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
661 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
662 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
663 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
664 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800665}
666
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700667#[cfg(feature = "parsing")]
668mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500669 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700670
David Tolnaydfc886b2018-01-06 08:03:09 -0800671 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500672 use parse_error;
673 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700674
675 pub trait FromSpans: Sized {
676 fn from_spans(spans: &[Span]) -> Self;
677 }
678
679 impl FromSpans for [Span; 1] {
680 fn from_spans(spans: &[Span]) -> Self {
681 [spans[0]]
682 }
683 }
684
685 impl FromSpans for [Span; 2] {
686 fn from_spans(spans: &[Span]) -> Self {
687 [spans[0], spans[1]]
688 }
689 }
690
691 impl FromSpans for [Span; 3] {
692 fn from_spans(spans: &[Span]) -> Self {
693 [spans[0], spans[1], spans[2]]
694 }
695 }
696
David Tolnay73c98de2017-12-31 15:56:56 -0500697 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 -0500698 where
699 T: FromSpans,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700700 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700701 let mut spans = [Span::call_site(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700702 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700703 let chars = s.chars();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700704
Alex Crichton954046c2017-05-30 21:49:42 -0700705 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400706 match tokens.op() {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700707 Some((op, rest)) if op.op() == ch => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400708 if i != s.len() - 1 {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700709 match op.spacing() {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700710 Spacing::Joint => {}
711 _ => return parse_error(),
Michael Layzell0a1a6632017-06-02 18:07:43 -0400712 }
713 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700714 *slot = op.span();
Michael Layzell0a1a6632017-06-02 18:07:43 -0400715 tokens = rest;
Alex Crichton954046c2017-05-30 21:49:42 -0700716 }
David Tolnay51382052017-12-27 13:46:21 -0500717 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700718 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700719 }
David Tolnayf4aa6b42017-12-31 16:40:33 -0500720 Ok((new(T::from_spans(&spans)), tokens))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700721 }
722
David Tolnay73c98de2017-12-31 15:56:56 -0500723 pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700724 if let Some((term, rest)) = tokens.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500725 if term.as_str() == keyword {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700726 return Ok((new(term.span()), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400727 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700728 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400729 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700730 }
731
David Tolnay51382052017-12-27 13:46:21 -0500732 pub fn delim<'a, F, R, T>(
733 delim: &str,
734 tokens: Cursor<'a>,
735 new: fn(Span) -> T,
736 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500737 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500738 where
739 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700740 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400741 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700742 let delim = match delim {
743 "(" => Delimiter::Parenthesis,
744 "{" => Delimiter::Brace,
745 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400746 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700747 _ => panic!("unknown delimiter: {}", delim),
748 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700749
David Tolnay65729482017-12-31 16:14:50 -0500750 if let Some((inside, span, rest)) = tokens.group(delim) {
751 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500752 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400753 if remaining.eof() {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500754 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400755 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700756 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400757 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700758 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700759 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400760 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700761 }
762}
763
764#[cfg(feature = "printing")]
765mod printing {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700766 use proc_macro2::{Delimiter, Spacing, Span, Term, Op, Group};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700767 use quote::Tokens;
768
David Tolnay73c98de2017-12-31 15:56:56 -0500769 pub fn punct(s: &str, spans: &[Span], tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700770 assert_eq!(s.len(), spans.len());
771
772 let mut chars = s.chars();
773 let mut spans = spans.iter();
774 let ch = chars.next_back().unwrap();
775 let span = spans.next_back().unwrap();
776 for (ch, span) in chars.zip(spans) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700777 let mut op = Op::new(ch, Spacing::Joint);
778 op.set_span(*span);
779 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700780 }
781
Alex Crichton9a4dca22018-03-28 06:32:19 -0700782 let mut op = Op::new(ch, Spacing::Alone);
783 op.set_span(*span);
784 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700785 }
786
David Tolnay73c98de2017-12-31 15:56:56 -0500787 pub fn keyword(s: &str, span: &Span, tokens: &mut Tokens) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700788 tokens.append(Term::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700789 }
790
791 pub fn delim<F>(s: &str, span: &Span, tokens: &mut Tokens, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500792 where
793 F: FnOnce(&mut Tokens),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700794 {
David Tolnay00ab6982017-12-31 18:15:06 -0500795 let delim = match s {
796 "(" => Delimiter::Parenthesis,
797 "[" => Delimiter::Bracket,
798 "{" => Delimiter::Brace,
799 " " => Delimiter::None,
800 _ => panic!("unknown delimiter: {}", s),
801 };
802 let mut inner = Tokens::new();
803 f(&mut inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700804 let mut g = Group::new(delim, inner.into());
805 g.set_span(*span);
806 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700807 }
808}