blob: 68f9475530a23607e15e8c84f232f4b5dc2fcec6 [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//! ```
David Tolnaye79ae182018-01-06 19:23:37 -080024//! # extern crate syn;
25//! #
David Tolnay9b00f652018-09-01 10:31:02 -070026//! # use syn::{Attribute, Expr, Ident, Token, Type, Visibility};
David Tolnaye79ae182018-01-06 19:23:37 -080027//! #
28//! pub struct ItemStatic {
29//! pub attrs: Vec<Attribute>,
30//! pub vis: Visibility,
31//! pub static_token: Token![static],
32//! pub mutability: Option<Token![mut]>,
33//! pub ident: Ident,
34//! pub colon_token: Token![:],
35//! pub ty: Box<Type>,
36//! pub eq_token: Token![=],
37//! pub expr: Box<Expr>,
38//! pub semi_token: Token![;],
39//! }
40//! #
41//! # fn main() {}
42//! ```
43//!
44//! # Parsing
45//!
David Tolnayd8cc0552018-08-31 08:39:17 -070046//! Keywords and punctuation can be parsed through the [`ParseStream::parse`]
47//! method. Delimiter tokens are parsed using the [`parenthesized!`],
48//! [`bracketed!`] and [`braced!`] macros.
David Tolnaye79ae182018-01-06 19:23:37 -080049//!
David Tolnayd8cc0552018-08-31 08:39:17 -070050//! [`ParseStream::parse`]: ../parse/struct.ParseBuffer.html#method.parse
51//! [`parenthesized!`]: ../macro.parenthesized.html
52//! [`bracketed!`]: ../macro.bracketed.html
53//! [`braced!`]: ../macro.braced.html
David Tolnaye79ae182018-01-06 19:23:37 -080054//!
55//! ```
David Tolnay9b00f652018-09-01 10:31:02 -070056//! # extern crate syn;
57//! #
David Tolnayd8cc0552018-08-31 08:39:17 -070058//! use syn::Attribute;
59//! use syn::parse::{Parse, ParseStream, Result};
David Tolnaye79ae182018-01-06 19:23:37 -080060//! #
David Tolnay9b00f652018-09-01 10:31:02 -070061//! # enum ItemStatic {}
David Tolnaye79ae182018-01-06 19:23:37 -080062//!
63//! // Parse the ItemStatic struct shown above.
David Tolnayd8cc0552018-08-31 08:39:17 -070064//! impl Parse for ItemStatic {
65//! fn parse(input: ParseStream) -> Result<Self> {
David Tolnay9b00f652018-09-01 10:31:02 -070066//! # use syn::ItemStatic;
67//! # fn parse(input: ParseStream) -> Result<ItemStatic> {
68//! Ok(ItemStatic {
69//! attrs: input.call(Attribute::parse_outer)?,
70//! vis: input.parse()?,
71//! static_token: input.parse()?,
72//! mutability: input.parse()?,
73//! ident: input.parse()?,
74//! colon_token: input.parse()?,
75//! ty: input.parse()?,
76//! eq_token: input.parse()?,
77//! expr: input.parse()?,
78//! semi_token: input.parse()?,
79//! })
80//! # }
81//! # unimplemented!()
82//! }
David Tolnaye79ae182018-01-06 19:23:37 -080083//! }
84//! #
85//! # fn main() {}
86//! ```
Alex Crichton954046c2017-05-30 21:49:42 -070087
David Tolnay776f8e02018-08-24 22:32:10 -040088use std;
David Tolnayd9836922018-08-25 18:05:36 -040089#[cfg(feature = "parsing")]
90use std::cell::Cell;
David Tolnay776f8e02018-08-24 22:32:10 -040091#[cfg(feature = "extra-traits")]
92use std::cmp;
93#[cfg(feature = "extra-traits")]
94use std::fmt::{self, Debug};
95#[cfg(feature = "extra-traits")]
96use std::hash::{Hash, Hasher};
David Tolnayd9836922018-08-25 18:05:36 -040097#[cfg(feature = "parsing")]
98use std::rc::Rc;
David Tolnay776f8e02018-08-24 22:32:10 -040099
David Tolnay2d84a082018-08-25 16:31:38 -0400100#[cfg(feature = "parsing")]
101use proc_macro2::Delimiter;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700102#[cfg(feature = "printing")]
David Tolnay78612672018-08-31 08:47:41 -0700103use proc_macro2::TokenStream;
104use proc_macro2::{Ident, Span};
David Tolnay776f8e02018-08-24 22:32:10 -0400105#[cfg(feature = "printing")]
106use quote::{ToTokens, TokenStreamExt};
107
108#[cfg(feature = "parsing")]
David Tolnay00f81fd2018-09-01 10:50:12 -0700109use buffer::Cursor;
110#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400111use error::Result;
David Tolnaya465b2d2018-08-27 08:21:09 -0700112#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayad4b2472018-08-25 08:25:24 -0400113#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400114use lifetime::Lifetime;
David Tolnaya465b2d2018-08-27 08:21:09 -0700115#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400116#[cfg(feature = "parsing")]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400117use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr};
David Tolnay4fb71232018-08-25 23:14:50 -0400118#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400119use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400120#[cfg(feature = "parsing")]
David Tolnay00f81fd2018-09-01 10:50:12 -0700121use parse::{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)]
David Tolnay00f81fd2018-09-01 10:50:12 -0700131 fn peek(cursor: Cursor) -> bool;
David Tolnay776f8e02018-08-24 22:32:10 -0400132
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 {
David Tolnay4fb71232018-08-25 23:14:50 -0400144 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400145 #[cfg(feature = "parsing")]
146 impl Token for $name {
David Tolnay00f81fd2018-09-01 10:50:12 -0700147 fn peek(cursor: Cursor) -> bool {
David Tolnayd9836922018-08-25 18:05:36 -0400148 // TODO factor out in a way that can be compiled just once
149 let scope = Span::call_site();
David Tolnayd9836922018-08-25 18:05:36 -0400150 let unexpected = Rc::new(Cell::new(None));
David Tolnay10951d52018-08-31 10:27:39 -0700151 ::private::new_parse_buffer(scope, cursor, unexpected)
David Tolnayd9836922018-08-25 18:05:36 -0400152 .parse::<Self>()
153 .is_ok()
David Tolnay776f8e02018-08-24 22:32:10 -0400154 }
155
156 fn display() -> String {
David Tolnay4fb71232018-08-25 23:14:50 -0400157 $display.to_owned()
David Tolnay776f8e02018-08-24 22:32:10 -0400158 }
159 }
160
161 #[cfg(feature = "parsing")]
162 impl private::Sealed for $name {}
163 };
164}
165
David Tolnay4fb71232018-08-25 23:14:50 -0400166impl_token!(Ident "identifier");
David Tolnaya465b2d2018-08-27 08:21:09 -0700167#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400168impl_token!(Lifetime "lifetime");
David Tolnaya465b2d2018-08-27 08:21:09 -0700169#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400170impl_token!(Lit "literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700171#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400172impl_token!(LitStr "string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700173#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400174impl_token!(LitByteStr "byte string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700175#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400176impl_token!(LitByte "byte literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700177#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400178impl_token!(LitChar "character literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700179#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400180impl_token!(LitInt "integer literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700181#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400182impl_token!(LitFloat "floating point literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700183#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400184impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400185
David Tolnay776f8e02018-08-24 22:32:10 -0400186macro_rules! define_keywords {
187 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
188 $(
189 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
190 #[$doc]
191 ///
192 /// Don't try to remember the name of this type -- use the [`Token!`]
193 /// macro instead.
194 ///
195 /// [`Token!`]: index.html
196 pub struct $name {
197 pub span: Span,
198 }
199
200 #[doc(hidden)]
201 #[allow(non_snake_case)]
202 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
203 $name {
204 span: span.into_spans()[0],
205 }
206 }
207
David Tolnay4fb71232018-08-25 23:14:50 -0400208 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400209
210 impl std::default::Default for $name {
211 fn default() -> Self {
212 $name(Span::call_site())
213 }
214 }
215
216 #[cfg(feature = "extra-traits")]
217 impl Debug for $name {
218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219 f.write_str(stringify!($name))
220 }
221 }
222
223 #[cfg(feature = "extra-traits")]
224 impl cmp::Eq for $name {}
225
226 #[cfg(feature = "extra-traits")]
227 impl PartialEq for $name {
228 fn eq(&self, _other: &$name) -> bool {
229 true
230 }
231 }
232
233 #[cfg(feature = "extra-traits")]
234 impl Hash for $name {
235 fn hash<H: Hasher>(&self, _state: &mut H) {}
236 }
237
238 #[cfg(feature = "printing")]
239 impl ToTokens for $name {
240 fn to_tokens(&self, tokens: &mut TokenStream) {
241 printing::keyword($token, &self.span, tokens);
242 }
243 }
244
245 #[cfg(feature = "parsing")]
246 impl Parse for $name {
247 fn parse(input: ParseStream) -> Result<Self> {
248 parsing::keyword(input, $token).map($name)
249 }
250 }
251 )*
252 };
253}
254
255macro_rules! define_punctuation_structs {
256 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
257 $(
258 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
259 #[$doc]
260 ///
261 /// Don't try to remember the name of this type -- use the [`Token!`]
262 /// macro instead.
263 ///
264 /// [`Token!`]: index.html
265 pub struct $name {
266 pub spans: [Span; $len],
267 }
268
269 #[doc(hidden)]
270 #[allow(non_snake_case)]
271 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
272 $name {
273 spans: spans.into_spans(),
274 }
275 }
276
David Tolnay4fb71232018-08-25 23:14:50 -0400277 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400278
279 impl std::default::Default for $name {
280 fn default() -> Self {
281 $name([Span::call_site(); $len])
282 }
283 }
284
285 #[cfg(feature = "extra-traits")]
286 impl Debug for $name {
287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
288 f.write_str(stringify!($name))
289 }
290 }
291
292 #[cfg(feature = "extra-traits")]
293 impl cmp::Eq for $name {}
294
295 #[cfg(feature = "extra-traits")]
296 impl PartialEq for $name {
297 fn eq(&self, _other: &$name) -> bool {
298 true
299 }
300 }
301
302 #[cfg(feature = "extra-traits")]
303 impl Hash for $name {
304 fn hash<H: Hasher>(&self, _state: &mut H) {}
305 }
306 )*
307 };
308}
309
310macro_rules! define_punctuation {
311 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
312 $(
313 define_punctuation_structs! {
314 $token pub struct $name/$len #[$doc]
315 }
316
317 #[cfg(feature = "printing")]
318 impl ToTokens for $name {
319 fn to_tokens(&self, tokens: &mut TokenStream) {
320 printing::punct($token, &self.spans, tokens);
321 }
322 }
323
324 #[cfg(feature = "parsing")]
325 impl Parse for $name {
326 fn parse(input: ParseStream) -> Result<Self> {
327 parsing::punct(input, $token).map($name::<[Span; $len]>)
328 }
329 }
330 )*
331 };
332}
333
334macro_rules! define_delimiters {
335 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
336 $(
337 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
338 #[$doc]
339 pub struct $name {
340 pub span: Span,
341 }
342
343 #[doc(hidden)]
344 #[allow(non_snake_case)]
345 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
346 $name {
347 span: span.into_spans()[0],
348 }
349 }
350
351 impl std::default::Default for $name {
352 fn default() -> Self {
353 $name(Span::call_site())
354 }
355 }
356
357 #[cfg(feature = "extra-traits")]
358 impl Debug for $name {
359 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
360 f.write_str(stringify!($name))
361 }
362 }
363
364 #[cfg(feature = "extra-traits")]
365 impl cmp::Eq for $name {}
366
367 #[cfg(feature = "extra-traits")]
368 impl PartialEq for $name {
369 fn eq(&self, _other: &$name) -> bool {
370 true
371 }
372 }
373
374 #[cfg(feature = "extra-traits")]
375 impl Hash for $name {
376 fn hash<H: Hasher>(&self, _state: &mut H) {}
377 }
378
379 impl $name {
380 #[cfg(feature = "printing")]
381 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
382 where
383 F: FnOnce(&mut TokenStream),
384 {
385 printing::delim($token, &self.span, tokens, f);
386 }
David Tolnay776f8e02018-08-24 22:32:10 -0400387 }
David Tolnay2d84a082018-08-25 16:31:38 -0400388
389 #[cfg(feature = "parsing")]
390 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400391 )*
392 };
393}
394
395define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400396 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700397}
398
David Tolnay776f8e02018-08-24 22:32:10 -0400399#[cfg(feature = "printing")]
400impl ToTokens for Underscore {
401 fn to_tokens(&self, tokens: &mut TokenStream) {
402 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700403 }
David Tolnay776f8e02018-08-24 22:32:10 -0400404}
405
406#[cfg(feature = "parsing")]
407impl Parse for Underscore {
408 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700409 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400410 if let Some((ident, rest)) = cursor.ident() {
411 if ident == "_" {
412 return Ok((Underscore(ident.span()), rest));
413 }
414 }
415 if let Some((punct, rest)) = cursor.punct() {
416 if punct.as_char() == '_' {
417 return Ok((Underscore(punct.span()), rest));
418 }
419 }
420 Err(cursor.error("expected `_`"))
421 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700422 }
David Tolnay776f8e02018-08-24 22:32:10 -0400423}
424
David Tolnay2d84a082018-08-25 16:31:38 -0400425#[cfg(feature = "parsing")]
426impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700427 fn peek(cursor: Cursor) -> bool {
428 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400429 }
430
431 fn display() -> String {
432 "parentheses".to_owned()
433 }
434}
435
436#[cfg(feature = "parsing")]
437impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700438 fn peek(cursor: Cursor) -> bool {
439 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400440 }
441
442 fn display() -> String {
443 "curly braces".to_owned()
444 }
445}
446
447#[cfg(feature = "parsing")]
448impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700449 fn peek(cursor: Cursor) -> bool {
450 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400451 }
452
453 fn display() -> String {
454 "square brackets".to_owned()
455 }
456}
457
David Tolnaya7d69fc2018-08-26 13:30:24 -0400458#[cfg(feature = "parsing")]
459impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700460 fn peek(cursor: Cursor) -> bool {
461 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400462 }
463
464 fn display() -> String {
465 "invisible group".to_owned()
466 }
467}
468
David Tolnay776f8e02018-08-24 22:32:10 -0400469define_keywords! {
470 "as" pub struct As /// `as`
471 "async" pub struct Async /// `async`
472 "auto" pub struct Auto /// `auto`
473 "box" pub struct Box /// `box`
474 "break" pub struct Break /// `break`
475 "Self" pub struct CapSelf /// `Self`
476 "const" pub struct Const /// `const`
477 "continue" pub struct Continue /// `continue`
478 "crate" pub struct Crate /// `crate`
479 "default" pub struct Default /// `default`
480 "dyn" pub struct Dyn /// `dyn`
481 "else" pub struct Else /// `else`
482 "enum" pub struct Enum /// `enum`
483 "existential" pub struct Existential /// `existential`
484 "extern" pub struct Extern /// `extern`
485 "fn" pub struct Fn /// `fn`
486 "for" pub struct For /// `for`
487 "if" pub struct If /// `if`
488 "impl" pub struct Impl /// `impl`
489 "in" pub struct In /// `in`
490 "let" pub struct Let /// `let`
491 "loop" pub struct Loop /// `loop`
492 "macro" pub struct Macro /// `macro`
493 "match" pub struct Match /// `match`
494 "mod" pub struct Mod /// `mod`
495 "move" pub struct Move /// `move`
496 "mut" pub struct Mut /// `mut`
497 "pub" pub struct Pub /// `pub`
498 "ref" pub struct Ref /// `ref`
499 "return" pub struct Return /// `return`
500 "self" pub struct Self_ /// `self`
501 "static" pub struct Static /// `static`
502 "struct" pub struct Struct /// `struct`
503 "super" pub struct Super /// `super`
504 "trait" pub struct Trait /// `trait`
505 "try" pub struct Try /// `try`
506 "type" pub struct Type /// `type`
507 "union" pub struct Union /// `union`
508 "unsafe" pub struct Unsafe /// `unsafe`
509 "use" pub struct Use /// `use`
510 "where" pub struct Where /// `where`
511 "while" pub struct While /// `while`
512 "yield" pub struct Yield /// `yield`
513}
514
515define_punctuation! {
516 "+" pub struct Add/1 /// `+`
517 "+=" pub struct AddEq/2 /// `+=`
518 "&" pub struct And/1 /// `&`
519 "&&" pub struct AndAnd/2 /// `&&`
520 "&=" pub struct AndEq/2 /// `&=`
521 "@" pub struct At/1 /// `@`
522 "!" pub struct Bang/1 /// `!`
523 "^" pub struct Caret/1 /// `^`
524 "^=" pub struct CaretEq/2 /// `^=`
525 ":" pub struct Colon/1 /// `:`
526 "::" pub struct Colon2/2 /// `::`
527 "," pub struct Comma/1 /// `,`
528 "/" pub struct Div/1 /// `/`
529 "/=" pub struct DivEq/2 /// `/=`
530 "$" pub struct Dollar/1 /// `$`
531 "." pub struct Dot/1 /// `.`
532 ".." pub struct Dot2/2 /// `..`
533 "..." pub struct Dot3/3 /// `...`
534 "..=" pub struct DotDotEq/3 /// `..=`
535 "=" pub struct Eq/1 /// `=`
536 "==" pub struct EqEq/2 /// `==`
537 ">=" pub struct Ge/2 /// `>=`
538 ">" pub struct Gt/1 /// `>`
539 "<=" pub struct Le/2 /// `<=`
540 "<" pub struct Lt/1 /// `<`
541 "*=" pub struct MulEq/2 /// `*=`
542 "!=" pub struct Ne/2 /// `!=`
543 "|" pub struct Or/1 /// `|`
544 "|=" pub struct OrEq/2 /// `|=`
545 "||" pub struct OrOr/2 /// `||`
546 "#" pub struct Pound/1 /// `#`
547 "?" pub struct Question/1 /// `?`
548 "->" pub struct RArrow/2 /// `->`
549 "<-" pub struct LArrow/2 /// `<-`
550 "%" pub struct Rem/1 /// `%`
551 "%=" pub struct RemEq/2 /// `%=`
552 "=>" pub struct FatArrow/2 /// `=>`
553 ";" pub struct Semi/1 /// `;`
554 "<<" pub struct Shl/2 /// `<<`
555 "<<=" pub struct ShlEq/3 /// `<<=`
556 ">>" pub struct Shr/2 /// `>>`
557 ">>=" pub struct ShrEq/3 /// `>>=`
558 "*" pub struct Star/1 /// `*`
559 "-" pub struct Sub/1 /// `-`
560 "-=" pub struct SubEq/2 /// `-=`
561}
562
563define_delimiters! {
564 "{" pub struct Brace /// `{...}`
565 "[" pub struct Bracket /// `[...]`
566 "(" pub struct Paren /// `(...)`
567 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700568}
569
David Tolnayf005f962018-01-06 21:19:41 -0800570/// A type-macro that expands to the name of the Rust type representation of a
571/// given token.
572///
573/// See the [token module] documentation for details and examples.
574///
575/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800576// Unfortunate duplication due to a rustdoc bug.
577// https://github.com/rust-lang/rust/issues/45939
578#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700579#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800580macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400581 (as) => { $crate::token::As };
582 (async) => { $crate::token::Async };
583 (auto) => { $crate::token::Auto };
584 (box) => { $crate::token::Box };
585 (break) => { $crate::token::Break };
586 (Self) => { $crate::token::CapSelf };
587 (const) => { $crate::token::Const };
588 (continue) => { $crate::token::Continue };
589 (crate) => { $crate::token::Crate };
590 (default) => { $crate::token::Default };
591 (dyn) => { $crate::token::Dyn };
592 (else) => { $crate::token::Else };
593 (enum) => { $crate::token::Enum };
594 (existential) => { $crate::token::Existential };
595 (extern) => { $crate::token::Extern };
596 (fn) => { $crate::token::Fn };
597 (for) => { $crate::token::For };
598 (if) => { $crate::token::If };
599 (impl) => { $crate::token::Impl };
600 (in) => { $crate::token::In };
601 (let) => { $crate::token::Let };
602 (loop) => { $crate::token::Loop };
603 (macro) => { $crate::token::Macro };
604 (match) => { $crate::token::Match };
605 (mod) => { $crate::token::Mod };
606 (move) => { $crate::token::Move };
607 (mut) => { $crate::token::Mut };
608 (pub) => { $crate::token::Pub };
609 (ref) => { $crate::token::Ref };
610 (return) => { $crate::token::Return };
611 (self) => { $crate::token::Self_ };
612 (static) => { $crate::token::Static };
613 (struct) => { $crate::token::Struct };
614 (super) => { $crate::token::Super };
615 (trait) => { $crate::token::Trait };
616 (try) => { $crate::token::Try };
617 (type) => { $crate::token::Type };
618 (union) => { $crate::token::Union };
619 (unsafe) => { $crate::token::Unsafe };
620 (use) => { $crate::token::Use };
621 (where) => { $crate::token::Where };
622 (while) => { $crate::token::While };
623 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400624 (+) => { $crate::token::Add };
625 (+=) => { $crate::token::AddEq };
626 (&) => { $crate::token::And };
627 (&&) => { $crate::token::AndAnd };
628 (&=) => { $crate::token::AndEq };
629 (@) => { $crate::token::At };
630 (!) => { $crate::token::Bang };
631 (^) => { $crate::token::Caret };
632 (^=) => { $crate::token::CaretEq };
633 (:) => { $crate::token::Colon };
634 (::) => { $crate::token::Colon2 };
635 (,) => { $crate::token::Comma };
636 (/) => { $crate::token::Div };
637 (/=) => { $crate::token::DivEq };
638 (.) => { $crate::token::Dot };
639 (..) => { $crate::token::Dot2 };
640 (...) => { $crate::token::Dot3 };
641 (..=) => { $crate::token::DotDotEq };
642 (=) => { $crate::token::Eq };
643 (==) => { $crate::token::EqEq };
644 (>=) => { $crate::token::Ge };
645 (>) => { $crate::token::Gt };
646 (<=) => { $crate::token::Le };
647 (<) => { $crate::token::Lt };
648 (*=) => { $crate::token::MulEq };
649 (!=) => { $crate::token::Ne };
650 (|) => { $crate::token::Or };
651 (|=) => { $crate::token::OrEq };
652 (||) => { $crate::token::OrOr };
653 (#) => { $crate::token::Pound };
654 (?) => { $crate::token::Question };
655 (->) => { $crate::token::RArrow };
656 (<-) => { $crate::token::LArrow };
657 (%) => { $crate::token::Rem };
658 (%=) => { $crate::token::RemEq };
659 (=>) => { $crate::token::FatArrow };
660 (;) => { $crate::token::Semi };
661 (<<) => { $crate::token::Shl };
662 (<<=) => { $crate::token::ShlEq };
663 (>>) => { $crate::token::Shr };
664 (>>=) => { $crate::token::ShrEq };
665 (*) => { $crate::token::Star };
666 (-) => { $crate::token::Sub };
667 (-=) => { $crate::token::SubEq };
668 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800669}
670
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700671macro_rules! ident_from_token {
672 ($token:ident) => {
673 impl From<Token![$token]> for Ident {
674 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400675 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700676 }
677 }
678 };
679}
680
681ident_from_token!(self);
682ident_from_token!(Self);
683ident_from_token!(super);
684ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700685ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700686
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700687#[cfg(feature = "parsing")]
688mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700689 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700690
David Tolnayad4b2472018-08-25 08:25:24 -0400691 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400692 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400693 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700694
David Tolnay776f8e02018-08-24 22:32:10 -0400695 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700696 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400697 if let Some((ident, rest)) = cursor.ident() {
698 if ident == token {
699 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700700 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700701 }
David Tolnay776f8e02018-08-24 22:32:10 -0400702 Err(cursor.error(format!("expected `{}`", token)))
703 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700704 }
705
David Tolnay776f8e02018-08-24 22:32:10 -0400706 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700707 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400708 let mut cursor = *cursor;
709 let mut spans = [cursor.span(); 3];
710 assert!(token.len() <= spans.len());
711
712 for (i, ch) in token.chars().enumerate() {
713 match cursor.punct() {
714 Some((punct, rest)) => {
715 spans[i] = punct.span();
716 if punct.as_char() != ch {
717 break;
718 } else if i == token.len() - 1 {
719 return Ok((S::from_spans(&spans), rest));
720 } else if punct.spacing() != Spacing::Joint {
721 break;
722 }
723 cursor = rest;
724 }
725 None => break,
726 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400727 }
David Tolnay776f8e02018-08-24 22:32:10 -0400728
729 Err(Error::new(spans[0], format!("expected `{}`", token)))
730 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700731 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700732}
733
734#[cfg(feature = "printing")]
735mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700736 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700737 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700738
Alex Crichtona74a1c82018-05-16 10:20:44 -0700739 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700740 assert_eq!(s.len(), spans.len());
741
742 let mut chars = s.chars();
743 let mut spans = spans.iter();
744 let ch = chars.next_back().unwrap();
745 let span = spans.next_back().unwrap();
746 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700747 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700748 op.set_span(*span);
749 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700750 }
751
Alex Crichtona74a1c82018-05-16 10:20:44 -0700752 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700753 op.set_span(*span);
754 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700755 }
756
Alex Crichtona74a1c82018-05-16 10:20:44 -0700757 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
758 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700759 }
760
Alex Crichtona74a1c82018-05-16 10:20:44 -0700761 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500762 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700763 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700764 {
David Tolnay00ab6982017-12-31 18:15:06 -0500765 let delim = match s {
766 "(" => Delimiter::Parenthesis,
767 "[" => Delimiter::Bracket,
768 "{" => Delimiter::Brace,
769 " " => Delimiter::None,
770 _ => panic!("unknown delimiter: {}", s),
771 };
hcplaa511792018-05-29 07:13:01 +0300772 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500773 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700774 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700775 g.set_span(*span);
776 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700777 }
778}