blob: 27a49d96e3c58879f6e7c97ac6a429afdda679c6 [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!(
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 Tolnay776f8e02018-08-24 22:32:10 -0400100use std;
101#[cfg(feature = "extra-traits")]
102use std::cmp;
103#[cfg(feature = "extra-traits")]
104use std::fmt::{self, Debug};
105#[cfg(feature = "extra-traits")]
106use std::hash::{Hash, Hasher};
107
David Tolnay2d84a082018-08-25 16:31:38 -0400108#[cfg(feature = "parsing")]
109use proc_macro2::Delimiter;
David Tolnay8c39ac52018-08-25 08:46:21 -0400110#[cfg(any(feature = "printing", feature = "parsing"))]
111use proc_macro2::Spacing;
David Tolnay65fb5662018-05-20 20:02:28 -0700112use proc_macro2::{Ident, Span};
Sergio Benitezd14d5362018-04-28 15:38:25 -0700113#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400114use proc_macro2::{Punct, TokenStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400115#[cfg(feature = "printing")]
116use quote::{ToTokens, TokenStreamExt};
117
118#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400119use error::Result;
120#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400121use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400122#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400123use parse::{Lookahead1, Parse, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400124use span::IntoSpans;
125
126/// Marker trait for types that represent single tokens.
127///
128/// This trait is sealed and cannot be implemented for types outside of Syn.
129#[cfg(feature = "parsing")]
130pub trait Token: private::Sealed {
131 // Not public API.
132 #[doc(hidden)]
133 fn peek(lookahead: &Lookahead1) -> bool;
134
135 // Not public API.
136 #[doc(hidden)]
137 fn display() -> String;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700138}
139
140#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400141mod private {
142 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700143}
144
David Tolnay776f8e02018-08-24 22:32:10 -0400145macro_rules! impl_token {
146 ($token:tt $name:ident) => {
147 #[cfg(feature = "parsing")]
148 impl Token for $name {
149 fn peek(lookahead: &Lookahead1) -> bool {
150 lookahead::is_token(lookahead, $token)
151 }
152
153 fn display() -> String {
154 concat!("`", $token, "`").to_owned()
155 }
156 }
157
158 #[cfg(feature = "parsing")]
159 impl private::Sealed for $name {}
160 };
161}
162
163macro_rules! define_keywords {
164 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
165 $(
166 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
167 #[$doc]
168 ///
169 /// Don't try to remember the name of this type -- use the [`Token!`]
170 /// macro instead.
171 ///
172 /// [`Token!`]: index.html
173 pub struct $name {
174 pub span: Span,
175 }
176
177 #[doc(hidden)]
178 #[allow(non_snake_case)]
179 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
180 $name {
181 span: span.into_spans()[0],
182 }
183 }
184
185 impl_token!($token $name);
186
187 impl std::default::Default for $name {
188 fn default() -> Self {
189 $name(Span::call_site())
190 }
191 }
192
193 #[cfg(feature = "extra-traits")]
194 impl Debug for $name {
195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 f.write_str(stringify!($name))
197 }
198 }
199
200 #[cfg(feature = "extra-traits")]
201 impl cmp::Eq for $name {}
202
203 #[cfg(feature = "extra-traits")]
204 impl PartialEq for $name {
205 fn eq(&self, _other: &$name) -> bool {
206 true
207 }
208 }
209
210 #[cfg(feature = "extra-traits")]
211 impl Hash for $name {
212 fn hash<H: Hasher>(&self, _state: &mut H) {}
213 }
214
215 #[cfg(feature = "printing")]
216 impl ToTokens for $name {
217 fn to_tokens(&self, tokens: &mut TokenStream) {
218 printing::keyword($token, &self.span, tokens);
219 }
220 }
221
222 #[cfg(feature = "parsing")]
223 impl Parse for $name {
224 fn parse(input: ParseStream) -> Result<Self> {
225 parsing::keyword(input, $token).map($name)
226 }
227 }
228 )*
229 };
230}
231
232macro_rules! define_punctuation_structs {
233 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
234 $(
235 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
236 #[$doc]
237 ///
238 /// Don't try to remember the name of this type -- use the [`Token!`]
239 /// macro instead.
240 ///
241 /// [`Token!`]: index.html
242 pub struct $name {
243 pub spans: [Span; $len],
244 }
245
246 #[doc(hidden)]
247 #[allow(non_snake_case)]
248 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
249 $name {
250 spans: spans.into_spans(),
251 }
252 }
253
254 impl_token!($token $name);
255
256 impl std::default::Default for $name {
257 fn default() -> Self {
258 $name([Span::call_site(); $len])
259 }
260 }
261
262 #[cfg(feature = "extra-traits")]
263 impl Debug for $name {
264 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
265 f.write_str(stringify!($name))
266 }
267 }
268
269 #[cfg(feature = "extra-traits")]
270 impl cmp::Eq for $name {}
271
272 #[cfg(feature = "extra-traits")]
273 impl PartialEq for $name {
274 fn eq(&self, _other: &$name) -> bool {
275 true
276 }
277 }
278
279 #[cfg(feature = "extra-traits")]
280 impl Hash for $name {
281 fn hash<H: Hasher>(&self, _state: &mut H) {}
282 }
283 )*
284 };
285}
286
287macro_rules! define_punctuation {
288 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
289 $(
290 define_punctuation_structs! {
291 $token pub struct $name/$len #[$doc]
292 }
293
294 #[cfg(feature = "printing")]
295 impl ToTokens for $name {
296 fn to_tokens(&self, tokens: &mut TokenStream) {
297 printing::punct($token, &self.spans, tokens);
298 }
299 }
300
301 #[cfg(feature = "parsing")]
302 impl Parse for $name {
303 fn parse(input: ParseStream) -> Result<Self> {
304 parsing::punct(input, $token).map($name::<[Span; $len]>)
305 }
306 }
307 )*
308 };
309}
310
311macro_rules! define_delimiters {
312 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
313 $(
314 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
315 #[$doc]
316 pub struct $name {
317 pub span: Span,
318 }
319
320 #[doc(hidden)]
321 #[allow(non_snake_case)]
322 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
323 $name {
324 span: span.into_spans()[0],
325 }
326 }
327
328 impl std::default::Default for $name {
329 fn default() -> Self {
330 $name(Span::call_site())
331 }
332 }
333
334 #[cfg(feature = "extra-traits")]
335 impl Debug for $name {
336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
337 f.write_str(stringify!($name))
338 }
339 }
340
341 #[cfg(feature = "extra-traits")]
342 impl cmp::Eq for $name {}
343
344 #[cfg(feature = "extra-traits")]
345 impl PartialEq for $name {
346 fn eq(&self, _other: &$name) -> bool {
347 true
348 }
349 }
350
351 #[cfg(feature = "extra-traits")]
352 impl Hash for $name {
353 fn hash<H: Hasher>(&self, _state: &mut H) {}
354 }
355
356 impl $name {
357 #[cfg(feature = "printing")]
358 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
359 where
360 F: FnOnce(&mut TokenStream),
361 {
362 printing::delim($token, &self.span, tokens, f);
363 }
364
365 #[cfg(feature = "parsing")]
366 pub fn parse<F, R>(
367 tokens: $crate::buffer::Cursor,
368 f: F,
369 ) -> $crate::synom::PResult<($name, R)>
370 where
371 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
372 {
373 parsing::delim($token, tokens, $name, f)
374 }
375 }
David Tolnay2d84a082018-08-25 16:31:38 -0400376
377 #[cfg(feature = "parsing")]
378 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400379 )*
380 };
381}
382
383define_punctuation_structs! {
384 "'" pub struct Apostrophe/1 /// `'`
385 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700386}
387
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700388// Implement Clone anyway because it is required for cloning Lifetime.
389#[cfg(not(feature = "clone-impls"))]
390impl Clone for Apostrophe {
391 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400392 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700393 }
394}
395
Alex Crichton131308c2018-05-18 14:00:24 -0700396#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400397impl ToTokens for Apostrophe {
398 fn to_tokens(&self, tokens: &mut TokenStream) {
399 let mut token = Punct::new('\'', Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400400 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700401 tokens.append(token);
402 }
403}
404
405#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400406impl Parse for Apostrophe {
407 fn parse(input: ParseStream) -> Result<Self> {
408 input.step_cursor(|cursor| {
409 if let Some((punct, rest)) = cursor.punct() {
410 if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint {
411 return Ok((Apostrophe(punct.span()), rest));
Alex Crichton131308c2018-05-18 14:00:24 -0700412 }
413 }
David Tolnay776f8e02018-08-24 22:32:10 -0400414 Err(cursor.error("expected `'`"))
415 })
Alex Crichton131308c2018-05-18 14:00:24 -0700416 }
417}
418
David Tolnay776f8e02018-08-24 22:32:10 -0400419#[cfg(feature = "printing")]
420impl ToTokens for Underscore {
421 fn to_tokens(&self, tokens: &mut TokenStream) {
422 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700423 }
David Tolnay776f8e02018-08-24 22:32:10 -0400424}
425
426#[cfg(feature = "parsing")]
427impl Parse for Underscore {
428 fn parse(input: ParseStream) -> Result<Self> {
429 input.step_cursor(|cursor| {
430 if let Some((ident, rest)) = cursor.ident() {
431 if ident == "_" {
432 return Ok((Underscore(ident.span()), rest));
433 }
434 }
435 if let Some((punct, rest)) = cursor.punct() {
436 if punct.as_char() == '_' {
437 return Ok((Underscore(punct.span()), rest));
438 }
439 }
440 Err(cursor.error("expected `_`"))
441 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700442 }
David Tolnay776f8e02018-08-24 22:32:10 -0400443}
444
David Tolnay2d84a082018-08-25 16:31:38 -0400445#[cfg(feature = "parsing")]
446impl Token for Paren {
447 fn peek(lookahead: &Lookahead1) -> bool {
448 lookahead::is_delimiter(lookahead, Delimiter::Parenthesis)
449 }
450
451 fn display() -> String {
452 "parentheses".to_owned()
453 }
454}
455
456#[cfg(feature = "parsing")]
457impl Token for Brace {
458 fn peek(lookahead: &Lookahead1) -> bool {
459 lookahead::is_delimiter(lookahead, Delimiter::Brace)
460 }
461
462 fn display() -> String {
463 "curly braces".to_owned()
464 }
465}
466
467#[cfg(feature = "parsing")]
468impl Token for Bracket {
469 fn peek(lookahead: &Lookahead1) -> bool {
470 lookahead::is_delimiter(lookahead, Delimiter::Bracket)
471 }
472
473 fn display() -> String {
474 "square brackets".to_owned()
475 }
476}
477
David Tolnay776f8e02018-08-24 22:32:10 -0400478define_keywords! {
479 "as" pub struct As /// `as`
480 "async" pub struct Async /// `async`
481 "auto" pub struct Auto /// `auto`
482 "box" pub struct Box /// `box`
483 "break" pub struct Break /// `break`
484 "Self" pub struct CapSelf /// `Self`
485 "const" pub struct Const /// `const`
486 "continue" pub struct Continue /// `continue`
487 "crate" pub struct Crate /// `crate`
488 "default" pub struct Default /// `default`
489 "dyn" pub struct Dyn /// `dyn`
490 "else" pub struct Else /// `else`
491 "enum" pub struct Enum /// `enum`
492 "existential" pub struct Existential /// `existential`
493 "extern" pub struct Extern /// `extern`
494 "fn" pub struct Fn /// `fn`
495 "for" pub struct For /// `for`
496 "if" pub struct If /// `if`
497 "impl" pub struct Impl /// `impl`
498 "in" pub struct In /// `in`
499 "let" pub struct Let /// `let`
500 "loop" pub struct Loop /// `loop`
501 "macro" pub struct Macro /// `macro`
502 "match" pub struct Match /// `match`
503 "mod" pub struct Mod /// `mod`
504 "move" pub struct Move /// `move`
505 "mut" pub struct Mut /// `mut`
506 "pub" pub struct Pub /// `pub`
507 "ref" pub struct Ref /// `ref`
508 "return" pub struct Return /// `return`
509 "self" pub struct Self_ /// `self`
510 "static" pub struct Static /// `static`
511 "struct" pub struct Struct /// `struct`
512 "super" pub struct Super /// `super`
513 "trait" pub struct Trait /// `trait`
514 "try" pub struct Try /// `try`
515 "type" pub struct Type /// `type`
516 "union" pub struct Union /// `union`
517 "unsafe" pub struct Unsafe /// `unsafe`
518 "use" pub struct Use /// `use`
519 "where" pub struct Where /// `where`
520 "while" pub struct While /// `while`
521 "yield" pub struct Yield /// `yield`
522}
523
524define_punctuation! {
525 "+" pub struct Add/1 /// `+`
526 "+=" pub struct AddEq/2 /// `+=`
527 "&" pub struct And/1 /// `&`
528 "&&" pub struct AndAnd/2 /// `&&`
529 "&=" pub struct AndEq/2 /// `&=`
530 "@" pub struct At/1 /// `@`
531 "!" pub struct Bang/1 /// `!`
532 "^" pub struct Caret/1 /// `^`
533 "^=" pub struct CaretEq/2 /// `^=`
534 ":" pub struct Colon/1 /// `:`
535 "::" pub struct Colon2/2 /// `::`
536 "," pub struct Comma/1 /// `,`
537 "/" pub struct Div/1 /// `/`
538 "/=" pub struct DivEq/2 /// `/=`
539 "$" pub struct Dollar/1 /// `$`
540 "." pub struct Dot/1 /// `.`
541 ".." pub struct Dot2/2 /// `..`
542 "..." pub struct Dot3/3 /// `...`
543 "..=" pub struct DotDotEq/3 /// `..=`
544 "=" pub struct Eq/1 /// `=`
545 "==" pub struct EqEq/2 /// `==`
546 ">=" pub struct Ge/2 /// `>=`
547 ">" pub struct Gt/1 /// `>`
548 "<=" pub struct Le/2 /// `<=`
549 "<" pub struct Lt/1 /// `<`
550 "*=" pub struct MulEq/2 /// `*=`
551 "!=" pub struct Ne/2 /// `!=`
552 "|" pub struct Or/1 /// `|`
553 "|=" pub struct OrEq/2 /// `|=`
554 "||" pub struct OrOr/2 /// `||`
555 "#" pub struct Pound/1 /// `#`
556 "?" pub struct Question/1 /// `?`
557 "->" pub struct RArrow/2 /// `->`
558 "<-" pub struct LArrow/2 /// `<-`
559 "%" pub struct Rem/1 /// `%`
560 "%=" pub struct RemEq/2 /// `%=`
561 "=>" pub struct FatArrow/2 /// `=>`
562 ";" pub struct Semi/1 /// `;`
563 "<<" pub struct Shl/2 /// `<<`
564 "<<=" pub struct ShlEq/3 /// `<<=`
565 ">>" pub struct Shr/2 /// `>>`
566 ">>=" pub struct ShrEq/3 /// `>>=`
567 "*" pub struct Star/1 /// `*`
568 "-" pub struct Sub/1 /// `-`
569 "-=" pub struct SubEq/2 /// `-=`
570}
571
572define_delimiters! {
573 "{" pub struct Brace /// `{...}`
574 "[" pub struct Bracket /// `[...]`
575 "(" pub struct Paren /// `(...)`
576 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700577}
578
David Tolnayf005f962018-01-06 21:19:41 -0800579/// A type-macro that expands to the name of the Rust type representation of a
580/// given token.
581///
582/// See the [token module] documentation for details and examples.
583///
584/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800585// Unfortunate duplication due to a rustdoc bug.
586// https://github.com/rust-lang/rust/issues/45939
587#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700588#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800589macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400590 (as) => { $crate::token::As };
591 (async) => { $crate::token::Async };
592 (auto) => { $crate::token::Auto };
593 (box) => { $crate::token::Box };
594 (break) => { $crate::token::Break };
595 (Self) => { $crate::token::CapSelf };
596 (const) => { $crate::token::Const };
597 (continue) => { $crate::token::Continue };
598 (crate) => { $crate::token::Crate };
599 (default) => { $crate::token::Default };
600 (dyn) => { $crate::token::Dyn };
601 (else) => { $crate::token::Else };
602 (enum) => { $crate::token::Enum };
603 (existential) => { $crate::token::Existential };
604 (extern) => { $crate::token::Extern };
605 (fn) => { $crate::token::Fn };
606 (for) => { $crate::token::For };
607 (if) => { $crate::token::If };
608 (impl) => { $crate::token::Impl };
609 (in) => { $crate::token::In };
610 (let) => { $crate::token::Let };
611 (loop) => { $crate::token::Loop };
612 (macro) => { $crate::token::Macro };
613 (match) => { $crate::token::Match };
614 (mod) => { $crate::token::Mod };
615 (move) => { $crate::token::Move };
616 (mut) => { $crate::token::Mut };
617 (pub) => { $crate::token::Pub };
618 (ref) => { $crate::token::Ref };
619 (return) => { $crate::token::Return };
620 (self) => { $crate::token::Self_ };
621 (static) => { $crate::token::Static };
622 (struct) => { $crate::token::Struct };
623 (super) => { $crate::token::Super };
624 (trait) => { $crate::token::Trait };
625 (try) => { $crate::token::Try };
626 (type) => { $crate::token::Type };
627 (union) => { $crate::token::Union };
628 (unsafe) => { $crate::token::Unsafe };
629 (use) => { $crate::token::Use };
630 (where) => { $crate::token::Where };
631 (while) => { $crate::token::While };
632 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400633 (+) => { $crate::token::Add };
634 (+=) => { $crate::token::AddEq };
635 (&) => { $crate::token::And };
636 (&&) => { $crate::token::AndAnd };
637 (&=) => { $crate::token::AndEq };
638 (@) => { $crate::token::At };
639 (!) => { $crate::token::Bang };
640 (^) => { $crate::token::Caret };
641 (^=) => { $crate::token::CaretEq };
642 (:) => { $crate::token::Colon };
643 (::) => { $crate::token::Colon2 };
644 (,) => { $crate::token::Comma };
645 (/) => { $crate::token::Div };
646 (/=) => { $crate::token::DivEq };
647 (.) => { $crate::token::Dot };
648 (..) => { $crate::token::Dot2 };
649 (...) => { $crate::token::Dot3 };
650 (..=) => { $crate::token::DotDotEq };
651 (=) => { $crate::token::Eq };
652 (==) => { $crate::token::EqEq };
653 (>=) => { $crate::token::Ge };
654 (>) => { $crate::token::Gt };
655 (<=) => { $crate::token::Le };
656 (<) => { $crate::token::Lt };
657 (*=) => { $crate::token::MulEq };
658 (!=) => { $crate::token::Ne };
659 (|) => { $crate::token::Or };
660 (|=) => { $crate::token::OrEq };
661 (||) => { $crate::token::OrOr };
662 (#) => { $crate::token::Pound };
663 (?) => { $crate::token::Question };
664 (->) => { $crate::token::RArrow };
665 (<-) => { $crate::token::LArrow };
666 (%) => { $crate::token::Rem };
667 (%=) => { $crate::token::RemEq };
668 (=>) => { $crate::token::FatArrow };
669 (;) => { $crate::token::Semi };
670 (<<) => { $crate::token::Shl };
671 (<<=) => { $crate::token::ShlEq };
672 (>>) => { $crate::token::Shr };
673 (>>=) => { $crate::token::ShrEq };
674 (*) => { $crate::token::Star };
675 (-) => { $crate::token::Sub };
676 (-=) => { $crate::token::SubEq };
677 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800678}
679
David Tolnayf005f962018-01-06 21:19:41 -0800680/// Parse a single Rust punctuation token.
681///
682/// See the [token module] documentation for details and examples.
683///
684/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800685///
686/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500687#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800688#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700689#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800690macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500691 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
692 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
693 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
694 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
695 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
696 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
697 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
698 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
699 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
700 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
701 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
702 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
703 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
704 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
705 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
706 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
707 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
708 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
709 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
710 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
711 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
712 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
713 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
714 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
715 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
716 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
717 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
718 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
719 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
720 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
721 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
722 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
723 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
724 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
725 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200726 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500727 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
728 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
729 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
730 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
731 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
732 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
733 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
734 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
735 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800736}
737
David Tolnayf005f962018-01-06 21:19:41 -0800738/// Parse a single Rust keyword token.
739///
740/// See the [token module] documentation for details and examples.
741///
742/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800743///
744/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500745#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800746#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700747#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800748macro_rules! keyword {
David Tolnaybb82ef02018-08-24 20:15:45 -0400749 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
750 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
751 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
752 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
753 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
754 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
755 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
756 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
757 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
758 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
759 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
760 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
761 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
762 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
763 ($i:expr, existential) => { call!($i, <$crate::token::Existential as $crate::synom::Synom>::parse) };
764 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
765 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
766 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
767 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
768 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
769 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
770 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
771 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
772 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
773 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
774 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
775 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
776 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
777 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
778 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
779 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
780 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
781 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
782 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
783 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
784 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
785 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
786 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
787 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
788 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
789 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
790 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
791 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800792}
793
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700794macro_rules! ident_from_token {
795 ($token:ident) => {
796 impl From<Token![$token]> for Ident {
797 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400798 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700799 }
800 }
801 };
802}
803
804ident_from_token!(self);
805ident_from_token!(Self);
806ident_from_token!(super);
807ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700808ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700809
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700810#[cfg(feature = "parsing")]
811mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500812 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700813
David Tolnaydfc886b2018-01-06 08:03:09 -0800814 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400815 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400816 use parse::ParseStream;
David Tolnay203557a2017-12-27 23:59:33 -0500817 use parse_error;
David Tolnay776f8e02018-08-24 22:32:10 -0400818 use span::FromSpans;
David Tolnay203557a2017-12-27 23:59:33 -0500819 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700820
David Tolnay776f8e02018-08-24 22:32:10 -0400821 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
822 input.step_cursor(|cursor| {
823 if let Some((ident, rest)) = cursor.ident() {
824 if ident == token {
825 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700826 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700827 }
David Tolnay776f8e02018-08-24 22:32:10 -0400828 Err(cursor.error(format!("expected `{}`", token)))
829 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700830 }
831
David Tolnay776f8e02018-08-24 22:32:10 -0400832 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
833 input.step_cursor(|cursor| {
834 let mut cursor = *cursor;
835 let mut spans = [cursor.span(); 3];
836 assert!(token.len() <= spans.len());
837
838 for (i, ch) in token.chars().enumerate() {
839 match cursor.punct() {
840 Some((punct, rest)) => {
841 spans[i] = punct.span();
842 if punct.as_char() != ch {
843 break;
844 } else if i == token.len() - 1 {
845 return Ok((S::from_spans(&spans), rest));
846 } else if punct.spacing() != Spacing::Joint {
847 break;
848 }
849 cursor = rest;
850 }
851 None => break,
852 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400853 }
David Tolnay776f8e02018-08-24 22:32:10 -0400854
855 Err(Error::new(spans[0], format!("expected `{}`", token)))
856 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700857 }
858
David Tolnay51382052017-12-27 13:46:21 -0500859 pub fn delim<'a, F, R, T>(
860 delim: &str,
861 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700862 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500863 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500864 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500865 where
866 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700867 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400868 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700869 let delim = match delim {
870 "(" => Delimiter::Parenthesis,
871 "{" => Delimiter::Brace,
872 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400873 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700874 _ => panic!("unknown delimiter: {}", delim),
875 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700876
David Tolnay65729482017-12-31 16:14:50 -0500877 if let Some((inside, span, rest)) = tokens.group(delim) {
878 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500879 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400880 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700881 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400882 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700883 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400884 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700885 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700886 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400887 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700888 }
889}
890
891#[cfg(feature = "printing")]
892mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700893 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700894 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700895
Alex Crichtona74a1c82018-05-16 10:20:44 -0700896 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700897 assert_eq!(s.len(), spans.len());
898
899 let mut chars = s.chars();
900 let mut spans = spans.iter();
901 let ch = chars.next_back().unwrap();
902 let span = spans.next_back().unwrap();
903 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700904 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700905 op.set_span(*span);
906 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700907 }
908
Alex Crichtona74a1c82018-05-16 10:20:44 -0700909 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700910 op.set_span(*span);
911 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700912 }
913
Alex Crichtona74a1c82018-05-16 10:20:44 -0700914 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
915 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700916 }
917
Alex Crichtona74a1c82018-05-16 10:20:44 -0700918 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500919 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700920 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700921 {
David Tolnay00ab6982017-12-31 18:15:06 -0500922 let delim = match s {
923 "(" => Delimiter::Parenthesis,
924 "[" => Delimiter::Bracket,
925 "{" => Delimiter::Brace,
926 " " => Delimiter::None,
927 _ => panic!("unknown delimiter: {}", s),
928 };
hcplaa511792018-05-29 07:13:01 +0300929 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500930 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700931 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700932 g.set_span(*span);
933 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700934 }
935}