blob: 1d355a33165b9e74c230f2de027a1a1a421a6c26 [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 Tolnay8c39ac52018-08-25 08:46:21 -0400108#[cfg(any(feature = "printing", feature = "parsing"))]
109use proc_macro2::Spacing;
David Tolnay65fb5662018-05-20 20:02:28 -0700110use proc_macro2::{Ident, Span};
Sergio Benitezd14d5362018-04-28 15:38:25 -0700111#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400112use proc_macro2::{Punct, TokenStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400113#[cfg(feature = "printing")]
114use quote::{ToTokens, TokenStreamExt};
115
116#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400117use error::Result;
118#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400119use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400120#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400121use parse::{Lookahead1, Parse, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400122use span::IntoSpans;
123
124/// Marker trait for types that represent single tokens.
125///
126/// This trait is sealed and cannot be implemented for types outside of Syn.
127#[cfg(feature = "parsing")]
128pub trait Token: private::Sealed {
129 // Not public API.
130 #[doc(hidden)]
131 fn peek(lookahead: &Lookahead1) -> bool;
132
133 // Not public API.
134 #[doc(hidden)]
135 fn display() -> String;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700136}
137
138#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400139mod private {
140 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700141}
142
David Tolnay776f8e02018-08-24 22:32:10 -0400143macro_rules! impl_token {
144 ($token:tt $name:ident) => {
145 #[cfg(feature = "parsing")]
146 impl Token for $name {
147 fn peek(lookahead: &Lookahead1) -> bool {
148 lookahead::is_token(lookahead, $token)
149 }
150
151 fn display() -> String {
152 concat!("`", $token, "`").to_owned()
153 }
154 }
155
156 #[cfg(feature = "parsing")]
157 impl private::Sealed for $name {}
158 };
159}
160
161macro_rules! define_keywords {
162 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
163 $(
164 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
165 #[$doc]
166 ///
167 /// Don't try to remember the name of this type -- use the [`Token!`]
168 /// macro instead.
169 ///
170 /// [`Token!`]: index.html
171 pub struct $name {
172 pub span: Span,
173 }
174
175 #[doc(hidden)]
176 #[allow(non_snake_case)]
177 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
178 $name {
179 span: span.into_spans()[0],
180 }
181 }
182
183 impl_token!($token $name);
184
185 impl std::default::Default for $name {
186 fn default() -> Self {
187 $name(Span::call_site())
188 }
189 }
190
191 #[cfg(feature = "extra-traits")]
192 impl Debug for $name {
193 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194 f.write_str(stringify!($name))
195 }
196 }
197
198 #[cfg(feature = "extra-traits")]
199 impl cmp::Eq for $name {}
200
201 #[cfg(feature = "extra-traits")]
202 impl PartialEq for $name {
203 fn eq(&self, _other: &$name) -> bool {
204 true
205 }
206 }
207
208 #[cfg(feature = "extra-traits")]
209 impl Hash for $name {
210 fn hash<H: Hasher>(&self, _state: &mut H) {}
211 }
212
213 #[cfg(feature = "printing")]
214 impl ToTokens for $name {
215 fn to_tokens(&self, tokens: &mut TokenStream) {
216 printing::keyword($token, &self.span, tokens);
217 }
218 }
219
220 #[cfg(feature = "parsing")]
221 impl Parse for $name {
222 fn parse(input: ParseStream) -> Result<Self> {
223 parsing::keyword(input, $token).map($name)
224 }
225 }
226 )*
227 };
228}
229
230macro_rules! define_punctuation_structs {
231 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
232 $(
233 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
234 #[$doc]
235 ///
236 /// Don't try to remember the name of this type -- use the [`Token!`]
237 /// macro instead.
238 ///
239 /// [`Token!`]: index.html
240 pub struct $name {
241 pub spans: [Span; $len],
242 }
243
244 #[doc(hidden)]
245 #[allow(non_snake_case)]
246 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
247 $name {
248 spans: spans.into_spans(),
249 }
250 }
251
252 impl_token!($token $name);
253
254 impl std::default::Default for $name {
255 fn default() -> Self {
256 $name([Span::call_site(); $len])
257 }
258 }
259
260 #[cfg(feature = "extra-traits")]
261 impl Debug for $name {
262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
263 f.write_str(stringify!($name))
264 }
265 }
266
267 #[cfg(feature = "extra-traits")]
268 impl cmp::Eq for $name {}
269
270 #[cfg(feature = "extra-traits")]
271 impl PartialEq for $name {
272 fn eq(&self, _other: &$name) -> bool {
273 true
274 }
275 }
276
277 #[cfg(feature = "extra-traits")]
278 impl Hash for $name {
279 fn hash<H: Hasher>(&self, _state: &mut H) {}
280 }
281 )*
282 };
283}
284
285macro_rules! define_punctuation {
286 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
287 $(
288 define_punctuation_structs! {
289 $token pub struct $name/$len #[$doc]
290 }
291
292 #[cfg(feature = "printing")]
293 impl ToTokens for $name {
294 fn to_tokens(&self, tokens: &mut TokenStream) {
295 printing::punct($token, &self.spans, tokens);
296 }
297 }
298
299 #[cfg(feature = "parsing")]
300 impl Parse for $name {
301 fn parse(input: ParseStream) -> Result<Self> {
302 parsing::punct(input, $token).map($name::<[Span; $len]>)
303 }
304 }
305 )*
306 };
307}
308
309macro_rules! define_delimiters {
310 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
311 $(
312 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
313 #[$doc]
314 pub struct $name {
315 pub span: Span,
316 }
317
318 #[doc(hidden)]
319 #[allow(non_snake_case)]
320 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
321 $name {
322 span: span.into_spans()[0],
323 }
324 }
325
326 impl std::default::Default for $name {
327 fn default() -> Self {
328 $name(Span::call_site())
329 }
330 }
331
332 #[cfg(feature = "extra-traits")]
333 impl Debug for $name {
334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
335 f.write_str(stringify!($name))
336 }
337 }
338
339 #[cfg(feature = "extra-traits")]
340 impl cmp::Eq for $name {}
341
342 #[cfg(feature = "extra-traits")]
343 impl PartialEq for $name {
344 fn eq(&self, _other: &$name) -> bool {
345 true
346 }
347 }
348
349 #[cfg(feature = "extra-traits")]
350 impl Hash for $name {
351 fn hash<H: Hasher>(&self, _state: &mut H) {}
352 }
353
354 impl $name {
355 #[cfg(feature = "printing")]
356 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
357 where
358 F: FnOnce(&mut TokenStream),
359 {
360 printing::delim($token, &self.span, tokens, f);
361 }
362
363 #[cfg(feature = "parsing")]
364 pub fn parse<F, R>(
365 tokens: $crate::buffer::Cursor,
366 f: F,
367 ) -> $crate::synom::PResult<($name, R)>
368 where
369 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
370 {
371 parsing::delim($token, tokens, $name, f)
372 }
373 }
374 )*
375 };
376}
377
378define_punctuation_structs! {
379 "'" pub struct Apostrophe/1 /// `'`
380 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700381}
382
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700383// Implement Clone anyway because it is required for cloning Lifetime.
384#[cfg(not(feature = "clone-impls"))]
385impl Clone for Apostrophe {
386 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400387 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700388 }
389}
390
Alex Crichton131308c2018-05-18 14:00:24 -0700391#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400392impl ToTokens for Apostrophe {
393 fn to_tokens(&self, tokens: &mut TokenStream) {
394 let mut token = Punct::new('\'', Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400395 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700396 tokens.append(token);
397 }
398}
399
400#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400401impl Parse for Apostrophe {
402 fn parse(input: ParseStream) -> Result<Self> {
403 input.step_cursor(|cursor| {
404 if let Some((punct, rest)) = cursor.punct() {
405 if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint {
406 return Ok((Apostrophe(punct.span()), rest));
Alex Crichton131308c2018-05-18 14:00:24 -0700407 }
408 }
David Tolnay776f8e02018-08-24 22:32:10 -0400409 Err(cursor.error("expected `'`"))
410 })
Alex Crichton131308c2018-05-18 14:00:24 -0700411 }
412}
413
David Tolnay776f8e02018-08-24 22:32:10 -0400414#[cfg(feature = "printing")]
415impl ToTokens for Underscore {
416 fn to_tokens(&self, tokens: &mut TokenStream) {
417 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700418 }
David Tolnay776f8e02018-08-24 22:32:10 -0400419}
420
421#[cfg(feature = "parsing")]
422impl Parse for Underscore {
423 fn parse(input: ParseStream) -> Result<Self> {
424 input.step_cursor(|cursor| {
425 if let Some((ident, rest)) = cursor.ident() {
426 if ident == "_" {
427 return Ok((Underscore(ident.span()), rest));
428 }
429 }
430 if let Some((punct, rest)) = cursor.punct() {
431 if punct.as_char() == '_' {
432 return Ok((Underscore(punct.span()), rest));
433 }
434 }
435 Err(cursor.error("expected `_`"))
436 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700437 }
David Tolnay776f8e02018-08-24 22:32:10 -0400438}
439
440define_keywords! {
441 "as" pub struct As /// `as`
442 "async" pub struct Async /// `async`
443 "auto" pub struct Auto /// `auto`
444 "box" pub struct Box /// `box`
445 "break" pub struct Break /// `break`
446 "Self" pub struct CapSelf /// `Self`
447 "const" pub struct Const /// `const`
448 "continue" pub struct Continue /// `continue`
449 "crate" pub struct Crate /// `crate`
450 "default" pub struct Default /// `default`
451 "dyn" pub struct Dyn /// `dyn`
452 "else" pub struct Else /// `else`
453 "enum" pub struct Enum /// `enum`
454 "existential" pub struct Existential /// `existential`
455 "extern" pub struct Extern /// `extern`
456 "fn" pub struct Fn /// `fn`
457 "for" pub struct For /// `for`
458 "if" pub struct If /// `if`
459 "impl" pub struct Impl /// `impl`
460 "in" pub struct In /// `in`
461 "let" pub struct Let /// `let`
462 "loop" pub struct Loop /// `loop`
463 "macro" pub struct Macro /// `macro`
464 "match" pub struct Match /// `match`
465 "mod" pub struct Mod /// `mod`
466 "move" pub struct Move /// `move`
467 "mut" pub struct Mut /// `mut`
468 "pub" pub struct Pub /// `pub`
469 "ref" pub struct Ref /// `ref`
470 "return" pub struct Return /// `return`
471 "self" pub struct Self_ /// `self`
472 "static" pub struct Static /// `static`
473 "struct" pub struct Struct /// `struct`
474 "super" pub struct Super /// `super`
475 "trait" pub struct Trait /// `trait`
476 "try" pub struct Try /// `try`
477 "type" pub struct Type /// `type`
478 "union" pub struct Union /// `union`
479 "unsafe" pub struct Unsafe /// `unsafe`
480 "use" pub struct Use /// `use`
481 "where" pub struct Where /// `where`
482 "while" pub struct While /// `while`
483 "yield" pub struct Yield /// `yield`
484}
485
486define_punctuation! {
487 "+" pub struct Add/1 /// `+`
488 "+=" pub struct AddEq/2 /// `+=`
489 "&" pub struct And/1 /// `&`
490 "&&" pub struct AndAnd/2 /// `&&`
491 "&=" pub struct AndEq/2 /// `&=`
492 "@" pub struct At/1 /// `@`
493 "!" pub struct Bang/1 /// `!`
494 "^" pub struct Caret/1 /// `^`
495 "^=" pub struct CaretEq/2 /// `^=`
496 ":" pub struct Colon/1 /// `:`
497 "::" pub struct Colon2/2 /// `::`
498 "," pub struct Comma/1 /// `,`
499 "/" pub struct Div/1 /// `/`
500 "/=" pub struct DivEq/2 /// `/=`
501 "$" pub struct Dollar/1 /// `$`
502 "." pub struct Dot/1 /// `.`
503 ".." pub struct Dot2/2 /// `..`
504 "..." pub struct Dot3/3 /// `...`
505 "..=" pub struct DotDotEq/3 /// `..=`
506 "=" pub struct Eq/1 /// `=`
507 "==" pub struct EqEq/2 /// `==`
508 ">=" pub struct Ge/2 /// `>=`
509 ">" pub struct Gt/1 /// `>`
510 "<=" pub struct Le/2 /// `<=`
511 "<" pub struct Lt/1 /// `<`
512 "*=" pub struct MulEq/2 /// `*=`
513 "!=" pub struct Ne/2 /// `!=`
514 "|" pub struct Or/1 /// `|`
515 "|=" pub struct OrEq/2 /// `|=`
516 "||" pub struct OrOr/2 /// `||`
517 "#" pub struct Pound/1 /// `#`
518 "?" pub struct Question/1 /// `?`
519 "->" pub struct RArrow/2 /// `->`
520 "<-" pub struct LArrow/2 /// `<-`
521 "%" pub struct Rem/1 /// `%`
522 "%=" pub struct RemEq/2 /// `%=`
523 "=>" pub struct FatArrow/2 /// `=>`
524 ";" pub struct Semi/1 /// `;`
525 "<<" pub struct Shl/2 /// `<<`
526 "<<=" pub struct ShlEq/3 /// `<<=`
527 ">>" pub struct Shr/2 /// `>>`
528 ">>=" pub struct ShrEq/3 /// `>>=`
529 "*" pub struct Star/1 /// `*`
530 "-" pub struct Sub/1 /// `-`
531 "-=" pub struct SubEq/2 /// `-=`
532}
533
534define_delimiters! {
535 "{" pub struct Brace /// `{...}`
536 "[" pub struct Bracket /// `[...]`
537 "(" pub struct Paren /// `(...)`
538 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700539}
540
David Tolnayf005f962018-01-06 21:19:41 -0800541/// A type-macro that expands to the name of the Rust type representation of a
542/// given token.
543///
544/// See the [token module] documentation for details and examples.
545///
546/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800547// Unfortunate duplication due to a rustdoc bug.
548// https://github.com/rust-lang/rust/issues/45939
549#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700550#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800551macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400552 (as) => { $crate::token::As };
553 (async) => { $crate::token::Async };
554 (auto) => { $crate::token::Auto };
555 (box) => { $crate::token::Box };
556 (break) => { $crate::token::Break };
557 (Self) => { $crate::token::CapSelf };
558 (const) => { $crate::token::Const };
559 (continue) => { $crate::token::Continue };
560 (crate) => { $crate::token::Crate };
561 (default) => { $crate::token::Default };
562 (dyn) => { $crate::token::Dyn };
563 (else) => { $crate::token::Else };
564 (enum) => { $crate::token::Enum };
565 (existential) => { $crate::token::Existential };
566 (extern) => { $crate::token::Extern };
567 (fn) => { $crate::token::Fn };
568 (for) => { $crate::token::For };
569 (if) => { $crate::token::If };
570 (impl) => { $crate::token::Impl };
571 (in) => { $crate::token::In };
572 (let) => { $crate::token::Let };
573 (loop) => { $crate::token::Loop };
574 (macro) => { $crate::token::Macro };
575 (match) => { $crate::token::Match };
576 (mod) => { $crate::token::Mod };
577 (move) => { $crate::token::Move };
578 (mut) => { $crate::token::Mut };
579 (pub) => { $crate::token::Pub };
580 (ref) => { $crate::token::Ref };
581 (return) => { $crate::token::Return };
582 (self) => { $crate::token::Self_ };
583 (static) => { $crate::token::Static };
584 (struct) => { $crate::token::Struct };
585 (super) => { $crate::token::Super };
586 (trait) => { $crate::token::Trait };
587 (try) => { $crate::token::Try };
588 (type) => { $crate::token::Type };
589 (union) => { $crate::token::Union };
590 (unsafe) => { $crate::token::Unsafe };
591 (use) => { $crate::token::Use };
592 (where) => { $crate::token::Where };
593 (while) => { $crate::token::While };
594 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400595 (+) => { $crate::token::Add };
596 (+=) => { $crate::token::AddEq };
597 (&) => { $crate::token::And };
598 (&&) => { $crate::token::AndAnd };
599 (&=) => { $crate::token::AndEq };
600 (@) => { $crate::token::At };
601 (!) => { $crate::token::Bang };
602 (^) => { $crate::token::Caret };
603 (^=) => { $crate::token::CaretEq };
604 (:) => { $crate::token::Colon };
605 (::) => { $crate::token::Colon2 };
606 (,) => { $crate::token::Comma };
607 (/) => { $crate::token::Div };
608 (/=) => { $crate::token::DivEq };
609 (.) => { $crate::token::Dot };
610 (..) => { $crate::token::Dot2 };
611 (...) => { $crate::token::Dot3 };
612 (..=) => { $crate::token::DotDotEq };
613 (=) => { $crate::token::Eq };
614 (==) => { $crate::token::EqEq };
615 (>=) => { $crate::token::Ge };
616 (>) => { $crate::token::Gt };
617 (<=) => { $crate::token::Le };
618 (<) => { $crate::token::Lt };
619 (*=) => { $crate::token::MulEq };
620 (!=) => { $crate::token::Ne };
621 (|) => { $crate::token::Or };
622 (|=) => { $crate::token::OrEq };
623 (||) => { $crate::token::OrOr };
624 (#) => { $crate::token::Pound };
625 (?) => { $crate::token::Question };
626 (->) => { $crate::token::RArrow };
627 (<-) => { $crate::token::LArrow };
628 (%) => { $crate::token::Rem };
629 (%=) => { $crate::token::RemEq };
630 (=>) => { $crate::token::FatArrow };
631 (;) => { $crate::token::Semi };
632 (<<) => { $crate::token::Shl };
633 (<<=) => { $crate::token::ShlEq };
634 (>>) => { $crate::token::Shr };
635 (>>=) => { $crate::token::ShrEq };
636 (*) => { $crate::token::Star };
637 (-) => { $crate::token::Sub };
638 (-=) => { $crate::token::SubEq };
639 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800640}
641
David Tolnayf005f962018-01-06 21:19:41 -0800642/// Parse a single Rust punctuation token.
643///
644/// See the [token module] documentation for details and examples.
645///
646/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800647///
648/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500649#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800650#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700651#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800652macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500653 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
654 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
655 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
656 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
657 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
658 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
659 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
660 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
661 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
662 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
663 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
664 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
665 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
666 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
667 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
668 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
669 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
670 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
671 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
672 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
673 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
674 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
675 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
676 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
677 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
678 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
679 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
680 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
681 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
682 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
683 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
684 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
685 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
686 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
687 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200688 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500689 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
690 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
691 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
692 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
693 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
694 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
695 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
696 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
697 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800698}
699
David Tolnayf005f962018-01-06 21:19:41 -0800700/// Parse a single Rust keyword token.
701///
702/// See the [token module] documentation for details and examples.
703///
704/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800705///
706/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500707#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800708#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700709#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800710macro_rules! keyword {
David Tolnaybb82ef02018-08-24 20:15:45 -0400711 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
712 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
713 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
714 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
715 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
716 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
717 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
718 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
719 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
720 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
721 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
722 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
723 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
724 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
725 ($i:expr, existential) => { call!($i, <$crate::token::Existential as $crate::synom::Synom>::parse) };
726 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
727 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
728 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
729 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
730 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
731 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
732 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
733 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
734 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
735 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
736 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
737 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
738 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
739 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
740 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
741 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
742 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
743 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
744 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
745 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
746 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
747 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
748 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
749 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
750 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
751 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
752 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
753 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800754}
755
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700756macro_rules! ident_from_token {
757 ($token:ident) => {
758 impl From<Token![$token]> for Ident {
759 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400760 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700761 }
762 }
763 };
764}
765
766ident_from_token!(self);
767ident_from_token!(Self);
768ident_from_token!(super);
769ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700770ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700771
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700772#[cfg(feature = "parsing")]
773mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500774 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700775
David Tolnaydfc886b2018-01-06 08:03:09 -0800776 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400777 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400778 use parse::ParseStream;
David Tolnay203557a2017-12-27 23:59:33 -0500779 use parse_error;
David Tolnay776f8e02018-08-24 22:32:10 -0400780 use span::FromSpans;
David Tolnay203557a2017-12-27 23:59:33 -0500781 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700782
David Tolnay776f8e02018-08-24 22:32:10 -0400783 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
784 input.step_cursor(|cursor| {
785 if let Some((ident, rest)) = cursor.ident() {
786 if ident == token {
787 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700788 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700789 }
David Tolnay776f8e02018-08-24 22:32:10 -0400790 Err(cursor.error(format!("expected `{}`", token)))
791 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700792 }
793
David Tolnay776f8e02018-08-24 22:32:10 -0400794 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
795 input.step_cursor(|cursor| {
796 let mut cursor = *cursor;
797 let mut spans = [cursor.span(); 3];
798 assert!(token.len() <= spans.len());
799
800 for (i, ch) in token.chars().enumerate() {
801 match cursor.punct() {
802 Some((punct, rest)) => {
803 spans[i] = punct.span();
804 if punct.as_char() != ch {
805 break;
806 } else if i == token.len() - 1 {
807 return Ok((S::from_spans(&spans), rest));
808 } else if punct.spacing() != Spacing::Joint {
809 break;
810 }
811 cursor = rest;
812 }
813 None => break,
814 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400815 }
David Tolnay776f8e02018-08-24 22:32:10 -0400816
817 Err(Error::new(spans[0], format!("expected `{}`", token)))
818 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700819 }
820
David Tolnay51382052017-12-27 13:46:21 -0500821 pub fn delim<'a, F, R, T>(
822 delim: &str,
823 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700824 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500825 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500826 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500827 where
828 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700829 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400830 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700831 let delim = match delim {
832 "(" => Delimiter::Parenthesis,
833 "{" => Delimiter::Brace,
834 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400835 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700836 _ => panic!("unknown delimiter: {}", delim),
837 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700838
David Tolnay65729482017-12-31 16:14:50 -0500839 if let Some((inside, span, rest)) = tokens.group(delim) {
840 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500841 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400842 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700843 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400844 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700845 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400846 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700847 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700848 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400849 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700850 }
851}
852
853#[cfg(feature = "printing")]
854mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700855 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700856 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700857
Alex Crichtona74a1c82018-05-16 10:20:44 -0700858 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700859 assert_eq!(s.len(), spans.len());
860
861 let mut chars = s.chars();
862 let mut spans = spans.iter();
863 let ch = chars.next_back().unwrap();
864 let span = spans.next_back().unwrap();
865 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700866 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700867 op.set_span(*span);
868 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700869 }
870
Alex Crichtona74a1c82018-05-16 10:20:44 -0700871 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700872 op.set_span(*span);
873 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700874 }
875
Alex Crichtona74a1c82018-05-16 10:20:44 -0700876 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
877 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700878 }
879
Alex Crichtona74a1c82018-05-16 10:20:44 -0700880 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500881 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700882 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700883 {
David Tolnay00ab6982017-12-31 18:15:06 -0500884 let delim = match s {
885 "(" => Delimiter::Parenthesis,
886 "[" => Delimiter::Bracket,
887 "{" => Delimiter::Brace,
888 " " => Delimiter::None,
889 _ => panic!("unknown delimiter: {}", s),
890 };
hcplaa511792018-05-29 07:13:01 +0300891 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500892 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700893 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700894 g.set_span(*span);
895 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700896 }
897}