blob: f05968bf32d1343c2eb47de3350b7f4ce9ba1c9f [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 ) => (
David Tolnay73c98de2017-12-31 15:56:56 -0500114 $(token_punct! { #[$punct_doc] $punct pub struct $punct_name/$len })*
115 $(token_delimiter! { #[$delimiter_doc] $delimiter pub struct $delimiter_name })*
116 $(token_keyword! { #[$keyword_doc] $keyword pub struct $keyword_name })*
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700117 )
118}
119
David Tolnay73c98de2017-12-31 15:56:56 -0500120macro_rules! token_punct {
David Tolnay5a20f632017-12-26 22:11:28 -0500121 (#[$doc:meta] $s:tt pub struct $name:ident/$len:tt) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700122 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500123 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800124 ///
125 /// Don't try to remember the name of this type -- use the [`Token!`]
126 /// macro instead.
127 ///
128 /// [`Token!`]: index.html
David Tolnay5a20f632017-12-26 22:11:28 -0500129 pub struct $name(pub [Span; $len]);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700130
David Tolnay0bdb0552017-12-27 21:31:51 -0500131 impl $name {
132 pub fn new(span: Span) -> Self {
133 $name([span; $len])
134 }
135 }
136
David Tolnay66bb8d52018-01-08 08:22:31 -0800137 impl ::std::default::Default for $name {
138 fn default() -> Self {
139 $name([Span::def_site(); $len])
140 }
141 }
142
Nika Layzelld73a3652017-10-24 08:57:05 -0400143 #[cfg(feature = "extra-traits")]
144 impl ::std::fmt::Debug for $name {
145 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
David Tolnay98942562017-12-26 21:24:35 -0500146 f.write_str(stringify!($name))
Nika Layzelld73a3652017-10-24 08:57:05 -0400147 }
148 }
149
David Tolnay98942562017-12-26 21:24:35 -0500150 #[cfg(feature = "extra-traits")]
151 impl ::std::cmp::Eq for $name {}
152
153 #[cfg(feature = "extra-traits")]
154 impl ::std::cmp::PartialEq for $name {
155 fn eq(&self, _other: &$name) -> bool {
156 true
157 }
158 }
159
160 #[cfg(feature = "extra-traits")]
161 impl ::std::hash::Hash for $name {
162 fn hash<H>(&self, _state: &mut H)
163 where H: ::std::hash::Hasher
164 {}
165 }
166
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700167 #[cfg(feature = "printing")]
168 impl ::quote::ToTokens for $name {
169 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500170 printing::punct($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700171 }
172 }
173
174 #[cfg(feature = "parsing")]
175 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800176 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500177 parsing::punct($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700178 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800179
180 fn description() -> Option<&'static str> {
181 Some(concat!("`", $s, "`"))
182 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700183 }
184 }
185}
186
David Tolnay73c98de2017-12-31 15:56:56 -0500187macro_rules! token_keyword {
David Tolnay5a20f632017-12-26 22:11:28 -0500188 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700189 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500190 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800191 ///
192 /// Don't try to remember the name of this type -- use the [`Token!`]
193 /// macro instead.
194 ///
195 /// [`Token!`]: index.html
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700196 pub struct $name(pub Span);
197
David Tolnay66bb8d52018-01-08 08:22:31 -0800198 impl ::std::default::Default for $name {
199 fn default() -> Self {
200 $name(Span::def_site())
201 }
202 }
203
David Tolnay98942562017-12-26 21:24:35 -0500204 #[cfg(feature = "extra-traits")]
205 impl ::std::fmt::Debug for $name {
206 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
207 f.write_str(stringify!($name))
208 }
209 }
210
211 #[cfg(feature = "extra-traits")]
212 impl ::std::cmp::Eq for $name {}
213
214 #[cfg(feature = "extra-traits")]
215 impl ::std::cmp::PartialEq for $name {
216 fn eq(&self, _other: &$name) -> bool {
217 true
218 }
219 }
220
221 #[cfg(feature = "extra-traits")]
222 impl ::std::hash::Hash for $name {
223 fn hash<H>(&self, _state: &mut H)
224 where H: ::std::hash::Hasher
225 {}
226 }
227
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700228 #[cfg(feature = "printing")]
229 impl ::quote::ToTokens for $name {
230 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500231 printing::keyword($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700232 }
233 }
234
235 #[cfg(feature = "parsing")]
236 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800237 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500238 parsing::keyword($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700239 }
David Tolnay79777332018-01-07 10:04:42 -0800240
241 fn description() -> Option<&'static str> {
242 Some(concat!("`", $s, "`"))
243 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700244 }
245 }
246}
247
David Tolnay73c98de2017-12-31 15:56:56 -0500248macro_rules! token_delimiter {
David Tolnay5a20f632017-12-26 22:11:28 -0500249 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700250 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
David Tolnay5a20f632017-12-26 22:11:28 -0500251 #[$doc]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700252 pub struct $name(pub Span);
253
David Tolnay66bb8d52018-01-08 08:22:31 -0800254 impl ::std::default::Default for $name {
255 fn default() -> Self {
256 $name(Span::def_site())
257 }
258 }
259
David Tolnay98942562017-12-26 21:24:35 -0500260 #[cfg(feature = "extra-traits")]
261 impl ::std::fmt::Debug for $name {
262 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
263 f.write_str(stringify!($name))
264 }
265 }
266
267 #[cfg(feature = "extra-traits")]
268 impl ::std::cmp::Eq for $name {}
269
270 #[cfg(feature = "extra-traits")]
271 impl ::std::cmp::PartialEq for $name {
272 fn eq(&self, _other: &$name) -> bool {
273 true
274 }
275 }
276
277 #[cfg(feature = "extra-traits")]
278 impl ::std::hash::Hash for $name {
279 fn hash<H>(&self, _state: &mut H)
280 where H: ::std::hash::Hasher
281 {}
282 }
283
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700284 impl $name {
285 #[cfg(feature = "printing")]
286 pub fn surround<F>(&self,
287 tokens: &mut ::quote::Tokens,
288 f: F)
289 where F: FnOnce(&mut ::quote::Tokens)
290 {
291 printing::delim($s, &self.0, tokens, f);
292 }
293
294 #[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800295 pub fn parse<F, R>(tokens: $crate::buffer::Cursor, f: F) -> $crate::synom::PResult<($name, R)>
296 where F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700297 {
298 parsing::delim($s, tokens, $name, f)
299 }
300 }
301 }
302}
303
304tokens! {
David Tolnay73c98de2017-12-31 15:56:56 -0500305 punct: {
David Tolnay5a20f632017-12-26 22:11:28 -0500306 "+" pub struct Add/1 /// `+`
307 "+=" pub struct AddEq/2 /// `+=`
308 "&" pub struct And/1 /// `&`
309 "&&" pub struct AndAnd/2 /// `&&`
310 "&=" pub struct AndEq/2 /// `&=`
311 "@" pub struct At/1 /// `@`
312 "!" pub struct Bang/1 /// `!`
313 "^" pub struct Caret/1 /// `^`
David Tolnay32954ef2017-12-26 22:43:16 -0500314 "^=" pub struct CaretEq/2 /// `^=`
David Tolnay5a20f632017-12-26 22:11:28 -0500315 ":" pub struct Colon/1 /// `:`
316 "::" pub struct Colon2/2 /// `::`
317 "," pub struct Comma/1 /// `,`
318 "/" pub struct Div/1 /// `/`
319 "/=" pub struct DivEq/2 /// `/=`
320 "." pub struct Dot/1 /// `.`
321 ".." pub struct Dot2/2 /// `..`
322 "..." pub struct Dot3/3 /// `...`
323 "..=" pub struct DotDotEq/3 /// `..=`
324 "=" pub struct Eq/1 /// `=`
325 "==" pub struct EqEq/2 /// `==`
326 ">=" pub struct Ge/2 /// `>=`
327 ">" pub struct Gt/1 /// `>`
328 "<=" pub struct Le/2 /// `<=`
329 "<" pub struct Lt/1 /// `<`
330 "*=" pub struct MulEq/2 /// `*=`
331 "!=" pub struct Ne/2 /// `!=`
332 "|" pub struct Or/1 /// `|`
333 "|=" pub struct OrEq/2 /// `|=`
334 "||" pub struct OrOr/2 /// `||`
335 "#" pub struct Pound/1 /// `#`
336 "?" pub struct Question/1 /// `?`
337 "->" pub struct RArrow/2 /// `->`
338 "<-" pub struct LArrow/2 /// `<-`
339 "%" pub struct Rem/1 /// `%`
340 "%=" pub struct RemEq/2 /// `%=`
341 "=>" pub struct Rocket/2 /// `=>`
342 ";" pub struct Semi/1 /// `;`
343 "<<" pub struct Shl/2 /// `<<`
344 "<<=" pub struct ShlEq/3 /// `<<=`
345 ">>" pub struct Shr/2 /// `>>`
346 ">>=" pub struct ShrEq/3 /// `>>=`
347 "*" pub struct Star/1 /// `*`
348 "-" pub struct Sub/1 /// `-`
349 "-=" pub struct SubEq/2 /// `-=`
350 "_" pub struct Underscore/1 /// `_`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700351 }
David Tolnay73c98de2017-12-31 15:56:56 -0500352 delimiter: {
David Tolnay5a20f632017-12-26 22:11:28 -0500353 "{" pub struct Brace /// `{...}`
354 "[" pub struct Bracket /// `[...]`
355 "(" pub struct Paren /// `(...)`
356 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700357 }
David Tolnay73c98de2017-12-31 15:56:56 -0500358 keyword: {
David Tolnay5a20f632017-12-26 22:11:28 -0500359 "as" pub struct As /// `as`
360 "auto" pub struct Auto /// `auto`
361 "box" pub struct Box /// `box`
362 "break" pub struct Break /// `break`
363 "Self" pub struct CapSelf /// `Self`
364 "catch" pub struct Catch /// `catch`
365 "const" pub struct Const /// `const`
366 "continue" pub struct Continue /// `continue`
367 "crate" pub struct Crate /// `crate`
368 "default" pub struct Default /// `default`
369 "do" pub struct Do /// `do`
370 "dyn" pub struct Dyn /// `dyn`
371 "else" pub struct Else /// `else`
372 "enum" pub struct Enum /// `enum`
373 "extern" pub struct Extern /// `extern`
374 "fn" pub struct Fn /// `fn`
375 "for" pub struct For /// `for`
376 "if" pub struct If /// `if`
377 "impl" pub struct Impl /// `impl`
378 "in" pub struct In /// `in`
379 "let" pub struct Let /// `let`
380 "loop" pub struct Loop /// `loop`
381 "macro" pub struct Macro /// `macro`
382 "match" pub struct Match /// `match`
383 "mod" pub struct Mod /// `mod`
384 "move" pub struct Move /// `move`
385 "mut" pub struct Mut /// `mut`
386 "pub" pub struct Pub /// `pub`
387 "ref" pub struct Ref /// `ref`
388 "return" pub struct Return /// `return`
389 "self" pub struct Self_ /// `self`
390 "static" pub struct Static /// `static`
391 "struct" pub struct Struct /// `struct`
392 "super" pub struct Super /// `super`
393 "trait" pub struct Trait /// `trait`
394 "type" pub struct Type /// `type`
395 "union" pub struct Union /// `union`
396 "unsafe" pub struct Unsafe /// `unsafe`
397 "use" pub struct Use /// `use`
398 "where" pub struct Where /// `where`
399 "while" pub struct While /// `while`
400 "yield" pub struct Yield /// `yield`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700401 }
402}
403
David Tolnayf005f962018-01-06 21:19:41 -0800404/// A type-macro that expands to the name of the Rust type representation of a
405/// given token.
406///
407/// See the [token module] documentation for details and examples.
408///
409/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800410// Unfortunate duplication due to a rustdoc bug.
411// https://github.com/rust-lang/rust/issues/45939
412#[macro_export]
413macro_rules! Token {
David Tolnay32954ef2017-12-26 22:43:16 -0500414 (+) => { $crate::token::Add };
415 (+=) => { $crate::token::AddEq };
416 (&) => { $crate::token::And };
417 (&&) => { $crate::token::AndAnd };
418 (&=) => { $crate::token::AndEq };
419 (@) => { $crate::token::At };
420 (!) => { $crate::token::Bang };
421 (^) => { $crate::token::Caret };
422 (^=) => { $crate::token::CaretEq };
423 (:) => { $crate::token::Colon };
424 (::) => { $crate::token::Colon2 };
425 (,) => { $crate::token::Comma };
426 (/) => { $crate::token::Div };
427 (/=) => { $crate::token::DivEq };
428 (.) => { $crate::token::Dot };
429 (..) => { $crate::token::Dot2 };
430 (...) => { $crate::token::Dot3 };
431 (..=) => { $crate::token::DotDotEq };
432 (=) => { $crate::token::Eq };
433 (==) => { $crate::token::EqEq };
434 (>=) => { $crate::token::Ge };
435 (>) => { $crate::token::Gt };
436 (<=) => { $crate::token::Le };
437 (<) => { $crate::token::Lt };
438 (*=) => { $crate::token::MulEq };
439 (!=) => { $crate::token::Ne };
440 (|) => { $crate::token::Or };
441 (|=) => { $crate::token::OrEq };
442 (||) => { $crate::token::OrOr };
443 (#) => { $crate::token::Pound };
444 (?) => { $crate::token::Question };
445 (->) => { $crate::token::RArrow };
446 (<-) => { $crate::token::LArrow };
447 (%) => { $crate::token::Rem };
448 (%=) => { $crate::token::RemEq };
449 (=>) => { $crate::token::Rocket };
450 (;) => { $crate::token::Semi };
451 (<<) => { $crate::token::Shl };
452 (<<=) => { $crate::token::ShlEq };
453 (>>) => { $crate::token::Shr };
454 (>>=) => { $crate::token::ShrEq };
455 (*) => { $crate::token::Star };
456 (-) => { $crate::token::Sub };
457 (-=) => { $crate::token::SubEq };
458 (_) => { $crate::token::Underscore };
459 (as) => { $crate::token::As };
460 (auto) => { $crate::token::Auto };
461 (box) => { $crate::token::Box };
462 (break) => { $crate::token::Break };
463 (Self) => { $crate::token::CapSelf };
464 (catch) => { $crate::token::Catch };
465 (const) => { $crate::token::Const };
466 (continue) => { $crate::token::Continue };
467 (crate) => { $crate::token::Crate };
468 (default) => { $crate::token::Default };
469 (do) => { $crate::token::Do };
470 (dyn) => { $crate::token::Dyn };
471 (else) => { $crate::token::Else };
472 (enum) => { $crate::token::Enum };
473 (extern) => { $crate::token::Extern };
474 (fn) => { $crate::token::Fn };
475 (for) => { $crate::token::For };
476 (if) => { $crate::token::If };
477 (impl) => { $crate::token::Impl };
478 (in) => { $crate::token::In };
479 (let) => { $crate::token::Let };
480 (loop) => { $crate::token::Loop };
481 (macro) => { $crate::token::Macro };
482 (match) => { $crate::token::Match };
483 (mod) => { $crate::token::Mod };
484 (move) => { $crate::token::Move };
485 (mut) => { $crate::token::Mut };
486 (pub) => { $crate::token::Pub };
487 (ref) => { $crate::token::Ref };
488 (return) => { $crate::token::Return };
489 (self) => { $crate::token::Self_ };
490 (static) => { $crate::token::Static };
491 (struct) => { $crate::token::Struct };
492 (super) => { $crate::token::Super };
493 (trait) => { $crate::token::Trait };
494 (type) => { $crate::token::Type };
495 (union) => { $crate::token::Union };
496 (unsafe) => { $crate::token::Unsafe };
497 (use) => { $crate::token::Use };
498 (where) => { $crate::token::Where };
499 (while) => { $crate::token::While };
500 (yield) => { $crate::token::Yield };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800501}
502
David Tolnayf005f962018-01-06 21:19:41 -0800503/// Parse a single Rust punctuation token.
504///
505/// See the [token module] documentation for details and examples.
506///
507/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800508///
509/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500510#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800511#[macro_export]
512macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500513 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
514 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
515 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
516 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
517 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
518 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
519 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
520 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
521 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
522 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
523 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
524 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
525 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
526 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
527 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
528 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
529 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
530 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
531 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
532 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
533 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
534 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
535 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
536 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
537 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
538 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
539 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
540 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
541 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
542 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
543 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
544 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
545 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
546 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
547 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
548 ($i:expr, =>) => { call!($i, <$crate::token::Rocket as $crate::synom::Synom>::parse) };
549 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
550 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
551 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
552 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
553 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
554 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
555 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
556 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
557 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800558}
559
David Tolnayf005f962018-01-06 21:19:41 -0800560/// Parse a single Rust keyword token.
561///
562/// See the [token module] documentation for details and examples.
563///
564/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800565///
566/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500567#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800568#[macro_export]
569macro_rules! keyword {
David Tolnay32954ef2017-12-26 22:43:16 -0500570 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
571 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
572 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
573 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
574 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
575 ($i:expr, catch) => { call!($i, <$crate::token::Catch as $crate::synom::Synom>::parse) };
576 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
577 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
578 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
579 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
580 ($i:expr, do) => { call!($i, <$crate::token::Do as $crate::synom::Synom>::parse) };
581 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
582 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
583 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
584 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
585 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
586 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
587 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
588 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
589 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
590 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
591 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
592 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
593 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
594 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
595 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
596 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
597 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
598 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
599 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
600 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
601 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
602 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
603 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
604 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
605 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
606 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
607 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
608 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
609 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
610 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
611 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800612}
613
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700614#[cfg(feature = "parsing")]
615mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500616 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700617
David Tolnaydfc886b2018-01-06 08:03:09 -0800618 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500619 use parse_error;
620 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700621
622 pub trait FromSpans: Sized {
623 fn from_spans(spans: &[Span]) -> Self;
624 }
625
626 impl FromSpans for [Span; 1] {
627 fn from_spans(spans: &[Span]) -> Self {
628 [spans[0]]
629 }
630 }
631
632 impl FromSpans for [Span; 2] {
633 fn from_spans(spans: &[Span]) -> Self {
634 [spans[0], spans[1]]
635 }
636 }
637
638 impl FromSpans for [Span; 3] {
639 fn from_spans(spans: &[Span]) -> Self {
640 [spans[0], spans[1], spans[2]]
641 }
642 }
643
David Tolnay73c98de2017-12-31 15:56:56 -0500644 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 -0500645 where
646 T: FromSpans,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700647 {
David Tolnay66bb8d52018-01-08 08:22:31 -0800648 let mut spans = [Span::def_site(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700649 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700650 let chars = s.chars();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700651
Alex Crichton954046c2017-05-30 21:49:42 -0700652 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400653 match tokens.op() {
David Tolnay65729482017-12-31 16:14:50 -0500654 Some((span, op, kind, rest)) if op == ch => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400655 if i != s.len() - 1 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700656 match kind {
657 Spacing::Joint => {}
658 _ => return parse_error(),
Michael Layzell0a1a6632017-06-02 18:07:43 -0400659 }
660 }
David Tolnay98942562017-12-26 21:24:35 -0500661 *slot = span;
Michael Layzell0a1a6632017-06-02 18:07:43 -0400662 tokens = rest;
Alex Crichton954046c2017-05-30 21:49:42 -0700663 }
David Tolnay51382052017-12-27 13:46:21 -0500664 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700665 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700666 }
David Tolnayf4aa6b42017-12-31 16:40:33 -0500667 Ok((new(T::from_spans(&spans)), tokens))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700668 }
669
David Tolnay73c98de2017-12-31 15:56:56 -0500670 pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> {
David Tolnay65729482017-12-31 16:14:50 -0500671 if let Some((span, term, rest)) = tokens.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500672 if term.as_str() == keyword {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500673 return Ok((new(span), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400674 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700675 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400676 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700677 }
678
David Tolnay51382052017-12-27 13:46:21 -0500679 pub fn delim<'a, F, R, T>(
680 delim: &str,
681 tokens: Cursor<'a>,
682 new: fn(Span) -> T,
683 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500684 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500685 where
686 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700687 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400688 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700689 let delim = match delim {
690 "(" => Delimiter::Parenthesis,
691 "{" => Delimiter::Brace,
692 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400693 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700694 _ => panic!("unknown delimiter: {}", delim),
695 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700696
David Tolnay65729482017-12-31 16:14:50 -0500697 if let Some((inside, span, rest)) = tokens.group(delim) {
698 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500699 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400700 if remaining.eof() {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500701 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400702 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700703 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400704 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700705 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700706 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400707 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700708 }
709}
710
711#[cfg(feature = "printing")]
712mod printing {
David Tolnayf2cfd722017-12-31 18:02:51 -0500713 use proc_macro2::{Delimiter, Spacing, Span, Term, TokenNode, TokenTree};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700714 use quote::Tokens;
715
David Tolnay73c98de2017-12-31 15:56:56 -0500716 pub fn punct(s: &str, spans: &[Span], tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700717 assert_eq!(s.len(), spans.len());
718
719 let mut chars = s.chars();
720 let mut spans = spans.iter();
721 let ch = chars.next_back().unwrap();
722 let span = spans.next_back().unwrap();
723 for (ch, span) in chars.zip(spans) {
724 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500725 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700726 kind: TokenNode::Op(ch, Spacing::Joint),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700727 });
728 }
729
730 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500731 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700732 kind: TokenNode::Op(ch, Spacing::Alone),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700733 });
734 }
735
David Tolnay73c98de2017-12-31 15:56:56 -0500736 pub fn keyword(s: &str, span: &Span, tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700737 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500738 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700739 kind: TokenNode::Term(Term::intern(s)),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700740 });
741 }
742
743 pub fn delim<F>(s: &str, span: &Span, tokens: &mut Tokens, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500744 where
745 F: FnOnce(&mut Tokens),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700746 {
David Tolnay00ab6982017-12-31 18:15:06 -0500747 let delim = match s {
748 "(" => Delimiter::Parenthesis,
749 "[" => Delimiter::Bracket,
750 "{" => Delimiter::Brace,
751 " " => Delimiter::None,
752 _ => panic!("unknown delimiter: {}", s),
753 };
754 let mut inner = Tokens::new();
755 f(&mut inner);
756 tokens.append(TokenTree {
757 span: *span,
758 kind: TokenNode::Group(delim, inner.into()),
759 });
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700760 }
761}