blob: 685fcd1e5294ebc9d3fc05af3b2d785141bae3df [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))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700123 #[derive(Default)]
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
Nika Layzelld73a3652017-10-24 08:57:05 -0400138 #[cfg(feature = "extra-traits")]
139 impl ::std::fmt::Debug for $name {
140 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
David Tolnay98942562017-12-26 21:24:35 -0500141 f.write_str(stringify!($name))
Nika Layzelld73a3652017-10-24 08:57:05 -0400142 }
143 }
144
David Tolnay98942562017-12-26 21:24:35 -0500145 #[cfg(feature = "extra-traits")]
146 impl ::std::cmp::Eq for $name {}
147
148 #[cfg(feature = "extra-traits")]
149 impl ::std::cmp::PartialEq for $name {
150 fn eq(&self, _other: &$name) -> bool {
151 true
152 }
153 }
154
155 #[cfg(feature = "extra-traits")]
156 impl ::std::hash::Hash for $name {
157 fn hash<H>(&self, _state: &mut H)
158 where H: ::std::hash::Hasher
159 {}
160 }
161
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700162 #[cfg(feature = "printing")]
163 impl ::quote::ToTokens for $name {
164 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500165 printing::punct($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700166 }
167 }
168
169 #[cfg(feature = "parsing")]
170 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800171 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500172 parsing::punct($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700173 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800174
175 fn description() -> Option<&'static str> {
176 Some(concat!("`", $s, "`"))
177 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700178 }
179 }
180}
181
David Tolnay73c98de2017-12-31 15:56:56 -0500182macro_rules! token_keyword {
David Tolnay5a20f632017-12-26 22:11:28 -0500183 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700184 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700185 #[derive(Default)]
David Tolnay5a20f632017-12-26 22:11:28 -0500186 #[$doc]
David Tolnay1bb760c2018-01-07 11:18:15 -0800187 ///
188 /// Don't try to remember the name of this type -- use the [`Token!`]
189 /// macro instead.
190 ///
191 /// [`Token!`]: index.html
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700192 pub struct $name(pub Span);
193
David Tolnay98942562017-12-26 21:24:35 -0500194 #[cfg(feature = "extra-traits")]
195 impl ::std::fmt::Debug for $name {
196 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
197 f.write_str(stringify!($name))
198 }
199 }
200
201 #[cfg(feature = "extra-traits")]
202 impl ::std::cmp::Eq for $name {}
203
204 #[cfg(feature = "extra-traits")]
205 impl ::std::cmp::PartialEq for $name {
206 fn eq(&self, _other: &$name) -> bool {
207 true
208 }
209 }
210
211 #[cfg(feature = "extra-traits")]
212 impl ::std::hash::Hash for $name {
213 fn hash<H>(&self, _state: &mut H)
214 where H: ::std::hash::Hasher
215 {}
216 }
217
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700218 #[cfg(feature = "printing")]
219 impl ::quote::ToTokens for $name {
220 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500221 printing::keyword($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700222 }
223 }
224
225 #[cfg(feature = "parsing")]
226 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800227 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500228 parsing::keyword($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700229 }
David Tolnay79777332018-01-07 10:04:42 -0800230
231 fn description() -> Option<&'static str> {
232 Some(concat!("`", $s, "`"))
233 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700234 }
235 }
236}
237
David Tolnay73c98de2017-12-31 15:56:56 -0500238macro_rules! token_delimiter {
David Tolnay5a20f632017-12-26 22:11:28 -0500239 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700240 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700241 #[derive(Default)]
David Tolnay5a20f632017-12-26 22:11:28 -0500242 #[$doc]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700243 pub struct $name(pub Span);
244
David Tolnay98942562017-12-26 21:24:35 -0500245 #[cfg(feature = "extra-traits")]
246 impl ::std::fmt::Debug for $name {
247 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
248 f.write_str(stringify!($name))
249 }
250 }
251
252 #[cfg(feature = "extra-traits")]
253 impl ::std::cmp::Eq for $name {}
254
255 #[cfg(feature = "extra-traits")]
256 impl ::std::cmp::PartialEq for $name {
257 fn eq(&self, _other: &$name) -> bool {
258 true
259 }
260 }
261
262 #[cfg(feature = "extra-traits")]
263 impl ::std::hash::Hash for $name {
264 fn hash<H>(&self, _state: &mut H)
265 where H: ::std::hash::Hasher
266 {}
267 }
268
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700269 impl $name {
270 #[cfg(feature = "printing")]
271 pub fn surround<F>(&self,
272 tokens: &mut ::quote::Tokens,
273 f: F)
274 where F: FnOnce(&mut ::quote::Tokens)
275 {
276 printing::delim($s, &self.0, tokens, f);
277 }
278
279 #[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800280 pub fn parse<F, R>(tokens: $crate::buffer::Cursor, f: F) -> $crate::synom::PResult<($name, R)>
281 where F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700282 {
283 parsing::delim($s, tokens, $name, f)
284 }
285 }
286 }
287}
288
289tokens! {
David Tolnay73c98de2017-12-31 15:56:56 -0500290 punct: {
David Tolnay5a20f632017-12-26 22:11:28 -0500291 "+" pub struct Add/1 /// `+`
292 "+=" pub struct AddEq/2 /// `+=`
293 "&" pub struct And/1 /// `&`
294 "&&" pub struct AndAnd/2 /// `&&`
295 "&=" pub struct AndEq/2 /// `&=`
296 "@" pub struct At/1 /// `@`
297 "!" pub struct Bang/1 /// `!`
298 "^" pub struct Caret/1 /// `^`
David Tolnay32954ef2017-12-26 22:43:16 -0500299 "^=" pub struct CaretEq/2 /// `^=`
David Tolnay5a20f632017-12-26 22:11:28 -0500300 ":" pub struct Colon/1 /// `:`
301 "::" pub struct Colon2/2 /// `::`
302 "," pub struct Comma/1 /// `,`
303 "/" pub struct Div/1 /// `/`
304 "/=" pub struct DivEq/2 /// `/=`
305 "." pub struct Dot/1 /// `.`
306 ".." pub struct Dot2/2 /// `..`
307 "..." pub struct Dot3/3 /// `...`
308 "..=" pub struct DotDotEq/3 /// `..=`
309 "=" pub struct Eq/1 /// `=`
310 "==" pub struct EqEq/2 /// `==`
311 ">=" pub struct Ge/2 /// `>=`
312 ">" pub struct Gt/1 /// `>`
313 "<=" pub struct Le/2 /// `<=`
314 "<" pub struct Lt/1 /// `<`
315 "*=" pub struct MulEq/2 /// `*=`
316 "!=" pub struct Ne/2 /// `!=`
317 "|" pub struct Or/1 /// `|`
318 "|=" pub struct OrEq/2 /// `|=`
319 "||" pub struct OrOr/2 /// `||`
320 "#" pub struct Pound/1 /// `#`
321 "?" pub struct Question/1 /// `?`
322 "->" pub struct RArrow/2 /// `->`
323 "<-" pub struct LArrow/2 /// `<-`
324 "%" pub struct Rem/1 /// `%`
325 "%=" pub struct RemEq/2 /// `%=`
326 "=>" pub struct Rocket/2 /// `=>`
327 ";" pub struct Semi/1 /// `;`
328 "<<" pub struct Shl/2 /// `<<`
329 "<<=" pub struct ShlEq/3 /// `<<=`
330 ">>" pub struct Shr/2 /// `>>`
331 ">>=" pub struct ShrEq/3 /// `>>=`
332 "*" pub struct Star/1 /// `*`
333 "-" pub struct Sub/1 /// `-`
334 "-=" pub struct SubEq/2 /// `-=`
335 "_" pub struct Underscore/1 /// `_`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700336 }
David Tolnay73c98de2017-12-31 15:56:56 -0500337 delimiter: {
David Tolnay5a20f632017-12-26 22:11:28 -0500338 "{" pub struct Brace /// `{...}`
339 "[" pub struct Bracket /// `[...]`
340 "(" pub struct Paren /// `(...)`
341 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700342 }
David Tolnay73c98de2017-12-31 15:56:56 -0500343 keyword: {
David Tolnay5a20f632017-12-26 22:11:28 -0500344 "as" pub struct As /// `as`
345 "auto" pub struct Auto /// `auto`
346 "box" pub struct Box /// `box`
347 "break" pub struct Break /// `break`
348 "Self" pub struct CapSelf /// `Self`
349 "catch" pub struct Catch /// `catch`
350 "const" pub struct Const /// `const`
351 "continue" pub struct Continue /// `continue`
352 "crate" pub struct Crate /// `crate`
353 "default" pub struct Default /// `default`
354 "do" pub struct Do /// `do`
355 "dyn" pub struct Dyn /// `dyn`
356 "else" pub struct Else /// `else`
357 "enum" pub struct Enum /// `enum`
358 "extern" pub struct Extern /// `extern`
359 "fn" pub struct Fn /// `fn`
360 "for" pub struct For /// `for`
361 "if" pub struct If /// `if`
362 "impl" pub struct Impl /// `impl`
363 "in" pub struct In /// `in`
364 "let" pub struct Let /// `let`
365 "loop" pub struct Loop /// `loop`
366 "macro" pub struct Macro /// `macro`
367 "match" pub struct Match /// `match`
368 "mod" pub struct Mod /// `mod`
369 "move" pub struct Move /// `move`
370 "mut" pub struct Mut /// `mut`
371 "pub" pub struct Pub /// `pub`
372 "ref" pub struct Ref /// `ref`
373 "return" pub struct Return /// `return`
374 "self" pub struct Self_ /// `self`
375 "static" pub struct Static /// `static`
376 "struct" pub struct Struct /// `struct`
377 "super" pub struct Super /// `super`
378 "trait" pub struct Trait /// `trait`
379 "type" pub struct Type /// `type`
380 "union" pub struct Union /// `union`
381 "unsafe" pub struct Unsafe /// `unsafe`
382 "use" pub struct Use /// `use`
383 "where" pub struct Where /// `where`
384 "while" pub struct While /// `while`
385 "yield" pub struct Yield /// `yield`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700386 }
387}
388
David Tolnayf005f962018-01-06 21:19:41 -0800389/// A type-macro that expands to the name of the Rust type representation of a
390/// given token.
391///
392/// See the [token module] documentation for details and examples.
393///
394/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800395// Unfortunate duplication due to a rustdoc bug.
396// https://github.com/rust-lang/rust/issues/45939
397#[macro_export]
398macro_rules! Token {
David Tolnay32954ef2017-12-26 22:43:16 -0500399 (+) => { $crate::token::Add };
400 (+=) => { $crate::token::AddEq };
401 (&) => { $crate::token::And };
402 (&&) => { $crate::token::AndAnd };
403 (&=) => { $crate::token::AndEq };
404 (@) => { $crate::token::At };
405 (!) => { $crate::token::Bang };
406 (^) => { $crate::token::Caret };
407 (^=) => { $crate::token::CaretEq };
408 (:) => { $crate::token::Colon };
409 (::) => { $crate::token::Colon2 };
410 (,) => { $crate::token::Comma };
411 (/) => { $crate::token::Div };
412 (/=) => { $crate::token::DivEq };
413 (.) => { $crate::token::Dot };
414 (..) => { $crate::token::Dot2 };
415 (...) => { $crate::token::Dot3 };
416 (..=) => { $crate::token::DotDotEq };
417 (=) => { $crate::token::Eq };
418 (==) => { $crate::token::EqEq };
419 (>=) => { $crate::token::Ge };
420 (>) => { $crate::token::Gt };
421 (<=) => { $crate::token::Le };
422 (<) => { $crate::token::Lt };
423 (*=) => { $crate::token::MulEq };
424 (!=) => { $crate::token::Ne };
425 (|) => { $crate::token::Or };
426 (|=) => { $crate::token::OrEq };
427 (||) => { $crate::token::OrOr };
428 (#) => { $crate::token::Pound };
429 (?) => { $crate::token::Question };
430 (->) => { $crate::token::RArrow };
431 (<-) => { $crate::token::LArrow };
432 (%) => { $crate::token::Rem };
433 (%=) => { $crate::token::RemEq };
434 (=>) => { $crate::token::Rocket };
435 (;) => { $crate::token::Semi };
436 (<<) => { $crate::token::Shl };
437 (<<=) => { $crate::token::ShlEq };
438 (>>) => { $crate::token::Shr };
439 (>>=) => { $crate::token::ShrEq };
440 (*) => { $crate::token::Star };
441 (-) => { $crate::token::Sub };
442 (-=) => { $crate::token::SubEq };
443 (_) => { $crate::token::Underscore };
444 (as) => { $crate::token::As };
445 (auto) => { $crate::token::Auto };
446 (box) => { $crate::token::Box };
447 (break) => { $crate::token::Break };
448 (Self) => { $crate::token::CapSelf };
449 (catch) => { $crate::token::Catch };
450 (const) => { $crate::token::Const };
451 (continue) => { $crate::token::Continue };
452 (crate) => { $crate::token::Crate };
453 (default) => { $crate::token::Default };
454 (do) => { $crate::token::Do };
455 (dyn) => { $crate::token::Dyn };
456 (else) => { $crate::token::Else };
457 (enum) => { $crate::token::Enum };
458 (extern) => { $crate::token::Extern };
459 (fn) => { $crate::token::Fn };
460 (for) => { $crate::token::For };
461 (if) => { $crate::token::If };
462 (impl) => { $crate::token::Impl };
463 (in) => { $crate::token::In };
464 (let) => { $crate::token::Let };
465 (loop) => { $crate::token::Loop };
466 (macro) => { $crate::token::Macro };
467 (match) => { $crate::token::Match };
468 (mod) => { $crate::token::Mod };
469 (move) => { $crate::token::Move };
470 (mut) => { $crate::token::Mut };
471 (pub) => { $crate::token::Pub };
472 (ref) => { $crate::token::Ref };
473 (return) => { $crate::token::Return };
474 (self) => { $crate::token::Self_ };
475 (static) => { $crate::token::Static };
476 (struct) => { $crate::token::Struct };
477 (super) => { $crate::token::Super };
478 (trait) => { $crate::token::Trait };
479 (type) => { $crate::token::Type };
480 (union) => { $crate::token::Union };
481 (unsafe) => { $crate::token::Unsafe };
482 (use) => { $crate::token::Use };
483 (where) => { $crate::token::Where };
484 (while) => { $crate::token::While };
485 (yield) => { $crate::token::Yield };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800486}
487
David Tolnayf005f962018-01-06 21:19:41 -0800488/// Parse a single Rust punctuation token.
489///
490/// See the [token module] documentation for details and examples.
491///
492/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800493///
494/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500495#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800496#[macro_export]
497macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500498 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
499 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
500 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
501 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
502 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
503 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
504 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
505 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
506 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
507 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
508 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
509 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
510 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
511 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
512 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
513 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
514 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
515 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
516 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
517 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
518 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
519 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
520 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
521 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
522 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
523 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
524 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
525 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
526 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
527 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
528 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
529 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
530 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
531 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
532 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
533 ($i:expr, =>) => { call!($i, <$crate::token::Rocket as $crate::synom::Synom>::parse) };
534 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
535 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
536 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
537 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
538 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
539 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
540 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
541 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
542 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800543}
544
David Tolnayf005f962018-01-06 21:19:41 -0800545/// Parse a single Rust keyword token.
546///
547/// See the [token module] documentation for details and examples.
548///
549/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800550///
551/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500552#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800553#[macro_export]
554macro_rules! keyword {
David Tolnay32954ef2017-12-26 22:43:16 -0500555 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
556 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
557 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
558 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
559 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
560 ($i:expr, catch) => { call!($i, <$crate::token::Catch as $crate::synom::Synom>::parse) };
561 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
562 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
563 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
564 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
565 ($i:expr, do) => { call!($i, <$crate::token::Do as $crate::synom::Synom>::parse) };
566 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
567 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
568 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
569 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
570 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
571 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
572 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
573 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
574 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
575 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
576 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
577 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
578 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
579 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
580 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
581 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
582 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
583 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
584 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
585 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
586 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
587 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
588 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
589 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
590 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
591 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
592 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
593 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
594 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
595 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
596 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800597}
598
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700599#[cfg(feature = "parsing")]
600mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500601 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700602
David Tolnaydfc886b2018-01-06 08:03:09 -0800603 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500604 use parse_error;
605 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700606
607 pub trait FromSpans: Sized {
608 fn from_spans(spans: &[Span]) -> Self;
609 }
610
611 impl FromSpans for [Span; 1] {
612 fn from_spans(spans: &[Span]) -> Self {
613 [spans[0]]
614 }
615 }
616
617 impl FromSpans for [Span; 2] {
618 fn from_spans(spans: &[Span]) -> Self {
619 [spans[0], spans[1]]
620 }
621 }
622
623 impl FromSpans for [Span; 3] {
624 fn from_spans(spans: &[Span]) -> Self {
625 [spans[0], spans[1], spans[2]]
626 }
627 }
628
David Tolnay73c98de2017-12-31 15:56:56 -0500629 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 -0500630 where
631 T: FromSpans,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700632 {
633 let mut spans = [Span::default(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700634 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700635 let chars = s.chars();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700636
Alex Crichton954046c2017-05-30 21:49:42 -0700637 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400638 match tokens.op() {
David Tolnay65729482017-12-31 16:14:50 -0500639 Some((span, op, kind, rest)) if op == ch => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400640 if i != s.len() - 1 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700641 match kind {
642 Spacing::Joint => {}
643 _ => return parse_error(),
Michael Layzell0a1a6632017-06-02 18:07:43 -0400644 }
645 }
David Tolnay98942562017-12-26 21:24:35 -0500646 *slot = span;
Michael Layzell0a1a6632017-06-02 18:07:43 -0400647 tokens = rest;
Alex Crichton954046c2017-05-30 21:49:42 -0700648 }
David Tolnay51382052017-12-27 13:46:21 -0500649 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700650 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700651 }
David Tolnayf4aa6b42017-12-31 16:40:33 -0500652 Ok((new(T::from_spans(&spans)), tokens))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700653 }
654
David Tolnay73c98de2017-12-31 15:56:56 -0500655 pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> {
David Tolnay65729482017-12-31 16:14:50 -0500656 if let Some((span, term, rest)) = tokens.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500657 if term.as_str() == keyword {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500658 return Ok((new(span), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400659 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700660 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400661 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700662 }
663
David Tolnay51382052017-12-27 13:46:21 -0500664 pub fn delim<'a, F, R, T>(
665 delim: &str,
666 tokens: Cursor<'a>,
667 new: fn(Span) -> T,
668 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500669 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500670 where
671 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700672 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400673 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700674 let delim = match delim {
675 "(" => Delimiter::Parenthesis,
676 "{" => Delimiter::Brace,
677 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400678 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700679 _ => panic!("unknown delimiter: {}", delim),
680 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700681
David Tolnay65729482017-12-31 16:14:50 -0500682 if let Some((inside, span, rest)) = tokens.group(delim) {
683 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500684 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400685 if remaining.eof() {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500686 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400687 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700688 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400689 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700690 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700691 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400692 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700693 }
694}
695
696#[cfg(feature = "printing")]
697mod printing {
David Tolnayf2cfd722017-12-31 18:02:51 -0500698 use proc_macro2::{Delimiter, Spacing, Span, Term, TokenNode, TokenTree};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700699 use quote::Tokens;
700
David Tolnay73c98de2017-12-31 15:56:56 -0500701 pub fn punct(s: &str, spans: &[Span], tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700702 assert_eq!(s.len(), spans.len());
703
704 let mut chars = s.chars();
705 let mut spans = spans.iter();
706 let ch = chars.next_back().unwrap();
707 let span = spans.next_back().unwrap();
708 for (ch, span) in chars.zip(spans) {
709 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500710 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700711 kind: TokenNode::Op(ch, Spacing::Joint),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700712 });
713 }
714
715 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500716 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700717 kind: TokenNode::Op(ch, Spacing::Alone),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700718 });
719 }
720
David Tolnay73c98de2017-12-31 15:56:56 -0500721 pub fn keyword(s: &str, span: &Span, tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700722 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500723 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700724 kind: TokenNode::Term(Term::intern(s)),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700725 });
726 }
727
728 pub fn delim<F>(s: &str, span: &Span, tokens: &mut Tokens, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500729 where
730 F: FnOnce(&mut Tokens),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700731 {
David Tolnay00ab6982017-12-31 18:15:06 -0500732 let delim = match s {
733 "(" => Delimiter::Parenthesis,
734 "[" => Delimiter::Bracket,
735 "{" => Delimiter::Brace,
736 " " => Delimiter::None,
737 _ => panic!("unknown delimiter: {}", s),
738 };
739 let mut inner = Tokens::new();
740 f(&mut inner);
741 tokens.append(TokenTree {
742 span: *span,
743 kind: TokenNode::Group(delim, inner.into()),
744 });
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700745 }
746}