blob: 706a3f13c0babada4ff456b79a0b0d854eea3fe9 [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]
125 pub struct $name(pub [Span; $len]);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700126
David Tolnay0bdb0552017-12-27 21:31:51 -0500127 impl $name {
128 pub fn new(span: Span) -> Self {
129 $name([span; $len])
130 }
131 }
132
Nika Layzelld73a3652017-10-24 08:57:05 -0400133 #[cfg(feature = "extra-traits")]
134 impl ::std::fmt::Debug for $name {
135 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
David Tolnay98942562017-12-26 21:24:35 -0500136 f.write_str(stringify!($name))
Nika Layzelld73a3652017-10-24 08:57:05 -0400137 }
138 }
139
David Tolnay98942562017-12-26 21:24:35 -0500140 #[cfg(feature = "extra-traits")]
141 impl ::std::cmp::Eq for $name {}
142
143 #[cfg(feature = "extra-traits")]
144 impl ::std::cmp::PartialEq for $name {
145 fn eq(&self, _other: &$name) -> bool {
146 true
147 }
148 }
149
150 #[cfg(feature = "extra-traits")]
151 impl ::std::hash::Hash for $name {
152 fn hash<H>(&self, _state: &mut H)
153 where H: ::std::hash::Hasher
154 {}
155 }
156
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700157 #[cfg(feature = "printing")]
158 impl ::quote::ToTokens for $name {
159 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500160 printing::punct($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700161 }
162 }
163
164 #[cfg(feature = "parsing")]
165 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800166 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500167 parsing::punct($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700168 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800169
170 fn description() -> Option<&'static str> {
171 Some(concat!("`", $s, "`"))
172 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700173 }
174 }
175}
176
David Tolnay73c98de2017-12-31 15:56:56 -0500177macro_rules! token_keyword {
David Tolnay5a20f632017-12-26 22:11:28 -0500178 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700179 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700180 #[derive(Default)]
David Tolnay5a20f632017-12-26 22:11:28 -0500181 #[$doc]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700182 pub struct $name(pub Span);
183
David Tolnay98942562017-12-26 21:24:35 -0500184 #[cfg(feature = "extra-traits")]
185 impl ::std::fmt::Debug for $name {
186 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
187 f.write_str(stringify!($name))
188 }
189 }
190
191 #[cfg(feature = "extra-traits")]
192 impl ::std::cmp::Eq for $name {}
193
194 #[cfg(feature = "extra-traits")]
195 impl ::std::cmp::PartialEq for $name {
196 fn eq(&self, _other: &$name) -> bool {
197 true
198 }
199 }
200
201 #[cfg(feature = "extra-traits")]
202 impl ::std::hash::Hash for $name {
203 fn hash<H>(&self, _state: &mut H)
204 where H: ::std::hash::Hasher
205 {}
206 }
207
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700208 #[cfg(feature = "printing")]
209 impl ::quote::ToTokens for $name {
210 fn to_tokens(&self, tokens: &mut ::quote::Tokens) {
David Tolnay73c98de2017-12-31 15:56:56 -0500211 printing::keyword($s, &self.0, tokens);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700212 }
213 }
214
215 #[cfg(feature = "parsing")]
216 impl ::Synom for $name {
David Tolnaydfc886b2018-01-06 08:03:09 -0800217 fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> {
David Tolnay73c98de2017-12-31 15:56:56 -0500218 parsing::keyword($s, tokens, $name)
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700219 }
220 }
221 }
222}
223
David Tolnay73c98de2017-12-31 15:56:56 -0500224macro_rules! token_delimiter {
David Tolnay5a20f632017-12-26 22:11:28 -0500225 (#[$doc:meta] $s:tt pub struct $name:ident) => {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700226 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700227 #[derive(Default)]
David Tolnay5a20f632017-12-26 22:11:28 -0500228 #[$doc]
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700229 pub struct $name(pub Span);
230
David Tolnay98942562017-12-26 21:24:35 -0500231 #[cfg(feature = "extra-traits")]
232 impl ::std::fmt::Debug for $name {
233 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
234 f.write_str(stringify!($name))
235 }
236 }
237
238 #[cfg(feature = "extra-traits")]
239 impl ::std::cmp::Eq for $name {}
240
241 #[cfg(feature = "extra-traits")]
242 impl ::std::cmp::PartialEq for $name {
243 fn eq(&self, _other: &$name) -> bool {
244 true
245 }
246 }
247
248 #[cfg(feature = "extra-traits")]
249 impl ::std::hash::Hash for $name {
250 fn hash<H>(&self, _state: &mut H)
251 where H: ::std::hash::Hasher
252 {}
253 }
254
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700255 impl $name {
256 #[cfg(feature = "printing")]
257 pub fn surround<F>(&self,
258 tokens: &mut ::quote::Tokens,
259 f: F)
260 where F: FnOnce(&mut ::quote::Tokens)
261 {
262 printing::delim($s, &self.0, tokens, f);
263 }
264
265 #[cfg(feature = "parsing")]
David Tolnaydfc886b2018-01-06 08:03:09 -0800266 pub fn parse<F, R>(tokens: $crate::buffer::Cursor, f: F) -> $crate::synom::PResult<($name, R)>
267 where F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700268 {
269 parsing::delim($s, tokens, $name, f)
270 }
271 }
272 }
273}
274
275tokens! {
David Tolnay73c98de2017-12-31 15:56:56 -0500276 punct: {
David Tolnay5a20f632017-12-26 22:11:28 -0500277 "+" pub struct Add/1 /// `+`
278 "+=" pub struct AddEq/2 /// `+=`
279 "&" pub struct And/1 /// `&`
280 "&&" pub struct AndAnd/2 /// `&&`
281 "&=" pub struct AndEq/2 /// `&=`
282 "@" pub struct At/1 /// `@`
283 "!" pub struct Bang/1 /// `!`
284 "^" pub struct Caret/1 /// `^`
David Tolnay32954ef2017-12-26 22:43:16 -0500285 "^=" pub struct CaretEq/2 /// `^=`
David Tolnay5a20f632017-12-26 22:11:28 -0500286 ":" pub struct Colon/1 /// `:`
287 "::" pub struct Colon2/2 /// `::`
288 "," pub struct Comma/1 /// `,`
289 "/" pub struct Div/1 /// `/`
290 "/=" pub struct DivEq/2 /// `/=`
291 "." pub struct Dot/1 /// `.`
292 ".." pub struct Dot2/2 /// `..`
293 "..." pub struct Dot3/3 /// `...`
294 "..=" pub struct DotDotEq/3 /// `..=`
295 "=" pub struct Eq/1 /// `=`
296 "==" pub struct EqEq/2 /// `==`
297 ">=" pub struct Ge/2 /// `>=`
298 ">" pub struct Gt/1 /// `>`
299 "<=" pub struct Le/2 /// `<=`
300 "<" pub struct Lt/1 /// `<`
301 "*=" pub struct MulEq/2 /// `*=`
302 "!=" pub struct Ne/2 /// `!=`
303 "|" pub struct Or/1 /// `|`
304 "|=" pub struct OrEq/2 /// `|=`
305 "||" pub struct OrOr/2 /// `||`
306 "#" pub struct Pound/1 /// `#`
307 "?" pub struct Question/1 /// `?`
308 "->" pub struct RArrow/2 /// `->`
309 "<-" pub struct LArrow/2 /// `<-`
310 "%" pub struct Rem/1 /// `%`
311 "%=" pub struct RemEq/2 /// `%=`
312 "=>" pub struct Rocket/2 /// `=>`
313 ";" pub struct Semi/1 /// `;`
314 "<<" pub struct Shl/2 /// `<<`
315 "<<=" pub struct ShlEq/3 /// `<<=`
316 ">>" pub struct Shr/2 /// `>>`
317 ">>=" pub struct ShrEq/3 /// `>>=`
318 "*" pub struct Star/1 /// `*`
319 "-" pub struct Sub/1 /// `-`
320 "-=" pub struct SubEq/2 /// `-=`
321 "_" pub struct Underscore/1 /// `_`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700322 }
David Tolnay73c98de2017-12-31 15:56:56 -0500323 delimiter: {
David Tolnay5a20f632017-12-26 22:11:28 -0500324 "{" pub struct Brace /// `{...}`
325 "[" pub struct Bracket /// `[...]`
326 "(" pub struct Paren /// `(...)`
327 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700328 }
David Tolnay73c98de2017-12-31 15:56:56 -0500329 keyword: {
David Tolnay5a20f632017-12-26 22:11:28 -0500330 "as" pub struct As /// `as`
331 "auto" pub struct Auto /// `auto`
332 "box" pub struct Box /// `box`
333 "break" pub struct Break /// `break`
334 "Self" pub struct CapSelf /// `Self`
335 "catch" pub struct Catch /// `catch`
336 "const" pub struct Const /// `const`
337 "continue" pub struct Continue /// `continue`
338 "crate" pub struct Crate /// `crate`
339 "default" pub struct Default /// `default`
340 "do" pub struct Do /// `do`
341 "dyn" pub struct Dyn /// `dyn`
342 "else" pub struct Else /// `else`
343 "enum" pub struct Enum /// `enum`
344 "extern" pub struct Extern /// `extern`
345 "fn" pub struct Fn /// `fn`
346 "for" pub struct For /// `for`
347 "if" pub struct If /// `if`
348 "impl" pub struct Impl /// `impl`
349 "in" pub struct In /// `in`
350 "let" pub struct Let /// `let`
351 "loop" pub struct Loop /// `loop`
352 "macro" pub struct Macro /// `macro`
353 "match" pub struct Match /// `match`
354 "mod" pub struct Mod /// `mod`
355 "move" pub struct Move /// `move`
356 "mut" pub struct Mut /// `mut`
357 "pub" pub struct Pub /// `pub`
358 "ref" pub struct Ref /// `ref`
359 "return" pub struct Return /// `return`
360 "self" pub struct Self_ /// `self`
361 "static" pub struct Static /// `static`
362 "struct" pub struct Struct /// `struct`
363 "super" pub struct Super /// `super`
364 "trait" pub struct Trait /// `trait`
365 "type" pub struct Type /// `type`
366 "union" pub struct Union /// `union`
367 "unsafe" pub struct Unsafe /// `unsafe`
368 "use" pub struct Use /// `use`
369 "where" pub struct Where /// `where`
370 "while" pub struct While /// `while`
371 "yield" pub struct Yield /// `yield`
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700372 }
373}
374
David Tolnayf005f962018-01-06 21:19:41 -0800375/// A type-macro that expands to the name of the Rust type representation of a
376/// given token.
377///
378/// See the [token module] documentation for details and examples.
379///
380/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800381// Unfortunate duplication due to a rustdoc bug.
382// https://github.com/rust-lang/rust/issues/45939
383#[macro_export]
384macro_rules! Token {
David Tolnay32954ef2017-12-26 22:43:16 -0500385 (+) => { $crate::token::Add };
386 (+=) => { $crate::token::AddEq };
387 (&) => { $crate::token::And };
388 (&&) => { $crate::token::AndAnd };
389 (&=) => { $crate::token::AndEq };
390 (@) => { $crate::token::At };
391 (!) => { $crate::token::Bang };
392 (^) => { $crate::token::Caret };
393 (^=) => { $crate::token::CaretEq };
394 (:) => { $crate::token::Colon };
395 (::) => { $crate::token::Colon2 };
396 (,) => { $crate::token::Comma };
397 (/) => { $crate::token::Div };
398 (/=) => { $crate::token::DivEq };
399 (.) => { $crate::token::Dot };
400 (..) => { $crate::token::Dot2 };
401 (...) => { $crate::token::Dot3 };
402 (..=) => { $crate::token::DotDotEq };
403 (=) => { $crate::token::Eq };
404 (==) => { $crate::token::EqEq };
405 (>=) => { $crate::token::Ge };
406 (>) => { $crate::token::Gt };
407 (<=) => { $crate::token::Le };
408 (<) => { $crate::token::Lt };
409 (*=) => { $crate::token::MulEq };
410 (!=) => { $crate::token::Ne };
411 (|) => { $crate::token::Or };
412 (|=) => { $crate::token::OrEq };
413 (||) => { $crate::token::OrOr };
414 (#) => { $crate::token::Pound };
415 (?) => { $crate::token::Question };
416 (->) => { $crate::token::RArrow };
417 (<-) => { $crate::token::LArrow };
418 (%) => { $crate::token::Rem };
419 (%=) => { $crate::token::RemEq };
420 (=>) => { $crate::token::Rocket };
421 (;) => { $crate::token::Semi };
422 (<<) => { $crate::token::Shl };
423 (<<=) => { $crate::token::ShlEq };
424 (>>) => { $crate::token::Shr };
425 (>>=) => { $crate::token::ShrEq };
426 (*) => { $crate::token::Star };
427 (-) => { $crate::token::Sub };
428 (-=) => { $crate::token::SubEq };
429 (_) => { $crate::token::Underscore };
430 (as) => { $crate::token::As };
431 (auto) => { $crate::token::Auto };
432 (box) => { $crate::token::Box };
433 (break) => { $crate::token::Break };
434 (Self) => { $crate::token::CapSelf };
435 (catch) => { $crate::token::Catch };
436 (const) => { $crate::token::Const };
437 (continue) => { $crate::token::Continue };
438 (crate) => { $crate::token::Crate };
439 (default) => { $crate::token::Default };
440 (do) => { $crate::token::Do };
441 (dyn) => { $crate::token::Dyn };
442 (else) => { $crate::token::Else };
443 (enum) => { $crate::token::Enum };
444 (extern) => { $crate::token::Extern };
445 (fn) => { $crate::token::Fn };
446 (for) => { $crate::token::For };
447 (if) => { $crate::token::If };
448 (impl) => { $crate::token::Impl };
449 (in) => { $crate::token::In };
450 (let) => { $crate::token::Let };
451 (loop) => { $crate::token::Loop };
452 (macro) => { $crate::token::Macro };
453 (match) => { $crate::token::Match };
454 (mod) => { $crate::token::Mod };
455 (move) => { $crate::token::Move };
456 (mut) => { $crate::token::Mut };
457 (pub) => { $crate::token::Pub };
458 (ref) => { $crate::token::Ref };
459 (return) => { $crate::token::Return };
460 (self) => { $crate::token::Self_ };
461 (static) => { $crate::token::Static };
462 (struct) => { $crate::token::Struct };
463 (super) => { $crate::token::Super };
464 (trait) => { $crate::token::Trait };
465 (type) => { $crate::token::Type };
466 (union) => { $crate::token::Union };
467 (unsafe) => { $crate::token::Unsafe };
468 (use) => { $crate::token::Use };
469 (where) => { $crate::token::Where };
470 (while) => { $crate::token::While };
471 (yield) => { $crate::token::Yield };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800472}
473
David Tolnayf005f962018-01-06 21:19:41 -0800474/// Parse a single Rust punctuation token.
475///
476/// See the [token module] documentation for details and examples.
477///
478/// [token module]: token/index.html
David Tolnay0fbe3282017-12-26 21:46:16 -0500479#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800480#[macro_export]
481macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500482 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
483 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
484 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
485 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
486 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
487 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
488 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
489 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
490 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
491 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
492 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
493 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
494 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
495 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
496 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
497 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
498 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
499 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
500 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
501 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
502 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
503 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
504 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
505 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
506 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
507 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
508 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
509 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
510 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
511 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
512 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
513 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
514 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
515 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
516 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
517 ($i:expr, =>) => { call!($i, <$crate::token::Rocket as $crate::synom::Synom>::parse) };
518 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
519 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
520 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
521 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
522 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
523 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
524 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
525 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
526 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800527}
528
David Tolnayf005f962018-01-06 21:19:41 -0800529/// Parse a single Rust keyword token.
530///
531/// See the [token module] documentation for details and examples.
532///
533/// [token module]: token/index.html
David Tolnay0fbe3282017-12-26 21:46:16 -0500534#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800535#[macro_export]
536macro_rules! keyword {
David Tolnay32954ef2017-12-26 22:43:16 -0500537 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
538 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
539 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
540 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
541 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
542 ($i:expr, catch) => { call!($i, <$crate::token::Catch as $crate::synom::Synom>::parse) };
543 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
544 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
545 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
546 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
547 ($i:expr, do) => { call!($i, <$crate::token::Do as $crate::synom::Synom>::parse) };
548 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
549 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
550 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
551 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
552 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
553 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
554 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
555 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
556 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
557 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
558 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
559 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
560 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
561 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
562 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
563 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
564 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
565 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
566 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
567 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
568 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
569 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
570 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
571 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
572 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
573 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
574 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
575 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
576 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
577 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
578 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800579}
580
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700581#[cfg(feature = "parsing")]
582mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500583 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700584
David Tolnaydfc886b2018-01-06 08:03:09 -0800585 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500586 use parse_error;
587 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700588
589 pub trait FromSpans: Sized {
590 fn from_spans(spans: &[Span]) -> Self;
591 }
592
593 impl FromSpans for [Span; 1] {
594 fn from_spans(spans: &[Span]) -> Self {
595 [spans[0]]
596 }
597 }
598
599 impl FromSpans for [Span; 2] {
600 fn from_spans(spans: &[Span]) -> Self {
601 [spans[0], spans[1]]
602 }
603 }
604
605 impl FromSpans for [Span; 3] {
606 fn from_spans(spans: &[Span]) -> Self {
607 [spans[0], spans[1], spans[2]]
608 }
609 }
610
David Tolnay73c98de2017-12-31 15:56:56 -0500611 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 -0500612 where
613 T: FromSpans,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700614 {
615 let mut spans = [Span::default(); 3];
Alex Crichton954046c2017-05-30 21:49:42 -0700616 assert!(s.len() <= spans.len());
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700617 let chars = s.chars();
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700618
Alex Crichton954046c2017-05-30 21:49:42 -0700619 for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400620 match tokens.op() {
David Tolnay65729482017-12-31 16:14:50 -0500621 Some((span, op, kind, rest)) if op == ch => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400622 if i != s.len() - 1 {
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700623 match kind {
624 Spacing::Joint => {}
625 _ => return parse_error(),
Michael Layzell0a1a6632017-06-02 18:07:43 -0400626 }
627 }
David Tolnay98942562017-12-26 21:24:35 -0500628 *slot = span;
Michael Layzell0a1a6632017-06-02 18:07:43 -0400629 tokens = rest;
Alex Crichton954046c2017-05-30 21:49:42 -0700630 }
David Tolnay51382052017-12-27 13:46:21 -0500631 _ => return parse_error(),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700632 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700633 }
David Tolnayf4aa6b42017-12-31 16:40:33 -0500634 Ok((new(T::from_spans(&spans)), tokens))
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700635 }
636
David Tolnay73c98de2017-12-31 15:56:56 -0500637 pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> {
David Tolnay65729482017-12-31 16:14:50 -0500638 if let Some((span, term, rest)) = tokens.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500639 if term.as_str() == keyword {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500640 return Ok((new(span), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400641 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700642 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400643 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700644 }
645
David Tolnay51382052017-12-27 13:46:21 -0500646 pub fn delim<'a, F, R, T>(
647 delim: &str,
648 tokens: Cursor<'a>,
649 new: fn(Span) -> T,
650 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500651 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500652 where
653 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700654 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400655 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700656 let delim = match delim {
657 "(" => Delimiter::Parenthesis,
658 "{" => Delimiter::Brace,
659 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400660 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700661 _ => panic!("unknown delimiter: {}", delim),
662 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700663
David Tolnay65729482017-12-31 16:14:50 -0500664 if let Some((inside, span, rest)) = tokens.group(delim) {
665 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500666 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400667 if remaining.eof() {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500668 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400669 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700670 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400671 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700672 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700673 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400674 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700675 }
676}
677
678#[cfg(feature = "printing")]
679mod printing {
David Tolnayf2cfd722017-12-31 18:02:51 -0500680 use proc_macro2::{Delimiter, Spacing, Span, Term, TokenNode, TokenTree};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700681 use quote::Tokens;
682
David Tolnay73c98de2017-12-31 15:56:56 -0500683 pub fn punct(s: &str, spans: &[Span], tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700684 assert_eq!(s.len(), spans.len());
685
686 let mut chars = s.chars();
687 let mut spans = spans.iter();
688 let ch = chars.next_back().unwrap();
689 let span = spans.next_back().unwrap();
690 for (ch, span) in chars.zip(spans) {
691 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500692 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700693 kind: TokenNode::Op(ch, Spacing::Joint),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700694 });
695 }
696
697 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500698 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700699 kind: TokenNode::Op(ch, Spacing::Alone),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700700 });
701 }
702
David Tolnay73c98de2017-12-31 15:56:56 -0500703 pub fn keyword(s: &str, span: &Span, tokens: &mut Tokens) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700704 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500705 span: *span,
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -0700706 kind: TokenNode::Term(Term::intern(s)),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700707 });
708 }
709
710 pub fn delim<F>(s: &str, span: &Span, tokens: &mut Tokens, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500711 where
712 F: FnOnce(&mut Tokens),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700713 {
David Tolnay00ab6982017-12-31 18:15:06 -0500714 let delim = match s {
715 "(" => Delimiter::Parenthesis,
716 "[" => Delimiter::Bracket,
717 "{" => Delimiter::Brace,
718 " " => Delimiter::None,
719 _ => panic!("unknown delimiter: {}", s),
720 };
721 let mut inner = Tokens::new();
722 f(&mut inner);
723 tokens.append(TokenTree {
724 span: *span,
725 kind: TokenNode::Group(delim, inner.into()),
726 });
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700727 }
728}