blob: d8975086e8a1f9aa83dace2da110a10a8f8b0f99 [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 {
218 $name(Span::call_site())
219 }
220 }
221
222 #[cfg(feature = "extra-traits")]
223 impl Debug for $name {
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 f.write_str(stringify!($name))
226 }
227 }
228
229 #[cfg(feature = "extra-traits")]
230 impl cmp::Eq for $name {}
231
232 #[cfg(feature = "extra-traits")]
233 impl PartialEq for $name {
234 fn eq(&self, _other: &$name) -> bool {
235 true
236 }
237 }
238
239 #[cfg(feature = "extra-traits")]
240 impl Hash for $name {
241 fn hash<H: Hasher>(&self, _state: &mut H) {}
242 }
243
244 #[cfg(feature = "printing")]
245 impl ToTokens for $name {
246 fn to_tokens(&self, tokens: &mut TokenStream) {
247 printing::keyword($token, &self.span, tokens);
248 }
249 }
250
251 #[cfg(feature = "parsing")]
252 impl Parse for $name {
253 fn parse(input: ParseStream) -> Result<Self> {
254 parsing::keyword(input, $token).map($name)
255 }
256 }
257 )*
258 };
259}
260
261macro_rules! define_punctuation_structs {
262 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
263 $(
264 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
265 #[$doc]
266 ///
267 /// Don't try to remember the name of this type -- use the [`Token!`]
268 /// macro instead.
269 ///
270 /// [`Token!`]: index.html
271 pub struct $name {
272 pub spans: [Span; $len],
273 }
274
275 #[doc(hidden)]
276 #[allow(non_snake_case)]
277 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
278 $name {
279 spans: spans.into_spans(),
280 }
281 }
282
David Tolnay4fb71232018-08-25 23:14:50 -0400283 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400284
285 impl std::default::Default for $name {
286 fn default() -> Self {
287 $name([Span::call_site(); $len])
288 }
289 }
290
291 #[cfg(feature = "extra-traits")]
292 impl Debug for $name {
293 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
294 f.write_str(stringify!($name))
295 }
296 }
297
298 #[cfg(feature = "extra-traits")]
299 impl cmp::Eq for $name {}
300
301 #[cfg(feature = "extra-traits")]
302 impl PartialEq for $name {
303 fn eq(&self, _other: &$name) -> bool {
304 true
305 }
306 }
307
308 #[cfg(feature = "extra-traits")]
309 impl Hash for $name {
310 fn hash<H: Hasher>(&self, _state: &mut H) {}
311 }
312 )*
313 };
314}
315
316macro_rules! define_punctuation {
317 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
318 $(
319 define_punctuation_structs! {
320 $token pub struct $name/$len #[$doc]
321 }
322
323 #[cfg(feature = "printing")]
324 impl ToTokens for $name {
325 fn to_tokens(&self, tokens: &mut TokenStream) {
326 printing::punct($token, &self.spans, tokens);
327 }
328 }
329
330 #[cfg(feature = "parsing")]
331 impl Parse for $name {
332 fn parse(input: ParseStream) -> Result<Self> {
333 parsing::punct(input, $token).map($name::<[Span; $len]>)
334 }
335 }
336 )*
337 };
338}
339
340macro_rules! define_delimiters {
341 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
342 $(
343 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
344 #[$doc]
345 pub struct $name {
346 pub span: Span,
347 }
348
349 #[doc(hidden)]
350 #[allow(non_snake_case)]
351 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
352 $name {
353 span: span.into_spans()[0],
354 }
355 }
356
357 impl std::default::Default for $name {
358 fn default() -> Self {
359 $name(Span::call_site())
360 }
361 }
362
363 #[cfg(feature = "extra-traits")]
364 impl Debug for $name {
365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
366 f.write_str(stringify!($name))
367 }
368 }
369
370 #[cfg(feature = "extra-traits")]
371 impl cmp::Eq for $name {}
372
373 #[cfg(feature = "extra-traits")]
374 impl PartialEq for $name {
375 fn eq(&self, _other: &$name) -> bool {
376 true
377 }
378 }
379
380 #[cfg(feature = "extra-traits")]
381 impl Hash for $name {
382 fn hash<H: Hasher>(&self, _state: &mut H) {}
383 }
384
385 impl $name {
386 #[cfg(feature = "printing")]
387 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
388 where
389 F: FnOnce(&mut TokenStream),
390 {
391 printing::delim($token, &self.span, tokens, f);
392 }
David Tolnay776f8e02018-08-24 22:32:10 -0400393 }
David Tolnay2d84a082018-08-25 16:31:38 -0400394
395 #[cfg(feature = "parsing")]
396 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400397 )*
398 };
399}
400
401define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400402 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700403}
404
David Tolnay776f8e02018-08-24 22:32:10 -0400405#[cfg(feature = "printing")]
406impl ToTokens for Underscore {
407 fn to_tokens(&self, tokens: &mut TokenStream) {
408 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700409 }
David Tolnay776f8e02018-08-24 22:32:10 -0400410}
411
412#[cfg(feature = "parsing")]
413impl Parse for Underscore {
414 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700415 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400416 if let Some((ident, rest)) = cursor.ident() {
417 if ident == "_" {
418 return Ok((Underscore(ident.span()), rest));
419 }
420 }
421 if let Some((punct, rest)) = cursor.punct() {
422 if punct.as_char() == '_' {
423 return Ok((Underscore(punct.span()), rest));
424 }
425 }
426 Err(cursor.error("expected `_`"))
427 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700428 }
David Tolnay776f8e02018-08-24 22:32:10 -0400429}
430
David Tolnay2d84a082018-08-25 16:31:38 -0400431#[cfg(feature = "parsing")]
432impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700433 fn peek(cursor: Cursor) -> bool {
434 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400435 }
436
David Tolnay2d032802018-09-01 10:51:59 -0700437 fn display() -> &'static str {
438 "parentheses"
David Tolnay2d84a082018-08-25 16:31:38 -0400439 }
440}
441
442#[cfg(feature = "parsing")]
443impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700444 fn peek(cursor: Cursor) -> bool {
445 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400446 }
447
David Tolnay2d032802018-09-01 10:51:59 -0700448 fn display() -> &'static str {
449 "curly braces"
David Tolnay2d84a082018-08-25 16:31:38 -0400450 }
451}
452
453#[cfg(feature = "parsing")]
454impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700455 fn peek(cursor: Cursor) -> bool {
456 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400457 }
458
David Tolnay2d032802018-09-01 10:51:59 -0700459 fn display() -> &'static str {
460 "square brackets"
David Tolnay2d84a082018-08-25 16:31:38 -0400461 }
462}
463
David Tolnaya7d69fc2018-08-26 13:30:24 -0400464#[cfg(feature = "parsing")]
465impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700466 fn peek(cursor: Cursor) -> bool {
467 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400468 }
469
David Tolnay2d032802018-09-01 10:51:59 -0700470 fn display() -> &'static str {
471 "invisible group"
David Tolnaya7d69fc2018-08-26 13:30:24 -0400472 }
473}
474
David Tolnay776f8e02018-08-24 22:32:10 -0400475define_keywords! {
476 "as" pub struct As /// `as`
477 "async" pub struct Async /// `async`
478 "auto" pub struct Auto /// `auto`
479 "box" pub struct Box /// `box`
480 "break" pub struct Break /// `break`
481 "Self" pub struct CapSelf /// `Self`
482 "const" pub struct Const /// `const`
483 "continue" pub struct Continue /// `continue`
484 "crate" pub struct Crate /// `crate`
485 "default" pub struct Default /// `default`
486 "dyn" pub struct Dyn /// `dyn`
487 "else" pub struct Else /// `else`
488 "enum" pub struct Enum /// `enum`
489 "existential" pub struct Existential /// `existential`
490 "extern" pub struct Extern /// `extern`
491 "fn" pub struct Fn /// `fn`
492 "for" pub struct For /// `for`
493 "if" pub struct If /// `if`
494 "impl" pub struct Impl /// `impl`
495 "in" pub struct In /// `in`
496 "let" pub struct Let /// `let`
497 "loop" pub struct Loop /// `loop`
498 "macro" pub struct Macro /// `macro`
499 "match" pub struct Match /// `match`
500 "mod" pub struct Mod /// `mod`
501 "move" pub struct Move /// `move`
502 "mut" pub struct Mut /// `mut`
503 "pub" pub struct Pub /// `pub`
504 "ref" pub struct Ref /// `ref`
505 "return" pub struct Return /// `return`
506 "self" pub struct Self_ /// `self`
507 "static" pub struct Static /// `static`
508 "struct" pub struct Struct /// `struct`
509 "super" pub struct Super /// `super`
510 "trait" pub struct Trait /// `trait`
511 "try" pub struct Try /// `try`
512 "type" pub struct Type /// `type`
513 "union" pub struct Union /// `union`
514 "unsafe" pub struct Unsafe /// `unsafe`
515 "use" pub struct Use /// `use`
516 "where" pub struct Where /// `where`
517 "while" pub struct While /// `while`
518 "yield" pub struct Yield /// `yield`
519}
520
521define_punctuation! {
522 "+" pub struct Add/1 /// `+`
523 "+=" pub struct AddEq/2 /// `+=`
524 "&" pub struct And/1 /// `&`
525 "&&" pub struct AndAnd/2 /// `&&`
526 "&=" pub struct AndEq/2 /// `&=`
527 "@" pub struct At/1 /// `@`
528 "!" pub struct Bang/1 /// `!`
529 "^" pub struct Caret/1 /// `^`
530 "^=" pub struct CaretEq/2 /// `^=`
531 ":" pub struct Colon/1 /// `:`
532 "::" pub struct Colon2/2 /// `::`
533 "," pub struct Comma/1 /// `,`
534 "/" pub struct Div/1 /// `/`
535 "/=" pub struct DivEq/2 /// `/=`
536 "$" pub struct Dollar/1 /// `$`
537 "." pub struct Dot/1 /// `.`
538 ".." pub struct Dot2/2 /// `..`
539 "..." pub struct Dot3/3 /// `...`
540 "..=" pub struct DotDotEq/3 /// `..=`
541 "=" pub struct Eq/1 /// `=`
542 "==" pub struct EqEq/2 /// `==`
543 ">=" pub struct Ge/2 /// `>=`
544 ">" pub struct Gt/1 /// `>`
545 "<=" pub struct Le/2 /// `<=`
546 "<" pub struct Lt/1 /// `<`
547 "*=" pub struct MulEq/2 /// `*=`
548 "!=" pub struct Ne/2 /// `!=`
549 "|" pub struct Or/1 /// `|`
550 "|=" pub struct OrEq/2 /// `|=`
551 "||" pub struct OrOr/2 /// `||`
552 "#" pub struct Pound/1 /// `#`
553 "?" pub struct Question/1 /// `?`
554 "->" pub struct RArrow/2 /// `->`
555 "<-" pub struct LArrow/2 /// `<-`
556 "%" pub struct Rem/1 /// `%`
557 "%=" pub struct RemEq/2 /// `%=`
558 "=>" pub struct FatArrow/2 /// `=>`
559 ";" pub struct Semi/1 /// `;`
560 "<<" pub struct Shl/2 /// `<<`
561 "<<=" pub struct ShlEq/3 /// `<<=`
562 ">>" pub struct Shr/2 /// `>>`
563 ">>=" pub struct ShrEq/3 /// `>>=`
564 "*" pub struct Star/1 /// `*`
565 "-" pub struct Sub/1 /// `-`
566 "-=" pub struct SubEq/2 /// `-=`
567}
568
569define_delimiters! {
570 "{" pub struct Brace /// `{...}`
571 "[" pub struct Bracket /// `[...]`
572 "(" pub struct Paren /// `(...)`
573 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700574}
575
David Tolnayf005f962018-01-06 21:19:41 -0800576/// A type-macro that expands to the name of the Rust type representation of a
577/// given token.
578///
579/// See the [token module] documentation for details and examples.
580///
581/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800582// Unfortunate duplication due to a rustdoc bug.
583// https://github.com/rust-lang/rust/issues/45939
584#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700585#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800586macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400587 (as) => { $crate::token::As };
588 (async) => { $crate::token::Async };
589 (auto) => { $crate::token::Auto };
590 (box) => { $crate::token::Box };
591 (break) => { $crate::token::Break };
592 (Self) => { $crate::token::CapSelf };
593 (const) => { $crate::token::Const };
594 (continue) => { $crate::token::Continue };
595 (crate) => { $crate::token::Crate };
596 (default) => { $crate::token::Default };
597 (dyn) => { $crate::token::Dyn };
598 (else) => { $crate::token::Else };
599 (enum) => { $crate::token::Enum };
600 (existential) => { $crate::token::Existential };
601 (extern) => { $crate::token::Extern };
602 (fn) => { $crate::token::Fn };
603 (for) => { $crate::token::For };
604 (if) => { $crate::token::If };
605 (impl) => { $crate::token::Impl };
606 (in) => { $crate::token::In };
607 (let) => { $crate::token::Let };
608 (loop) => { $crate::token::Loop };
609 (macro) => { $crate::token::Macro };
610 (match) => { $crate::token::Match };
611 (mod) => { $crate::token::Mod };
612 (move) => { $crate::token::Move };
613 (mut) => { $crate::token::Mut };
614 (pub) => { $crate::token::Pub };
615 (ref) => { $crate::token::Ref };
616 (return) => { $crate::token::Return };
617 (self) => { $crate::token::Self_ };
618 (static) => { $crate::token::Static };
619 (struct) => { $crate::token::Struct };
620 (super) => { $crate::token::Super };
621 (trait) => { $crate::token::Trait };
622 (try) => { $crate::token::Try };
623 (type) => { $crate::token::Type };
624 (union) => { $crate::token::Union };
625 (unsafe) => { $crate::token::Unsafe };
626 (use) => { $crate::token::Use };
627 (where) => { $crate::token::Where };
628 (while) => { $crate::token::While };
629 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400630 (+) => { $crate::token::Add };
631 (+=) => { $crate::token::AddEq };
632 (&) => { $crate::token::And };
633 (&&) => { $crate::token::AndAnd };
634 (&=) => { $crate::token::AndEq };
635 (@) => { $crate::token::At };
636 (!) => { $crate::token::Bang };
637 (^) => { $crate::token::Caret };
638 (^=) => { $crate::token::CaretEq };
639 (:) => { $crate::token::Colon };
640 (::) => { $crate::token::Colon2 };
641 (,) => { $crate::token::Comma };
642 (/) => { $crate::token::Div };
643 (/=) => { $crate::token::DivEq };
644 (.) => { $crate::token::Dot };
645 (..) => { $crate::token::Dot2 };
646 (...) => { $crate::token::Dot3 };
647 (..=) => { $crate::token::DotDotEq };
648 (=) => { $crate::token::Eq };
649 (==) => { $crate::token::EqEq };
650 (>=) => { $crate::token::Ge };
651 (>) => { $crate::token::Gt };
652 (<=) => { $crate::token::Le };
653 (<) => { $crate::token::Lt };
654 (*=) => { $crate::token::MulEq };
655 (!=) => { $crate::token::Ne };
656 (|) => { $crate::token::Or };
657 (|=) => { $crate::token::OrEq };
658 (||) => { $crate::token::OrOr };
659 (#) => { $crate::token::Pound };
660 (?) => { $crate::token::Question };
661 (->) => { $crate::token::RArrow };
662 (<-) => { $crate::token::LArrow };
663 (%) => { $crate::token::Rem };
664 (%=) => { $crate::token::RemEq };
665 (=>) => { $crate::token::FatArrow };
666 (;) => { $crate::token::Semi };
667 (<<) => { $crate::token::Shl };
668 (<<=) => { $crate::token::ShlEq };
669 (>>) => { $crate::token::Shr };
670 (>>=) => { $crate::token::ShrEq };
671 (*) => { $crate::token::Star };
672 (-) => { $crate::token::Sub };
673 (-=) => { $crate::token::SubEq };
674 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800675}
676
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700677macro_rules! ident_from_token {
678 ($token:ident) => {
679 impl From<Token![$token]> for Ident {
680 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400681 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700682 }
683 }
684 };
685}
686
687ident_from_token!(self);
688ident_from_token!(Self);
689ident_from_token!(super);
690ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700691ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700692
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700693#[cfg(feature = "parsing")]
694mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700695 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700696
David Tolnayad4b2472018-08-25 08:25:24 -0400697 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400698 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400699 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700700
David Tolnay776f8e02018-08-24 22:32:10 -0400701 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700702 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400703 if let Some((ident, rest)) = cursor.ident() {
704 if ident == token {
705 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700706 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700707 }
David Tolnay776f8e02018-08-24 22:32:10 -0400708 Err(cursor.error(format!("expected `{}`", token)))
709 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700710 }
711
David Tolnay776f8e02018-08-24 22:32:10 -0400712 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700713 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400714 let mut cursor = *cursor;
715 let mut spans = [cursor.span(); 3];
716 assert!(token.len() <= spans.len());
717
718 for (i, ch) in token.chars().enumerate() {
719 match cursor.punct() {
720 Some((punct, rest)) => {
721 spans[i] = punct.span();
722 if punct.as_char() != ch {
723 break;
724 } else if i == token.len() - 1 {
725 return Ok((S::from_spans(&spans), rest));
726 } else if punct.spacing() != Spacing::Joint {
727 break;
728 }
729 cursor = rest;
730 }
731 None => break,
732 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400733 }
David Tolnay776f8e02018-08-24 22:32:10 -0400734
735 Err(Error::new(spans[0], format!("expected `{}`", token)))
736 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700737 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700738}
739
740#[cfg(feature = "printing")]
741mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700742 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700743 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700744
Alex Crichtona74a1c82018-05-16 10:20:44 -0700745 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700746 assert_eq!(s.len(), spans.len());
747
748 let mut chars = s.chars();
749 let mut spans = spans.iter();
750 let ch = chars.next_back().unwrap();
751 let span = spans.next_back().unwrap();
752 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700753 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700754 op.set_span(*span);
755 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700756 }
757
Alex Crichtona74a1c82018-05-16 10:20:44 -0700758 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700759 op.set_span(*span);
760 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700761 }
762
Alex Crichtona74a1c82018-05-16 10:20:44 -0700763 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
764 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700765 }
766
Alex Crichtona74a1c82018-05-16 10:20:44 -0700767 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500768 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700769 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700770 {
David Tolnay00ab6982017-12-31 18:15:06 -0500771 let delim = match s {
772 "(" => Delimiter::Parenthesis,
773 "[" => Delimiter::Bracket,
774 "{" => Delimiter::Brace,
775 " " => Delimiter::None,
776 _ => panic!("unknown delimiter: {}", s),
777 };
hcplaa511792018-05-29 07:13:01 +0300778 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500779 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700780 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700781 g.set_span(*span);
782 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700783 }
784}