blob: 90f20f9daa01baf3fc07061260b3cc7d4f900e4a [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 Tolnay65fb5662018-05-20 20:02:28 -0700108use proc_macro2::{Ident, Span};
Sergio Benitezd14d5362018-04-28 15:38:25 -0700109#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400110use proc_macro2::{Punct, TokenStream};
111#[cfg(any(feature = "printing", feature = "parsing"))]
112use proc_macro2::Spacing;
113#[cfg(feature = "printing")]
114use quote::{ToTokens, TokenStreamExt};
115
116#[cfg(feature = "parsing")]
117use next::lookahead;
118#[cfg(feature = "parsing")]
119use next::parse::{Lookahead1, Parse, ParseStream, Result};
120use span::IntoSpans;
121
122/// Marker trait for types that represent single tokens.
123///
124/// This trait is sealed and cannot be implemented for types outside of Syn.
125#[cfg(feature = "parsing")]
126pub trait Token: private::Sealed {
127 // Not public API.
128 #[doc(hidden)]
129 fn peek(lookahead: &Lookahead1) -> bool;
130
131 // Not public API.
132 #[doc(hidden)]
133 fn display() -> String;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700134}
135
136#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400137mod private {
138 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700139}
140
David Tolnay776f8e02018-08-24 22:32:10 -0400141macro_rules! impl_token {
142 ($token:tt $name:ident) => {
143 #[cfg(feature = "parsing")]
144 impl Token for $name {
145 fn peek(lookahead: &Lookahead1) -> bool {
146 lookahead::is_token(lookahead, $token)
147 }
148
149 fn display() -> String {
150 concat!("`", $token, "`").to_owned()
151 }
152 }
153
154 #[cfg(feature = "parsing")]
155 impl private::Sealed for $name {}
156 };
157}
158
159macro_rules! define_keywords {
160 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
161 $(
162 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
163 #[$doc]
164 ///
165 /// Don't try to remember the name of this type -- use the [`Token!`]
166 /// macro instead.
167 ///
168 /// [`Token!`]: index.html
169 pub struct $name {
170 pub span: Span,
171 }
172
173 #[doc(hidden)]
174 #[allow(non_snake_case)]
175 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
176 $name {
177 span: span.into_spans()[0],
178 }
179 }
180
181 impl_token!($token $name);
182
183 impl std::default::Default for $name {
184 fn default() -> Self {
185 $name(Span::call_site())
186 }
187 }
188
189 #[cfg(feature = "extra-traits")]
190 impl Debug for $name {
191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
192 f.write_str(stringify!($name))
193 }
194 }
195
196 #[cfg(feature = "extra-traits")]
197 impl cmp::Eq for $name {}
198
199 #[cfg(feature = "extra-traits")]
200 impl PartialEq for $name {
201 fn eq(&self, _other: &$name) -> bool {
202 true
203 }
204 }
205
206 #[cfg(feature = "extra-traits")]
207 impl Hash for $name {
208 fn hash<H: Hasher>(&self, _state: &mut H) {}
209 }
210
211 #[cfg(feature = "printing")]
212 impl ToTokens for $name {
213 fn to_tokens(&self, tokens: &mut TokenStream) {
214 printing::keyword($token, &self.span, tokens);
215 }
216 }
217
218 #[cfg(feature = "parsing")]
219 impl Parse for $name {
220 fn parse(input: ParseStream) -> Result<Self> {
221 parsing::keyword(input, $token).map($name)
222 }
223 }
224 )*
225 };
226}
227
228macro_rules! define_punctuation_structs {
229 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
230 $(
231 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
232 #[$doc]
233 ///
234 /// Don't try to remember the name of this type -- use the [`Token!`]
235 /// macro instead.
236 ///
237 /// [`Token!`]: index.html
238 pub struct $name {
239 pub spans: [Span; $len],
240 }
241
242 #[doc(hidden)]
243 #[allow(non_snake_case)]
244 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
245 $name {
246 spans: spans.into_spans(),
247 }
248 }
249
250 impl_token!($token $name);
251
252 impl std::default::Default for $name {
253 fn default() -> Self {
254 $name([Span::call_site(); $len])
255 }
256 }
257
258 #[cfg(feature = "extra-traits")]
259 impl Debug for $name {
260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
261 f.write_str(stringify!($name))
262 }
263 }
264
265 #[cfg(feature = "extra-traits")]
266 impl cmp::Eq for $name {}
267
268 #[cfg(feature = "extra-traits")]
269 impl PartialEq for $name {
270 fn eq(&self, _other: &$name) -> bool {
271 true
272 }
273 }
274
275 #[cfg(feature = "extra-traits")]
276 impl Hash for $name {
277 fn hash<H: Hasher>(&self, _state: &mut H) {}
278 }
279 )*
280 };
281}
282
283macro_rules! define_punctuation {
284 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
285 $(
286 define_punctuation_structs! {
287 $token pub struct $name/$len #[$doc]
288 }
289
290 #[cfg(feature = "printing")]
291 impl ToTokens for $name {
292 fn to_tokens(&self, tokens: &mut TokenStream) {
293 printing::punct($token, &self.spans, tokens);
294 }
295 }
296
297 #[cfg(feature = "parsing")]
298 impl Parse for $name {
299 fn parse(input: ParseStream) -> Result<Self> {
300 parsing::punct(input, $token).map($name::<[Span; $len]>)
301 }
302 }
303 )*
304 };
305}
306
307macro_rules! define_delimiters {
308 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
309 $(
310 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
311 #[$doc]
312 pub struct $name {
313 pub span: Span,
314 }
315
316 #[doc(hidden)]
317 #[allow(non_snake_case)]
318 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
319 $name {
320 span: span.into_spans()[0],
321 }
322 }
323
324 impl std::default::Default for $name {
325 fn default() -> Self {
326 $name(Span::call_site())
327 }
328 }
329
330 #[cfg(feature = "extra-traits")]
331 impl Debug for $name {
332 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333 f.write_str(stringify!($name))
334 }
335 }
336
337 #[cfg(feature = "extra-traits")]
338 impl cmp::Eq for $name {}
339
340 #[cfg(feature = "extra-traits")]
341 impl PartialEq for $name {
342 fn eq(&self, _other: &$name) -> bool {
343 true
344 }
345 }
346
347 #[cfg(feature = "extra-traits")]
348 impl Hash for $name {
349 fn hash<H: Hasher>(&self, _state: &mut H) {}
350 }
351
352 impl $name {
353 #[cfg(feature = "printing")]
354 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
355 where
356 F: FnOnce(&mut TokenStream),
357 {
358 printing::delim($token, &self.span, tokens, f);
359 }
360
361 #[cfg(feature = "parsing")]
362 pub fn parse<F, R>(
363 tokens: $crate::buffer::Cursor,
364 f: F,
365 ) -> $crate::synom::PResult<($name, R)>
366 where
367 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
368 {
369 parsing::delim($token, tokens, $name, f)
370 }
371 }
372 )*
373 };
374}
375
376define_punctuation_structs! {
377 "'" pub struct Apostrophe/1 /// `'`
378 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700379}
380
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700381// Implement Clone anyway because it is required for cloning Lifetime.
382#[cfg(not(feature = "clone-impls"))]
383impl Clone for Apostrophe {
384 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400385 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700386 }
387}
388
Alex Crichton131308c2018-05-18 14:00:24 -0700389#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400390impl ToTokens for Apostrophe {
391 fn to_tokens(&self, tokens: &mut TokenStream) {
392 let mut token = Punct::new('\'', Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400393 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700394 tokens.append(token);
395 }
396}
397
398#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400399impl Parse for Apostrophe {
400 fn parse(input: ParseStream) -> Result<Self> {
401 input.step_cursor(|cursor| {
402 if let Some((punct, rest)) = cursor.punct() {
403 if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint {
404 return Ok((Apostrophe(punct.span()), rest));
Alex Crichton131308c2018-05-18 14:00:24 -0700405 }
406 }
David Tolnay776f8e02018-08-24 22:32:10 -0400407 Err(cursor.error("expected `'`"))
408 })
Alex Crichton131308c2018-05-18 14:00:24 -0700409 }
410}
411
David Tolnay776f8e02018-08-24 22:32:10 -0400412#[cfg(feature = "printing")]
413impl ToTokens for Underscore {
414 fn to_tokens(&self, tokens: &mut TokenStream) {
415 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700416 }
David Tolnay776f8e02018-08-24 22:32:10 -0400417}
418
419#[cfg(feature = "parsing")]
420impl Parse for Underscore {
421 fn parse(input: ParseStream) -> Result<Self> {
422 input.step_cursor(|cursor| {
423 if let Some((ident, rest)) = cursor.ident() {
424 if ident == "_" {
425 return Ok((Underscore(ident.span()), rest));
426 }
427 }
428 if let Some((punct, rest)) = cursor.punct() {
429 if punct.as_char() == '_' {
430 return Ok((Underscore(punct.span()), rest));
431 }
432 }
433 Err(cursor.error("expected `_`"))
434 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700435 }
David Tolnay776f8e02018-08-24 22:32:10 -0400436}
437
438define_keywords! {
439 "as" pub struct As /// `as`
440 "async" pub struct Async /// `async`
441 "auto" pub struct Auto /// `auto`
442 "box" pub struct Box /// `box`
443 "break" pub struct Break /// `break`
444 "Self" pub struct CapSelf /// `Self`
445 "const" pub struct Const /// `const`
446 "continue" pub struct Continue /// `continue`
447 "crate" pub struct Crate /// `crate`
448 "default" pub struct Default /// `default`
449 "dyn" pub struct Dyn /// `dyn`
450 "else" pub struct Else /// `else`
451 "enum" pub struct Enum /// `enum`
452 "existential" pub struct Existential /// `existential`
453 "extern" pub struct Extern /// `extern`
454 "fn" pub struct Fn /// `fn`
455 "for" pub struct For /// `for`
456 "if" pub struct If /// `if`
457 "impl" pub struct Impl /// `impl`
458 "in" pub struct In /// `in`
459 "let" pub struct Let /// `let`
460 "loop" pub struct Loop /// `loop`
461 "macro" pub struct Macro /// `macro`
462 "match" pub struct Match /// `match`
463 "mod" pub struct Mod /// `mod`
464 "move" pub struct Move /// `move`
465 "mut" pub struct Mut /// `mut`
466 "pub" pub struct Pub /// `pub`
467 "ref" pub struct Ref /// `ref`
468 "return" pub struct Return /// `return`
469 "self" pub struct Self_ /// `self`
470 "static" pub struct Static /// `static`
471 "struct" pub struct Struct /// `struct`
472 "super" pub struct Super /// `super`
473 "trait" pub struct Trait /// `trait`
474 "try" pub struct Try /// `try`
475 "type" pub struct Type /// `type`
476 "union" pub struct Union /// `union`
477 "unsafe" pub struct Unsafe /// `unsafe`
478 "use" pub struct Use /// `use`
479 "where" pub struct Where /// `where`
480 "while" pub struct While /// `while`
481 "yield" pub struct Yield /// `yield`
482}
483
484define_punctuation! {
485 "+" pub struct Add/1 /// `+`
486 "+=" pub struct AddEq/2 /// `+=`
487 "&" pub struct And/1 /// `&`
488 "&&" pub struct AndAnd/2 /// `&&`
489 "&=" pub struct AndEq/2 /// `&=`
490 "@" pub struct At/1 /// `@`
491 "!" pub struct Bang/1 /// `!`
492 "^" pub struct Caret/1 /// `^`
493 "^=" pub struct CaretEq/2 /// `^=`
494 ":" pub struct Colon/1 /// `:`
495 "::" pub struct Colon2/2 /// `::`
496 "," pub struct Comma/1 /// `,`
497 "/" pub struct Div/1 /// `/`
498 "/=" pub struct DivEq/2 /// `/=`
499 "$" pub struct Dollar/1 /// `$`
500 "." pub struct Dot/1 /// `.`
501 ".." pub struct Dot2/2 /// `..`
502 "..." pub struct Dot3/3 /// `...`
503 "..=" pub struct DotDotEq/3 /// `..=`
504 "=" pub struct Eq/1 /// `=`
505 "==" pub struct EqEq/2 /// `==`
506 ">=" pub struct Ge/2 /// `>=`
507 ">" pub struct Gt/1 /// `>`
508 "<=" pub struct Le/2 /// `<=`
509 "<" pub struct Lt/1 /// `<`
510 "*=" pub struct MulEq/2 /// `*=`
511 "!=" pub struct Ne/2 /// `!=`
512 "|" pub struct Or/1 /// `|`
513 "|=" pub struct OrEq/2 /// `|=`
514 "||" pub struct OrOr/2 /// `||`
515 "#" pub struct Pound/1 /// `#`
516 "?" pub struct Question/1 /// `?`
517 "->" pub struct RArrow/2 /// `->`
518 "<-" pub struct LArrow/2 /// `<-`
519 "%" pub struct Rem/1 /// `%`
520 "%=" pub struct RemEq/2 /// `%=`
521 "=>" pub struct FatArrow/2 /// `=>`
522 ";" pub struct Semi/1 /// `;`
523 "<<" pub struct Shl/2 /// `<<`
524 "<<=" pub struct ShlEq/3 /// `<<=`
525 ">>" pub struct Shr/2 /// `>>`
526 ">>=" pub struct ShrEq/3 /// `>>=`
527 "*" pub struct Star/1 /// `*`
528 "-" pub struct Sub/1 /// `-`
529 "-=" pub struct SubEq/2 /// `-=`
530}
531
532define_delimiters! {
533 "{" pub struct Brace /// `{...}`
534 "[" pub struct Bracket /// `[...]`
535 "(" pub struct Paren /// `(...)`
536 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700537}
538
David Tolnayf005f962018-01-06 21:19:41 -0800539/// A type-macro that expands to the name of the Rust type representation of a
540/// given token.
541///
542/// See the [token module] documentation for details and examples.
543///
544/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800545// Unfortunate duplication due to a rustdoc bug.
546// https://github.com/rust-lang/rust/issues/45939
547#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700548#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800549macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400550 (as) => { $crate::token::As };
551 (async) => { $crate::token::Async };
552 (auto) => { $crate::token::Auto };
553 (box) => { $crate::token::Box };
554 (break) => { $crate::token::Break };
555 (Self) => { $crate::token::CapSelf };
556 (const) => { $crate::token::Const };
557 (continue) => { $crate::token::Continue };
558 (crate) => { $crate::token::Crate };
559 (default) => { $crate::token::Default };
560 (dyn) => { $crate::token::Dyn };
561 (else) => { $crate::token::Else };
562 (enum) => { $crate::token::Enum };
563 (existential) => { $crate::token::Existential };
564 (extern) => { $crate::token::Extern };
565 (fn) => { $crate::token::Fn };
566 (for) => { $crate::token::For };
567 (if) => { $crate::token::If };
568 (impl) => { $crate::token::Impl };
569 (in) => { $crate::token::In };
570 (let) => { $crate::token::Let };
571 (loop) => { $crate::token::Loop };
572 (macro) => { $crate::token::Macro };
573 (match) => { $crate::token::Match };
574 (mod) => { $crate::token::Mod };
575 (move) => { $crate::token::Move };
576 (mut) => { $crate::token::Mut };
577 (pub) => { $crate::token::Pub };
578 (ref) => { $crate::token::Ref };
579 (return) => { $crate::token::Return };
580 (self) => { $crate::token::Self_ };
581 (static) => { $crate::token::Static };
582 (struct) => { $crate::token::Struct };
583 (super) => { $crate::token::Super };
584 (trait) => { $crate::token::Trait };
585 (try) => { $crate::token::Try };
586 (type) => { $crate::token::Type };
587 (union) => { $crate::token::Union };
588 (unsafe) => { $crate::token::Unsafe };
589 (use) => { $crate::token::Use };
590 (where) => { $crate::token::Where };
591 (while) => { $crate::token::While };
592 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400593 (+) => { $crate::token::Add };
594 (+=) => { $crate::token::AddEq };
595 (&) => { $crate::token::And };
596 (&&) => { $crate::token::AndAnd };
597 (&=) => { $crate::token::AndEq };
598 (@) => { $crate::token::At };
599 (!) => { $crate::token::Bang };
600 (^) => { $crate::token::Caret };
601 (^=) => { $crate::token::CaretEq };
602 (:) => { $crate::token::Colon };
603 (::) => { $crate::token::Colon2 };
604 (,) => { $crate::token::Comma };
605 (/) => { $crate::token::Div };
606 (/=) => { $crate::token::DivEq };
607 (.) => { $crate::token::Dot };
608 (..) => { $crate::token::Dot2 };
609 (...) => { $crate::token::Dot3 };
610 (..=) => { $crate::token::DotDotEq };
611 (=) => { $crate::token::Eq };
612 (==) => { $crate::token::EqEq };
613 (>=) => { $crate::token::Ge };
614 (>) => { $crate::token::Gt };
615 (<=) => { $crate::token::Le };
616 (<) => { $crate::token::Lt };
617 (*=) => { $crate::token::MulEq };
618 (!=) => { $crate::token::Ne };
619 (|) => { $crate::token::Or };
620 (|=) => { $crate::token::OrEq };
621 (||) => { $crate::token::OrOr };
622 (#) => { $crate::token::Pound };
623 (?) => { $crate::token::Question };
624 (->) => { $crate::token::RArrow };
625 (<-) => { $crate::token::LArrow };
626 (%) => { $crate::token::Rem };
627 (%=) => { $crate::token::RemEq };
628 (=>) => { $crate::token::FatArrow };
629 (;) => { $crate::token::Semi };
630 (<<) => { $crate::token::Shl };
631 (<<=) => { $crate::token::ShlEq };
632 (>>) => { $crate::token::Shr };
633 (>>=) => { $crate::token::ShrEq };
634 (*) => { $crate::token::Star };
635 (-) => { $crate::token::Sub };
636 (-=) => { $crate::token::SubEq };
637 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800638}
639
David Tolnayf005f962018-01-06 21:19:41 -0800640/// Parse a single Rust punctuation token.
641///
642/// See the [token module] documentation for details and examples.
643///
644/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800645///
646/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500647#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800648#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700649#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800650macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500651 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
652 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
653 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
654 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
655 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
656 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
657 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
658 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
659 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
660 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
661 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
662 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
663 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
664 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
665 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
666 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
667 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
668 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
669 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
670 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
671 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
672 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
673 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
674 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
675 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
676 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
677 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
678 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
679 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
680 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
681 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
682 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
683 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
684 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
685 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200686 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500687 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
688 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
689 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
690 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
691 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
692 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
693 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
694 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
695 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800696}
697
David Tolnayf005f962018-01-06 21:19:41 -0800698/// Parse a single Rust keyword token.
699///
700/// See the [token module] documentation for details and examples.
701///
702/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800703///
704/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500705#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800706#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700707#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800708macro_rules! keyword {
David Tolnaybb82ef02018-08-24 20:15:45 -0400709 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
710 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
711 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
712 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
713 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
714 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
715 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
716 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
717 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
718 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
719 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
720 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
721 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
722 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
723 ($i:expr, existential) => { call!($i, <$crate::token::Existential as $crate::synom::Synom>::parse) };
724 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
725 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
726 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
727 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
728 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
729 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
730 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
731 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
732 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
733 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
734 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
735 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
736 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
737 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
738 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
739 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
740 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
741 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
742 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
743 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
744 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
745 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
746 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
747 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
748 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
749 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
750 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
751 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800752}
753
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700754macro_rules! ident_from_token {
755 ($token:ident) => {
756 impl From<Token![$token]> for Ident {
757 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400758 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700759 }
760 }
761 };
762}
763
764ident_from_token!(self);
765ident_from_token!(Self);
766ident_from_token!(super);
767ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700768ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700769
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700770#[cfg(feature = "parsing")]
771mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500772 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700773
David Tolnaydfc886b2018-01-06 08:03:09 -0800774 use buffer::Cursor;
David Tolnay776f8e02018-08-24 22:32:10 -0400775 use next::parse::{Error, ParseStream, Result};
David Tolnay203557a2017-12-27 23:59:33 -0500776 use parse_error;
David Tolnay776f8e02018-08-24 22:32:10 -0400777 use span::FromSpans;
David Tolnay203557a2017-12-27 23:59:33 -0500778 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700779
David Tolnay776f8e02018-08-24 22:32:10 -0400780 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
781 input.step_cursor(|cursor| {
782 if let Some((ident, rest)) = cursor.ident() {
783 if ident == token {
784 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700785 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700786 }
David Tolnay776f8e02018-08-24 22:32:10 -0400787 Err(cursor.error(format!("expected `{}`", token)))
788 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700789 }
790
David Tolnay776f8e02018-08-24 22:32:10 -0400791 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
792 input.step_cursor(|cursor| {
793 let mut cursor = *cursor;
794 let mut spans = [cursor.span(); 3];
795 assert!(token.len() <= spans.len());
796
797 for (i, ch) in token.chars().enumerate() {
798 match cursor.punct() {
799 Some((punct, rest)) => {
800 spans[i] = punct.span();
801 if punct.as_char() != ch {
802 break;
803 } else if i == token.len() - 1 {
804 return Ok((S::from_spans(&spans), rest));
805 } else if punct.spacing() != Spacing::Joint {
806 break;
807 }
808 cursor = rest;
809 }
810 None => break,
811 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400812 }
David Tolnay776f8e02018-08-24 22:32:10 -0400813
814 Err(Error::new(spans[0], format!("expected `{}`", token)))
815 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700816 }
817
David Tolnay51382052017-12-27 13:46:21 -0500818 pub fn delim<'a, F, R, T>(
819 delim: &str,
820 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700821 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500822 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500823 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500824 where
825 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700826 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400827 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700828 let delim = match delim {
829 "(" => Delimiter::Parenthesis,
830 "{" => Delimiter::Brace,
831 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400832 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700833 _ => panic!("unknown delimiter: {}", delim),
834 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700835
David Tolnay65729482017-12-31 16:14:50 -0500836 if let Some((inside, span, rest)) = tokens.group(delim) {
837 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500838 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400839 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700840 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400841 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700842 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400843 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700844 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700845 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400846 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700847 }
848}
849
850#[cfg(feature = "printing")]
851mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700852 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700853 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700854
Alex Crichtona74a1c82018-05-16 10:20:44 -0700855 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700856 assert_eq!(s.len(), spans.len());
857
858 let mut chars = s.chars();
859 let mut spans = spans.iter();
860 let ch = chars.next_back().unwrap();
861 let span = spans.next_back().unwrap();
862 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700863 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700864 op.set_span(*span);
865 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700866 }
867
Alex Crichtona74a1c82018-05-16 10:20:44 -0700868 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700869 op.set_span(*span);
870 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700871 }
872
Alex Crichtona74a1c82018-05-16 10:20:44 -0700873 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
874 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700875 }
876
Alex Crichtona74a1c82018-05-16 10:20:44 -0700877 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500878 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700879 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700880 {
David Tolnay00ab6982017-12-31 18:15:06 -0500881 let delim = match s {
882 "(" => Delimiter::Parenthesis,
883 "[" => Delimiter::Bracket,
884 "{" => Delimiter::Brace,
885 " " => Delimiter::None,
886 _ => panic!("unknown delimiter: {}", s),
887 };
hcplaa511792018-05-29 07:13:01 +0300888 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500889 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700890 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700891 g.set_span(*span);
892 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700893 }
894}