blob: 0dd00a2f5b629b948de5782fcabd5117fbdce7a6 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnaye79ae182018-01-06 19:23:37 -08009//! Tokens representing Rust punctuation, keywords, and delimiters.
Alex Crichton954046c2017-05-30 21:49:42 -070010//!
David Tolnaye79ae182018-01-06 19:23:37 -080011//! The type names in this module can be difficult to keep straight, so we
12//! prefer to use the [`Token!`] macro instead. This is a type-macro that
13//! expands to the token type of the given token.
14//!
15//! [`Token!`]: ../macro.Token.html
16//!
17//! # Example
18//!
19//! The [`ItemStatic`] syntax tree node is defined like this.
20//!
21//! [`ItemStatic`]: ../struct.ItemStatic.html
22//!
23//! ```
24//! # #[macro_use]
25//! # extern crate syn;
26//! #
David Tolnaye303b7c2018-05-20 16:46:35 -070027//! # use syn::{Attribute, Visibility, Ident, Type, Expr};
David Tolnaye79ae182018-01-06 19:23:37 -080028//! #
29//! pub struct ItemStatic {
30//! pub attrs: Vec<Attribute>,
31//! pub vis: Visibility,
32//! pub static_token: Token![static],
33//! pub mutability: Option<Token![mut]>,
34//! pub ident: Ident,
35//! pub colon_token: Token![:],
36//! pub ty: Box<Type>,
37//! pub eq_token: Token![=],
38//! pub expr: Box<Expr>,
39//! pub semi_token: Token![;],
40//! }
41//! #
42//! # fn main() {}
43//! ```
44//!
45//! # Parsing
46//!
47//! These tokens can be parsed using the [`Synom`] trait and the parser
48//! combinator macros [`punct!`], [`keyword!`], [`parens!`], [`braces!`], and
49//! [`brackets!`].
50//!
51//! [`Synom`]: ../synom/trait.Synom.html
52//! [`punct!`]: ../macro.punct.html
53//! [`keyword!`]: ../macro.keyword.html
54//! [`parens!`]: ../macro.parens.html
55//! [`braces!`]: ../macro.braces.html
56//! [`brackets!`]: ../macro.brackets.html
57//!
58//! ```
59//! #[macro_use]
60//! extern crate syn;
61//!
62//! use syn::synom::Synom;
David Tolnaye303b7c2018-05-20 16:46:35 -070063//! use syn::{Attribute, Visibility, Ident, Type, Expr};
David Tolnaye79ae182018-01-06 19:23:37 -080064//! #
65//! # struct ItemStatic;
66//! # use syn::ItemStatic as SynItemStatic;
67//!
68//! // Parse the ItemStatic struct shown above.
69//! impl Synom for ItemStatic {
70//! named!(parse -> Self, do_parse!(
71//! # (ItemStatic)
72//! # ));
73//! # }
74//! #
75//! # mod example {
76//! # use super::*;
77//! # use super::SynItemStatic as ItemStatic;
78//! #
79//! # named!(parse -> ItemStatic, do_parse!(
David Tolnayf8106f82018-08-25 21:17:45 -040080//! attrs: many0!(Attribute::old_parse_outer) >>
David Tolnaye79ae182018-01-06 19:23:37 -080081//! 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 Tolnay776f8e02018-08-24 22:32:10 -0400100use std;
David Tolnayd9836922018-08-25 18:05:36 -0400101#[cfg(feature = "parsing")]
102use std::cell::Cell;
David Tolnay776f8e02018-08-24 22:32:10 -0400103#[cfg(feature = "extra-traits")]
104use std::cmp;
105#[cfg(feature = "extra-traits")]
106use std::fmt::{self, Debug};
107#[cfg(feature = "extra-traits")]
108use std::hash::{Hash, Hasher};
David Tolnayd9836922018-08-25 18:05:36 -0400109#[cfg(feature = "parsing")]
110use std::rc::Rc;
David Tolnay776f8e02018-08-24 22:32:10 -0400111
David Tolnay2d84a082018-08-25 16:31:38 -0400112#[cfg(feature = "parsing")]
113use proc_macro2::Delimiter;
David Tolnay8c39ac52018-08-25 08:46:21 -0400114#[cfg(any(feature = "printing", feature = "parsing"))]
115use proc_macro2::Spacing;
David Tolnay65fb5662018-05-20 20:02:28 -0700116use proc_macro2::{Ident, Span};
Sergio Benitezd14d5362018-04-28 15:38:25 -0700117#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400118use proc_macro2::{Punct, TokenStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400119#[cfg(feature = "printing")]
120use quote::{ToTokens, TokenStreamExt};
121
122#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400123use error::Result;
124#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400125use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400126#[cfg(feature = "parsing")]
David Tolnayd9836922018-08-25 18:05:36 -0400127use parse::{Lookahead1, Parse, ParseBuffer, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400128use span::IntoSpans;
129
130/// Marker trait for types that represent single tokens.
131///
132/// This trait is sealed and cannot be implemented for types outside of Syn.
133#[cfg(feature = "parsing")]
134pub trait Token: private::Sealed {
135 // Not public API.
136 #[doc(hidden)]
137 fn peek(lookahead: &Lookahead1) -> bool;
138
139 // Not public API.
140 #[doc(hidden)]
141 fn display() -> String;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700142}
143
144#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400145mod private {
146 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700147}
148
David Tolnay776f8e02018-08-24 22:32:10 -0400149macro_rules! impl_token {
150 ($token:tt $name:ident) => {
151 #[cfg(feature = "parsing")]
152 impl Token for $name {
153 fn peek(lookahead: &Lookahead1) -> bool {
David Tolnayd9836922018-08-25 18:05:36 -0400154 // TODO factor out in a way that can be compiled just once
155 let scope = Span::call_site();
156 let cursor = lookahead.cursor();
157 let unexpected = Rc::new(Cell::new(None));
158 ParseBuffer::new(scope, cursor, unexpected)
159 .parse::<Self>()
160 .is_ok()
David Tolnay776f8e02018-08-24 22:32:10 -0400161 }
162
163 fn display() -> String {
164 concat!("`", $token, "`").to_owned()
165 }
166 }
167
168 #[cfg(feature = "parsing")]
169 impl private::Sealed for $name {}
170 };
171}
172
173macro_rules! define_keywords {
174 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
175 $(
176 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
177 #[$doc]
178 ///
179 /// Don't try to remember the name of this type -- use the [`Token!`]
180 /// macro instead.
181 ///
182 /// [`Token!`]: index.html
183 pub struct $name {
184 pub span: Span,
185 }
186
187 #[doc(hidden)]
188 #[allow(non_snake_case)]
189 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
190 $name {
191 span: span.into_spans()[0],
192 }
193 }
194
195 impl_token!($token $name);
196
197 impl std::default::Default for $name {
198 fn default() -> Self {
199 $name(Span::call_site())
200 }
201 }
202
203 #[cfg(feature = "extra-traits")]
204 impl Debug for $name {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206 f.write_str(stringify!($name))
207 }
208 }
209
210 #[cfg(feature = "extra-traits")]
211 impl cmp::Eq for $name {}
212
213 #[cfg(feature = "extra-traits")]
214 impl PartialEq for $name {
215 fn eq(&self, _other: &$name) -> bool {
216 true
217 }
218 }
219
220 #[cfg(feature = "extra-traits")]
221 impl Hash for $name {
222 fn hash<H: Hasher>(&self, _state: &mut H) {}
223 }
224
225 #[cfg(feature = "printing")]
226 impl ToTokens for $name {
227 fn to_tokens(&self, tokens: &mut TokenStream) {
228 printing::keyword($token, &self.span, tokens);
229 }
230 }
231
232 #[cfg(feature = "parsing")]
233 impl Parse for $name {
234 fn parse(input: ParseStream) -> Result<Self> {
235 parsing::keyword(input, $token).map($name)
236 }
237 }
238 )*
239 };
240}
241
242macro_rules! define_punctuation_structs {
243 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
244 $(
245 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
246 #[$doc]
247 ///
248 /// Don't try to remember the name of this type -- use the [`Token!`]
249 /// macro instead.
250 ///
251 /// [`Token!`]: index.html
252 pub struct $name {
253 pub spans: [Span; $len],
254 }
255
256 #[doc(hidden)]
257 #[allow(non_snake_case)]
258 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
259 $name {
260 spans: spans.into_spans(),
261 }
262 }
263
264 impl_token!($token $name);
265
266 impl std::default::Default for $name {
267 fn default() -> Self {
268 $name([Span::call_site(); $len])
269 }
270 }
271
272 #[cfg(feature = "extra-traits")]
273 impl Debug for $name {
274 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
275 f.write_str(stringify!($name))
276 }
277 }
278
279 #[cfg(feature = "extra-traits")]
280 impl cmp::Eq for $name {}
281
282 #[cfg(feature = "extra-traits")]
283 impl PartialEq for $name {
284 fn eq(&self, _other: &$name) -> bool {
285 true
286 }
287 }
288
289 #[cfg(feature = "extra-traits")]
290 impl Hash for $name {
291 fn hash<H: Hasher>(&self, _state: &mut H) {}
292 }
293 )*
294 };
295}
296
297macro_rules! define_punctuation {
298 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
299 $(
300 define_punctuation_structs! {
301 $token pub struct $name/$len #[$doc]
302 }
303
304 #[cfg(feature = "printing")]
305 impl ToTokens for $name {
306 fn to_tokens(&self, tokens: &mut TokenStream) {
307 printing::punct($token, &self.spans, tokens);
308 }
309 }
310
311 #[cfg(feature = "parsing")]
312 impl Parse for $name {
313 fn parse(input: ParseStream) -> Result<Self> {
314 parsing::punct(input, $token).map($name::<[Span; $len]>)
315 }
316 }
317 )*
318 };
319}
320
321macro_rules! define_delimiters {
322 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
323 $(
324 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
325 #[$doc]
326 pub struct $name {
327 pub span: Span,
328 }
329
330 #[doc(hidden)]
331 #[allow(non_snake_case)]
332 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
333 $name {
334 span: span.into_spans()[0],
335 }
336 }
337
338 impl std::default::Default for $name {
339 fn default() -> Self {
340 $name(Span::call_site())
341 }
342 }
343
344 #[cfg(feature = "extra-traits")]
345 impl Debug for $name {
346 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
347 f.write_str(stringify!($name))
348 }
349 }
350
351 #[cfg(feature = "extra-traits")]
352 impl cmp::Eq for $name {}
353
354 #[cfg(feature = "extra-traits")]
355 impl PartialEq for $name {
356 fn eq(&self, _other: &$name) -> bool {
357 true
358 }
359 }
360
361 #[cfg(feature = "extra-traits")]
362 impl Hash for $name {
363 fn hash<H: Hasher>(&self, _state: &mut H) {}
364 }
365
366 impl $name {
367 #[cfg(feature = "printing")]
368 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
369 where
370 F: FnOnce(&mut TokenStream),
371 {
372 printing::delim($token, &self.span, tokens, f);
373 }
374
375 #[cfg(feature = "parsing")]
376 pub fn parse<F, R>(
377 tokens: $crate::buffer::Cursor,
378 f: F,
379 ) -> $crate::synom::PResult<($name, R)>
380 where
381 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
382 {
383 parsing::delim($token, tokens, $name, f)
384 }
385 }
David Tolnay2d84a082018-08-25 16:31:38 -0400386
387 #[cfg(feature = "parsing")]
388 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400389 )*
390 };
391}
392
393define_punctuation_structs! {
394 "'" pub struct Apostrophe/1 /// `'`
395 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700396}
397
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700398// Implement Clone anyway because it is required for cloning Lifetime.
399#[cfg(not(feature = "clone-impls"))]
400impl Clone for Apostrophe {
401 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400402 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700403 }
404}
405
Alex Crichton131308c2018-05-18 14:00:24 -0700406#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400407impl ToTokens for Apostrophe {
408 fn to_tokens(&self, tokens: &mut TokenStream) {
409 let mut token = Punct::new('\'', Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400410 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700411 tokens.append(token);
412 }
413}
414
415#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400416impl Parse for Apostrophe {
417 fn parse(input: ParseStream) -> Result<Self> {
418 input.step_cursor(|cursor| {
419 if let Some((punct, rest)) = cursor.punct() {
420 if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint {
421 return Ok((Apostrophe(punct.span()), rest));
Alex Crichton131308c2018-05-18 14:00:24 -0700422 }
423 }
David Tolnay776f8e02018-08-24 22:32:10 -0400424 Err(cursor.error("expected `'`"))
425 })
Alex Crichton131308c2018-05-18 14:00:24 -0700426 }
427}
428
David Tolnay776f8e02018-08-24 22:32:10 -0400429#[cfg(feature = "printing")]
430impl ToTokens for Underscore {
431 fn to_tokens(&self, tokens: &mut TokenStream) {
432 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700433 }
David Tolnay776f8e02018-08-24 22:32:10 -0400434}
435
436#[cfg(feature = "parsing")]
437impl Parse for Underscore {
438 fn parse(input: ParseStream) -> Result<Self> {
439 input.step_cursor(|cursor| {
440 if let Some((ident, rest)) = cursor.ident() {
441 if ident == "_" {
442 return Ok((Underscore(ident.span()), rest));
443 }
444 }
445 if let Some((punct, rest)) = cursor.punct() {
446 if punct.as_char() == '_' {
447 return Ok((Underscore(punct.span()), rest));
448 }
449 }
450 Err(cursor.error("expected `_`"))
451 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700452 }
David Tolnay776f8e02018-08-24 22:32:10 -0400453}
454
David Tolnay2d84a082018-08-25 16:31:38 -0400455#[cfg(feature = "parsing")]
456impl Token for Paren {
457 fn peek(lookahead: &Lookahead1) -> bool {
458 lookahead::is_delimiter(lookahead, Delimiter::Parenthesis)
459 }
460
461 fn display() -> String {
462 "parentheses".to_owned()
463 }
464}
465
466#[cfg(feature = "parsing")]
467impl Token for Brace {
468 fn peek(lookahead: &Lookahead1) -> bool {
469 lookahead::is_delimiter(lookahead, Delimiter::Brace)
470 }
471
472 fn display() -> String {
473 "curly braces".to_owned()
474 }
475}
476
477#[cfg(feature = "parsing")]
478impl Token for Bracket {
479 fn peek(lookahead: &Lookahead1) -> bool {
480 lookahead::is_delimiter(lookahead, Delimiter::Bracket)
481 }
482
483 fn display() -> String {
484 "square brackets".to_owned()
485 }
486}
487
David Tolnay776f8e02018-08-24 22:32:10 -0400488define_keywords! {
489 "as" pub struct As /// `as`
490 "async" pub struct Async /// `async`
491 "auto" pub struct Auto /// `auto`
492 "box" pub struct Box /// `box`
493 "break" pub struct Break /// `break`
494 "Self" pub struct CapSelf /// `Self`
495 "const" pub struct Const /// `const`
496 "continue" pub struct Continue /// `continue`
497 "crate" pub struct Crate /// `crate`
498 "default" pub struct Default /// `default`
499 "dyn" pub struct Dyn /// `dyn`
500 "else" pub struct Else /// `else`
501 "enum" pub struct Enum /// `enum`
502 "existential" pub struct Existential /// `existential`
503 "extern" pub struct Extern /// `extern`
504 "fn" pub struct Fn /// `fn`
505 "for" pub struct For /// `for`
506 "if" pub struct If /// `if`
507 "impl" pub struct Impl /// `impl`
508 "in" pub struct In /// `in`
509 "let" pub struct Let /// `let`
510 "loop" pub struct Loop /// `loop`
511 "macro" pub struct Macro /// `macro`
512 "match" pub struct Match /// `match`
513 "mod" pub struct Mod /// `mod`
514 "move" pub struct Move /// `move`
515 "mut" pub struct Mut /// `mut`
516 "pub" pub struct Pub /// `pub`
517 "ref" pub struct Ref /// `ref`
518 "return" pub struct Return /// `return`
519 "self" pub struct Self_ /// `self`
520 "static" pub struct Static /// `static`
521 "struct" pub struct Struct /// `struct`
522 "super" pub struct Super /// `super`
523 "trait" pub struct Trait /// `trait`
524 "try" pub struct Try /// `try`
525 "type" pub struct Type /// `type`
526 "union" pub struct Union /// `union`
527 "unsafe" pub struct Unsafe /// `unsafe`
528 "use" pub struct Use /// `use`
529 "where" pub struct Where /// `where`
530 "while" pub struct While /// `while`
531 "yield" pub struct Yield /// `yield`
532}
533
534define_punctuation! {
535 "+" pub struct Add/1 /// `+`
536 "+=" pub struct AddEq/2 /// `+=`
537 "&" pub struct And/1 /// `&`
538 "&&" pub struct AndAnd/2 /// `&&`
539 "&=" pub struct AndEq/2 /// `&=`
540 "@" pub struct At/1 /// `@`
541 "!" pub struct Bang/1 /// `!`
542 "^" pub struct Caret/1 /// `^`
543 "^=" pub struct CaretEq/2 /// `^=`
544 ":" pub struct Colon/1 /// `:`
545 "::" pub struct Colon2/2 /// `::`
546 "," pub struct Comma/1 /// `,`
547 "/" pub struct Div/1 /// `/`
548 "/=" pub struct DivEq/2 /// `/=`
549 "$" pub struct Dollar/1 /// `$`
550 "." pub struct Dot/1 /// `.`
551 ".." pub struct Dot2/2 /// `..`
552 "..." pub struct Dot3/3 /// `...`
553 "..=" pub struct DotDotEq/3 /// `..=`
554 "=" pub struct Eq/1 /// `=`
555 "==" pub struct EqEq/2 /// `==`
556 ">=" pub struct Ge/2 /// `>=`
557 ">" pub struct Gt/1 /// `>`
558 "<=" pub struct Le/2 /// `<=`
559 "<" pub struct Lt/1 /// `<`
560 "*=" pub struct MulEq/2 /// `*=`
561 "!=" pub struct Ne/2 /// `!=`
562 "|" pub struct Or/1 /// `|`
563 "|=" pub struct OrEq/2 /// `|=`
564 "||" pub struct OrOr/2 /// `||`
565 "#" pub struct Pound/1 /// `#`
566 "?" pub struct Question/1 /// `?`
567 "->" pub struct RArrow/2 /// `->`
568 "<-" pub struct LArrow/2 /// `<-`
569 "%" pub struct Rem/1 /// `%`
570 "%=" pub struct RemEq/2 /// `%=`
571 "=>" pub struct FatArrow/2 /// `=>`
572 ";" pub struct Semi/1 /// `;`
573 "<<" pub struct Shl/2 /// `<<`
574 "<<=" pub struct ShlEq/3 /// `<<=`
575 ">>" pub struct Shr/2 /// `>>`
576 ">>=" pub struct ShrEq/3 /// `>>=`
577 "*" pub struct Star/1 /// `*`
578 "-" pub struct Sub/1 /// `-`
579 "-=" pub struct SubEq/2 /// `-=`
580}
581
582define_delimiters! {
583 "{" pub struct Brace /// `{...}`
584 "[" pub struct Bracket /// `[...]`
585 "(" pub struct Paren /// `(...)`
586 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700587}
588
David Tolnayf005f962018-01-06 21:19:41 -0800589/// A type-macro that expands to the name of the Rust type representation of a
590/// given token.
591///
592/// See the [token module] documentation for details and examples.
593///
594/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800595// Unfortunate duplication due to a rustdoc bug.
596// https://github.com/rust-lang/rust/issues/45939
597#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700598#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800599macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400600 (as) => { $crate::token::As };
601 (async) => { $crate::token::Async };
602 (auto) => { $crate::token::Auto };
603 (box) => { $crate::token::Box };
604 (break) => { $crate::token::Break };
605 (Self) => { $crate::token::CapSelf };
606 (const) => { $crate::token::Const };
607 (continue) => { $crate::token::Continue };
608 (crate) => { $crate::token::Crate };
609 (default) => { $crate::token::Default };
610 (dyn) => { $crate::token::Dyn };
611 (else) => { $crate::token::Else };
612 (enum) => { $crate::token::Enum };
613 (existential) => { $crate::token::Existential };
614 (extern) => { $crate::token::Extern };
615 (fn) => { $crate::token::Fn };
616 (for) => { $crate::token::For };
617 (if) => { $crate::token::If };
618 (impl) => { $crate::token::Impl };
619 (in) => { $crate::token::In };
620 (let) => { $crate::token::Let };
621 (loop) => { $crate::token::Loop };
622 (macro) => { $crate::token::Macro };
623 (match) => { $crate::token::Match };
624 (mod) => { $crate::token::Mod };
625 (move) => { $crate::token::Move };
626 (mut) => { $crate::token::Mut };
627 (pub) => { $crate::token::Pub };
628 (ref) => { $crate::token::Ref };
629 (return) => { $crate::token::Return };
630 (self) => { $crate::token::Self_ };
631 (static) => { $crate::token::Static };
632 (struct) => { $crate::token::Struct };
633 (super) => { $crate::token::Super };
634 (trait) => { $crate::token::Trait };
635 (try) => { $crate::token::Try };
636 (type) => { $crate::token::Type };
637 (union) => { $crate::token::Union };
638 (unsafe) => { $crate::token::Unsafe };
639 (use) => { $crate::token::Use };
640 (where) => { $crate::token::Where };
641 (while) => { $crate::token::While };
642 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400643 (+) => { $crate::token::Add };
644 (+=) => { $crate::token::AddEq };
645 (&) => { $crate::token::And };
646 (&&) => { $crate::token::AndAnd };
647 (&=) => { $crate::token::AndEq };
648 (@) => { $crate::token::At };
649 (!) => { $crate::token::Bang };
650 (^) => { $crate::token::Caret };
651 (^=) => { $crate::token::CaretEq };
652 (:) => { $crate::token::Colon };
653 (::) => { $crate::token::Colon2 };
654 (,) => { $crate::token::Comma };
655 (/) => { $crate::token::Div };
656 (/=) => { $crate::token::DivEq };
657 (.) => { $crate::token::Dot };
658 (..) => { $crate::token::Dot2 };
659 (...) => { $crate::token::Dot3 };
660 (..=) => { $crate::token::DotDotEq };
661 (=) => { $crate::token::Eq };
662 (==) => { $crate::token::EqEq };
663 (>=) => { $crate::token::Ge };
664 (>) => { $crate::token::Gt };
665 (<=) => { $crate::token::Le };
666 (<) => { $crate::token::Lt };
667 (*=) => { $crate::token::MulEq };
668 (!=) => { $crate::token::Ne };
669 (|) => { $crate::token::Or };
670 (|=) => { $crate::token::OrEq };
671 (||) => { $crate::token::OrOr };
672 (#) => { $crate::token::Pound };
673 (?) => { $crate::token::Question };
674 (->) => { $crate::token::RArrow };
675 (<-) => { $crate::token::LArrow };
676 (%) => { $crate::token::Rem };
677 (%=) => { $crate::token::RemEq };
678 (=>) => { $crate::token::FatArrow };
679 (;) => { $crate::token::Semi };
680 (<<) => { $crate::token::Shl };
681 (<<=) => { $crate::token::ShlEq };
682 (>>) => { $crate::token::Shr };
683 (>>=) => { $crate::token::ShrEq };
684 (*) => { $crate::token::Star };
685 (-) => { $crate::token::Sub };
686 (-=) => { $crate::token::SubEq };
687 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800688}
689
David Tolnayf005f962018-01-06 21:19:41 -0800690/// Parse a single Rust punctuation token.
691///
692/// See the [token module] documentation for details and examples.
693///
694/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800695///
696/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500697#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800698#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700699#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800700macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500701 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
702 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
703 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
704 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
705 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
706 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
707 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
708 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
709 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
710 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
711 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
712 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
713 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
714 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
715 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
716 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
717 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
718 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
719 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
720 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
721 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
722 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
723 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
724 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
725 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
726 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
727 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
728 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
729 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
730 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
731 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
732 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
733 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
734 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
735 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200736 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500737 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
738 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
739 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
740 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
741 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
742 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
743 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
744 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
745 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800746}
747
David Tolnayf005f962018-01-06 21:19:41 -0800748/// Parse a single Rust keyword token.
749///
750/// See the [token module] documentation for details and examples.
751///
752/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800753///
754/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500755#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800756#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700757#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800758macro_rules! keyword {
David Tolnaybb82ef02018-08-24 20:15:45 -0400759 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
760 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
761 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
762 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
763 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
764 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
765 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
766 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
767 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
768 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
769 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
770 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
771 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
772 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
773 ($i:expr, existential) => { call!($i, <$crate::token::Existential as $crate::synom::Synom>::parse) };
774 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
775 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
776 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
777 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
778 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
779 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
780 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
781 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
782 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
783 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
784 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
785 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
786 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
787 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
788 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
789 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
790 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
791 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
792 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
793 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
794 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
795 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
796 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
797 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
798 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
799 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
800 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
801 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800802}
803
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700804macro_rules! ident_from_token {
805 ($token:ident) => {
806 impl From<Token![$token]> for Ident {
807 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400808 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700809 }
810 }
811 };
812}
813
814ident_from_token!(self);
815ident_from_token!(Self);
816ident_from_token!(super);
817ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700818ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700819
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700820#[cfg(feature = "parsing")]
821mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500822 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700823
David Tolnaydfc886b2018-01-06 08:03:09 -0800824 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400825 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400826 use parse::ParseStream;
David Tolnay203557a2017-12-27 23:59:33 -0500827 use parse_error;
David Tolnay776f8e02018-08-24 22:32:10 -0400828 use span::FromSpans;
David Tolnay203557a2017-12-27 23:59:33 -0500829 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700830
David Tolnay776f8e02018-08-24 22:32:10 -0400831 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
832 input.step_cursor(|cursor| {
833 if let Some((ident, rest)) = cursor.ident() {
834 if ident == token {
835 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700836 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700837 }
David Tolnay776f8e02018-08-24 22:32:10 -0400838 Err(cursor.error(format!("expected `{}`", token)))
839 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700840 }
841
David Tolnay776f8e02018-08-24 22:32:10 -0400842 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
843 input.step_cursor(|cursor| {
844 let mut cursor = *cursor;
845 let mut spans = [cursor.span(); 3];
846 assert!(token.len() <= spans.len());
847
848 for (i, ch) in token.chars().enumerate() {
849 match cursor.punct() {
850 Some((punct, rest)) => {
851 spans[i] = punct.span();
852 if punct.as_char() != ch {
853 break;
854 } else if i == token.len() - 1 {
855 return Ok((S::from_spans(&spans), rest));
856 } else if punct.spacing() != Spacing::Joint {
857 break;
858 }
859 cursor = rest;
860 }
861 None => break,
862 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400863 }
David Tolnay776f8e02018-08-24 22:32:10 -0400864
865 Err(Error::new(spans[0], format!("expected `{}`", token)))
866 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700867 }
868
David Tolnay51382052017-12-27 13:46:21 -0500869 pub fn delim<'a, F, R, T>(
870 delim: &str,
871 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700872 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500873 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500874 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500875 where
876 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700877 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400878 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700879 let delim = match delim {
880 "(" => Delimiter::Parenthesis,
881 "{" => Delimiter::Brace,
882 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400883 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700884 _ => panic!("unknown delimiter: {}", delim),
885 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700886
David Tolnay65729482017-12-31 16:14:50 -0500887 if let Some((inside, span, rest)) = tokens.group(delim) {
888 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500889 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400890 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700891 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400892 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700893 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400894 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700895 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700896 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400897 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700898 }
899}
900
901#[cfg(feature = "printing")]
902mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700903 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700904 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700905
Alex Crichtona74a1c82018-05-16 10:20:44 -0700906 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700907 assert_eq!(s.len(), spans.len());
908
909 let mut chars = s.chars();
910 let mut spans = spans.iter();
911 let ch = chars.next_back().unwrap();
912 let span = spans.next_back().unwrap();
913 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700914 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700915 op.set_span(*span);
916 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700917 }
918
Alex Crichtona74a1c82018-05-16 10:20:44 -0700919 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700920 op.set_span(*span);
921 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700922 }
923
Alex Crichtona74a1c82018-05-16 10:20:44 -0700924 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
925 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700926 }
927
Alex Crichtona74a1c82018-05-16 10:20:44 -0700928 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500929 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700930 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700931 {
David Tolnay00ab6982017-12-31 18:15:06 -0500932 let delim = match s {
933 "(" => Delimiter::Parenthesis,
934 "[" => Delimiter::Bracket,
935 "{" => Delimiter::Brace,
936 " " => Delimiter::None,
937 _ => panic!("unknown delimiter: {}", s),
938 };
hcplaa511792018-05-29 07:13:01 +0300939 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500940 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700941 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700942 g.set_span(*span);
943 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700944 }
945}