blob: a95bdc210635742092e7c3b574a04856db48c0b3 [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)]
David Tolnay2d032802018-09-01 10:51:59 -0700135 fn display() -> &'static str;
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 Tolnay65557f02018-09-01 11:08:27 -0700143#[cfg(feature = "parsing")]
144fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool {
145 let scope = Span::call_site();
146 let unexpected = Rc::new(Cell::new(None));
147 let buffer = ::private::new_parse_buffer(scope, cursor, unexpected);
148 peek(&buffer)
149}
150
David Tolnay776f8e02018-08-24 22:32:10 -0400151macro_rules! impl_token {
David Tolnay4fb71232018-08-25 23:14:50 -0400152 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400153 #[cfg(feature = "parsing")]
154 impl Token for $name {
David Tolnay00f81fd2018-09-01 10:50:12 -0700155 fn peek(cursor: Cursor) -> bool {
David Tolnay65557f02018-09-01 11:08:27 -0700156 fn peek(input: ParseStream) -> bool {
157 <$name as Parse>::parse(input).is_ok()
158 }
159 peek_impl(cursor, peek)
David Tolnay776f8e02018-08-24 22:32:10 -0400160 }
161
David Tolnay2d032802018-09-01 10:51:59 -0700162 fn display() -> &'static str {
163 $display
David Tolnay776f8e02018-08-24 22:32:10 -0400164 }
165 }
166
167 #[cfg(feature = "parsing")]
168 impl private::Sealed for $name {}
169 };
170}
171
David Tolnay4fb71232018-08-25 23:14:50 -0400172impl_token!(Ident "identifier");
David Tolnaya465b2d2018-08-27 08:21:09 -0700173#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400174impl_token!(Lifetime "lifetime");
David Tolnaya465b2d2018-08-27 08:21:09 -0700175#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400176impl_token!(Lit "literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700177#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400178impl_token!(LitStr "string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700179#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400180impl_token!(LitByteStr "byte string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700181#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400182impl_token!(LitByte "byte literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700183#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400184impl_token!(LitChar "character literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700185#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400186impl_token!(LitInt "integer literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700187#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400188impl_token!(LitFloat "floating point literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700189#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400190impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400191
David Tolnay776f8e02018-08-24 22:32:10 -0400192macro_rules! define_keywords {
193 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
194 $(
195 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
196 #[$doc]
197 ///
198 /// Don't try to remember the name of this type -- use the [`Token!`]
199 /// macro instead.
200 ///
201 /// [`Token!`]: index.html
202 pub struct $name {
203 pub span: Span,
204 }
205
206 #[doc(hidden)]
207 #[allow(non_snake_case)]
208 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
209 $name {
210 span: span.into_spans()[0],
211 }
212 }
213
David Tolnay4fb71232018-08-25 23:14:50 -0400214 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400215
216 impl std::default::Default for $name {
217 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700218 $name {
219 span: Span::call_site(),
220 }
David Tolnay776f8e02018-08-24 22:32:10 -0400221 }
222 }
223
224 #[cfg(feature = "extra-traits")]
225 impl Debug for $name {
226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227 f.write_str(stringify!($name))
228 }
229 }
230
231 #[cfg(feature = "extra-traits")]
232 impl cmp::Eq for $name {}
233
234 #[cfg(feature = "extra-traits")]
235 impl PartialEq for $name {
236 fn eq(&self, _other: &$name) -> bool {
237 true
238 }
239 }
240
241 #[cfg(feature = "extra-traits")]
242 impl Hash for $name {
243 fn hash<H: Hasher>(&self, _state: &mut H) {}
244 }
245
246 #[cfg(feature = "printing")]
247 impl ToTokens for $name {
248 fn to_tokens(&self, tokens: &mut TokenStream) {
249 printing::keyword($token, &self.span, tokens);
250 }
251 }
252
253 #[cfg(feature = "parsing")]
254 impl Parse for $name {
255 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700256 Ok($name {
257 span: parsing::keyword(input, $token)?,
258 })
David Tolnay776f8e02018-08-24 22:32:10 -0400259 }
260 }
261 )*
262 };
263}
264
265macro_rules! define_punctuation_structs {
266 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
267 $(
268 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
269 #[$doc]
270 ///
271 /// Don't try to remember the name of this type -- use the [`Token!`]
272 /// macro instead.
273 ///
274 /// [`Token!`]: index.html
275 pub struct $name {
276 pub spans: [Span; $len],
277 }
278
279 #[doc(hidden)]
280 #[allow(non_snake_case)]
281 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
282 $name {
283 spans: spans.into_spans(),
284 }
285 }
286
David Tolnay4fb71232018-08-25 23:14:50 -0400287 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400288
289 impl std::default::Default for $name {
290 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700291 $name {
292 spans: [Span::call_site(); $len],
293 }
David Tolnay776f8e02018-08-24 22:32:10 -0400294 }
295 }
296
297 #[cfg(feature = "extra-traits")]
298 impl Debug for $name {
299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
300 f.write_str(stringify!($name))
301 }
302 }
303
304 #[cfg(feature = "extra-traits")]
305 impl cmp::Eq for $name {}
306
307 #[cfg(feature = "extra-traits")]
308 impl PartialEq for $name {
309 fn eq(&self, _other: &$name) -> bool {
310 true
311 }
312 }
313
314 #[cfg(feature = "extra-traits")]
315 impl Hash for $name {
316 fn hash<H: Hasher>(&self, _state: &mut H) {}
317 }
318 )*
319 };
320}
321
322macro_rules! define_punctuation {
323 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
324 $(
325 define_punctuation_structs! {
326 $token pub struct $name/$len #[$doc]
327 }
328
329 #[cfg(feature = "printing")]
330 impl ToTokens for $name {
331 fn to_tokens(&self, tokens: &mut TokenStream) {
332 printing::punct($token, &self.spans, tokens);
333 }
334 }
335
336 #[cfg(feature = "parsing")]
337 impl Parse for $name {
338 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700339 Ok($name {
340 spans: parsing::punct(input, $token)?,
341 })
David Tolnay776f8e02018-08-24 22:32:10 -0400342 }
343 }
344 )*
345 };
346}
347
348macro_rules! define_delimiters {
349 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
350 $(
351 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
352 #[$doc]
353 pub struct $name {
354 pub span: Span,
355 }
356
357 #[doc(hidden)]
358 #[allow(non_snake_case)]
359 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
360 $name {
361 span: span.into_spans()[0],
362 }
363 }
364
365 impl std::default::Default for $name {
366 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700367 $name {
368 span: Span::call_site(),
369 }
David Tolnay776f8e02018-08-24 22:32:10 -0400370 }
371 }
372
373 #[cfg(feature = "extra-traits")]
374 impl Debug for $name {
375 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
376 f.write_str(stringify!($name))
377 }
378 }
379
380 #[cfg(feature = "extra-traits")]
381 impl cmp::Eq for $name {}
382
383 #[cfg(feature = "extra-traits")]
384 impl PartialEq for $name {
385 fn eq(&self, _other: &$name) -> bool {
386 true
387 }
388 }
389
390 #[cfg(feature = "extra-traits")]
391 impl Hash for $name {
392 fn hash<H: Hasher>(&self, _state: &mut H) {}
393 }
394
395 impl $name {
396 #[cfg(feature = "printing")]
397 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
398 where
399 F: FnOnce(&mut TokenStream),
400 {
401 printing::delim($token, &self.span, tokens, f);
402 }
David Tolnay776f8e02018-08-24 22:32:10 -0400403 }
David Tolnay2d84a082018-08-25 16:31:38 -0400404
405 #[cfg(feature = "parsing")]
406 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400407 )*
408 };
409}
410
411define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400412 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700413}
414
David Tolnay776f8e02018-08-24 22:32:10 -0400415#[cfg(feature = "printing")]
416impl ToTokens for Underscore {
417 fn to_tokens(&self, tokens: &mut TokenStream) {
418 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700419 }
David Tolnay776f8e02018-08-24 22:32:10 -0400420}
421
422#[cfg(feature = "parsing")]
423impl Parse for Underscore {
424 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700425 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400426 if let Some((ident, rest)) = cursor.ident() {
427 if ident == "_" {
428 return Ok((Underscore(ident.span()), rest));
429 }
430 }
431 if let Some((punct, rest)) = cursor.punct() {
432 if punct.as_char() == '_' {
433 return Ok((Underscore(punct.span()), rest));
434 }
435 }
436 Err(cursor.error("expected `_`"))
437 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700438 }
David Tolnay776f8e02018-08-24 22:32:10 -0400439}
440
David Tolnay2d84a082018-08-25 16:31:38 -0400441#[cfg(feature = "parsing")]
442impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700443 fn peek(cursor: Cursor) -> bool {
444 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400445 }
446
David Tolnay2d032802018-09-01 10:51:59 -0700447 fn display() -> &'static str {
448 "parentheses"
David Tolnay2d84a082018-08-25 16:31:38 -0400449 }
450}
451
452#[cfg(feature = "parsing")]
453impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700454 fn peek(cursor: Cursor) -> bool {
455 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400456 }
457
David Tolnay2d032802018-09-01 10:51:59 -0700458 fn display() -> &'static str {
459 "curly braces"
David Tolnay2d84a082018-08-25 16:31:38 -0400460 }
461}
462
463#[cfg(feature = "parsing")]
464impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700465 fn peek(cursor: Cursor) -> bool {
466 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400467 }
468
David Tolnay2d032802018-09-01 10:51:59 -0700469 fn display() -> &'static str {
470 "square brackets"
David Tolnay2d84a082018-08-25 16:31:38 -0400471 }
472}
473
David Tolnaya7d69fc2018-08-26 13:30:24 -0400474#[cfg(feature = "parsing")]
475impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700476 fn peek(cursor: Cursor) -> bool {
477 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400478 }
479
David Tolnay2d032802018-09-01 10:51:59 -0700480 fn display() -> &'static str {
481 "invisible group"
David Tolnaya7d69fc2018-08-26 13:30:24 -0400482 }
483}
484
David Tolnay776f8e02018-08-24 22:32:10 -0400485define_keywords! {
486 "as" pub struct As /// `as`
487 "async" pub struct Async /// `async`
488 "auto" pub struct Auto /// `auto`
489 "box" pub struct Box /// `box`
490 "break" pub struct Break /// `break`
491 "Self" pub struct CapSelf /// `Self`
492 "const" pub struct Const /// `const`
493 "continue" pub struct Continue /// `continue`
494 "crate" pub struct Crate /// `crate`
495 "default" pub struct Default /// `default`
496 "dyn" pub struct Dyn /// `dyn`
497 "else" pub struct Else /// `else`
498 "enum" pub struct Enum /// `enum`
499 "existential" pub struct Existential /// `existential`
500 "extern" pub struct Extern /// `extern`
501 "fn" pub struct Fn /// `fn`
502 "for" pub struct For /// `for`
503 "if" pub struct If /// `if`
504 "impl" pub struct Impl /// `impl`
505 "in" pub struct In /// `in`
506 "let" pub struct Let /// `let`
507 "loop" pub struct Loop /// `loop`
508 "macro" pub struct Macro /// `macro`
509 "match" pub struct Match /// `match`
510 "mod" pub struct Mod /// `mod`
511 "move" pub struct Move /// `move`
512 "mut" pub struct Mut /// `mut`
513 "pub" pub struct Pub /// `pub`
514 "ref" pub struct Ref /// `ref`
515 "return" pub struct Return /// `return`
516 "self" pub struct Self_ /// `self`
517 "static" pub struct Static /// `static`
518 "struct" pub struct Struct /// `struct`
519 "super" pub struct Super /// `super`
520 "trait" pub struct Trait /// `trait`
521 "try" pub struct Try /// `try`
522 "type" pub struct Type /// `type`
523 "union" pub struct Union /// `union`
524 "unsafe" pub struct Unsafe /// `unsafe`
525 "use" pub struct Use /// `use`
526 "where" pub struct Where /// `where`
527 "while" pub struct While /// `while`
528 "yield" pub struct Yield /// `yield`
529}
530
531define_punctuation! {
532 "+" pub struct Add/1 /// `+`
533 "+=" pub struct AddEq/2 /// `+=`
534 "&" pub struct And/1 /// `&`
535 "&&" pub struct AndAnd/2 /// `&&`
536 "&=" pub struct AndEq/2 /// `&=`
537 "@" pub struct At/1 /// `@`
538 "!" pub struct Bang/1 /// `!`
539 "^" pub struct Caret/1 /// `^`
540 "^=" pub struct CaretEq/2 /// `^=`
541 ":" pub struct Colon/1 /// `:`
542 "::" pub struct Colon2/2 /// `::`
543 "," pub struct Comma/1 /// `,`
544 "/" pub struct Div/1 /// `/`
545 "/=" pub struct DivEq/2 /// `/=`
546 "$" pub struct Dollar/1 /// `$`
547 "." pub struct Dot/1 /// `.`
548 ".." pub struct Dot2/2 /// `..`
549 "..." pub struct Dot3/3 /// `...`
550 "..=" pub struct DotDotEq/3 /// `..=`
551 "=" pub struct Eq/1 /// `=`
552 "==" pub struct EqEq/2 /// `==`
553 ">=" pub struct Ge/2 /// `>=`
554 ">" pub struct Gt/1 /// `>`
555 "<=" pub struct Le/2 /// `<=`
556 "<" pub struct Lt/1 /// `<`
557 "*=" pub struct MulEq/2 /// `*=`
558 "!=" pub struct Ne/2 /// `!=`
559 "|" pub struct Or/1 /// `|`
560 "|=" pub struct OrEq/2 /// `|=`
561 "||" pub struct OrOr/2 /// `||`
562 "#" pub struct Pound/1 /// `#`
563 "?" pub struct Question/1 /// `?`
564 "->" pub struct RArrow/2 /// `->`
565 "<-" pub struct LArrow/2 /// `<-`
566 "%" pub struct Rem/1 /// `%`
567 "%=" pub struct RemEq/2 /// `%=`
568 "=>" pub struct FatArrow/2 /// `=>`
569 ";" pub struct Semi/1 /// `;`
570 "<<" pub struct Shl/2 /// `<<`
571 "<<=" pub struct ShlEq/3 /// `<<=`
572 ">>" pub struct Shr/2 /// `>>`
573 ">>=" pub struct ShrEq/3 /// `>>=`
574 "*" pub struct Star/1 /// `*`
575 "-" pub struct Sub/1 /// `-`
576 "-=" pub struct SubEq/2 /// `-=`
577}
578
579define_delimiters! {
580 "{" pub struct Brace /// `{...}`
581 "[" pub struct Bracket /// `[...]`
582 "(" pub struct Paren /// `(...)`
583 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700584}
585
David Tolnayf005f962018-01-06 21:19:41 -0800586/// A type-macro that expands to the name of the Rust type representation of a
587/// given token.
588///
589/// See the [token module] documentation for details and examples.
590///
591/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800592// Unfortunate duplication due to a rustdoc bug.
593// https://github.com/rust-lang/rust/issues/45939
594#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700595#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800596macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400597 (as) => { $crate::token::As };
598 (async) => { $crate::token::Async };
599 (auto) => { $crate::token::Auto };
600 (box) => { $crate::token::Box };
601 (break) => { $crate::token::Break };
602 (Self) => { $crate::token::CapSelf };
603 (const) => { $crate::token::Const };
604 (continue) => { $crate::token::Continue };
605 (crate) => { $crate::token::Crate };
606 (default) => { $crate::token::Default };
607 (dyn) => { $crate::token::Dyn };
608 (else) => { $crate::token::Else };
609 (enum) => { $crate::token::Enum };
610 (existential) => { $crate::token::Existential };
611 (extern) => { $crate::token::Extern };
612 (fn) => { $crate::token::Fn };
613 (for) => { $crate::token::For };
614 (if) => { $crate::token::If };
615 (impl) => { $crate::token::Impl };
616 (in) => { $crate::token::In };
617 (let) => { $crate::token::Let };
618 (loop) => { $crate::token::Loop };
619 (macro) => { $crate::token::Macro };
620 (match) => { $crate::token::Match };
621 (mod) => { $crate::token::Mod };
622 (move) => { $crate::token::Move };
623 (mut) => { $crate::token::Mut };
624 (pub) => { $crate::token::Pub };
625 (ref) => { $crate::token::Ref };
626 (return) => { $crate::token::Return };
627 (self) => { $crate::token::Self_ };
628 (static) => { $crate::token::Static };
629 (struct) => { $crate::token::Struct };
630 (super) => { $crate::token::Super };
631 (trait) => { $crate::token::Trait };
632 (try) => { $crate::token::Try };
633 (type) => { $crate::token::Type };
634 (union) => { $crate::token::Union };
635 (unsafe) => { $crate::token::Unsafe };
636 (use) => { $crate::token::Use };
637 (where) => { $crate::token::Where };
638 (while) => { $crate::token::While };
639 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400640 (+) => { $crate::token::Add };
641 (+=) => { $crate::token::AddEq };
642 (&) => { $crate::token::And };
643 (&&) => { $crate::token::AndAnd };
644 (&=) => { $crate::token::AndEq };
645 (@) => { $crate::token::At };
646 (!) => { $crate::token::Bang };
647 (^) => { $crate::token::Caret };
648 (^=) => { $crate::token::CaretEq };
649 (:) => { $crate::token::Colon };
650 (::) => { $crate::token::Colon2 };
651 (,) => { $crate::token::Comma };
652 (/) => { $crate::token::Div };
653 (/=) => { $crate::token::DivEq };
654 (.) => { $crate::token::Dot };
655 (..) => { $crate::token::Dot2 };
656 (...) => { $crate::token::Dot3 };
657 (..=) => { $crate::token::DotDotEq };
658 (=) => { $crate::token::Eq };
659 (==) => { $crate::token::EqEq };
660 (>=) => { $crate::token::Ge };
661 (>) => { $crate::token::Gt };
662 (<=) => { $crate::token::Le };
663 (<) => { $crate::token::Lt };
664 (*=) => { $crate::token::MulEq };
665 (!=) => { $crate::token::Ne };
666 (|) => { $crate::token::Or };
667 (|=) => { $crate::token::OrEq };
668 (||) => { $crate::token::OrOr };
669 (#) => { $crate::token::Pound };
670 (?) => { $crate::token::Question };
671 (->) => { $crate::token::RArrow };
672 (<-) => { $crate::token::LArrow };
673 (%) => { $crate::token::Rem };
674 (%=) => { $crate::token::RemEq };
675 (=>) => { $crate::token::FatArrow };
676 (;) => { $crate::token::Semi };
677 (<<) => { $crate::token::Shl };
678 (<<=) => { $crate::token::ShlEq };
679 (>>) => { $crate::token::Shr };
680 (>>=) => { $crate::token::ShrEq };
681 (*) => { $crate::token::Star };
682 (-) => { $crate::token::Sub };
683 (-=) => { $crate::token::SubEq };
684 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800685}
686
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700687macro_rules! ident_from_token {
688 ($token:ident) => {
689 impl From<Token![$token]> for Ident {
690 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400691 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700692 }
693 }
694 };
695}
696
697ident_from_token!(self);
698ident_from_token!(Self);
699ident_from_token!(super);
700ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700701ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700702
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700703#[cfg(feature = "parsing")]
704mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700705 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700706
David Tolnayad4b2472018-08-25 08:25:24 -0400707 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400708 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400709 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700710
David Tolnay776f8e02018-08-24 22:32:10 -0400711 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700712 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400713 if let Some((ident, rest)) = cursor.ident() {
714 if ident == token {
715 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700716 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700717 }
David Tolnay776f8e02018-08-24 22:32:10 -0400718 Err(cursor.error(format!("expected `{}`", token)))
719 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700720 }
721
David Tolnay776f8e02018-08-24 22:32:10 -0400722 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnay4398c922018-09-01 11:23:10 -0700723 let mut spans = [input.cursor().span(); 3];
724 punct_helper(input, token, &mut spans)?;
725 Ok(S::from_spans(&spans))
726 }
727
728 fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700729 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400730 let mut cursor = *cursor;
David Tolnay776f8e02018-08-24 22:32:10 -0400731 assert!(token.len() <= spans.len());
732
733 for (i, ch) in token.chars().enumerate() {
734 match cursor.punct() {
735 Some((punct, rest)) => {
736 spans[i] = punct.span();
737 if punct.as_char() != ch {
738 break;
739 } else if i == token.len() - 1 {
David Tolnay4398c922018-09-01 11:23:10 -0700740 return Ok(((), rest));
David Tolnay776f8e02018-08-24 22:32:10 -0400741 } else if punct.spacing() != Spacing::Joint {
742 break;
743 }
744 cursor = rest;
745 }
746 None => break,
747 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400748 }
David Tolnay776f8e02018-08-24 22:32:10 -0400749
750 Err(Error::new(spans[0], format!("expected `{}`", token)))
751 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700752 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700753}
754
755#[cfg(feature = "printing")]
756mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700757 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700758 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700759
Alex Crichtona74a1c82018-05-16 10:20:44 -0700760 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700761 assert_eq!(s.len(), spans.len());
762
763 let mut chars = s.chars();
764 let mut spans = spans.iter();
765 let ch = chars.next_back().unwrap();
766 let span = spans.next_back().unwrap();
767 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700768 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700769 op.set_span(*span);
770 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700771 }
772
Alex Crichtona74a1c82018-05-16 10:20:44 -0700773 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700774 op.set_span(*span);
775 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700776 }
777
Alex Crichtona74a1c82018-05-16 10:20:44 -0700778 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
779 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700780 }
781
Alex Crichtona74a1c82018-05-16 10:20:44 -0700782 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500783 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700784 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700785 {
David Tolnay00ab6982017-12-31 18:15:06 -0500786 let delim = match s {
787 "(" => Delimiter::Parenthesis,
788 "[" => Delimiter::Bracket,
789 "{" => Delimiter::Brace,
790 " " => Delimiter::None,
791 _ => panic!("unknown delimiter: {}", s),
792 };
hcplaa511792018-05-29 07:13:01 +0300793 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500794 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700795 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700796 g.set_span(*span);
797 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700798 }
799}