blob: f8eb6b855dcce30c607274db9a4c64450fae2892 [file] [log] [blame]
David Tolnaye79ae182018-01-06 19:23:37 -08001//! Tokens representing Rust punctuation, keywords, and delimiters.
Alex Crichton954046c2017-05-30 21:49:42 -07002//!
David Tolnaye79ae182018-01-06 19:23:37 -08003//! The type names in this module can be difficult to keep straight, so we
4//! prefer to use the [`Token!`] macro instead. This is a type-macro that
5//! expands to the token type of the given token.
6//!
7//! [`Token!`]: ../macro.Token.html
8//!
9//! # Example
10//!
11//! The [`ItemStatic`] syntax tree node is defined like this.
12//!
13//! [`ItemStatic`]: ../struct.ItemStatic.html
14//!
David Tolnay95989db2019-01-01 15:05:57 -050015//! ```edition2018
David Tolnayfd5b1172018-12-31 17:54:36 -050016//! # use syn::{Attribute, Expr, Ident, Token, Type, Visibility};
David Tolnaye79ae182018-01-06 19:23:37 -080017//! #
18//! pub struct ItemStatic {
19//! pub attrs: Vec<Attribute>,
20//! pub vis: Visibility,
21//! pub static_token: Token![static],
22//! pub mutability: Option<Token![mut]>,
23//! pub ident: Ident,
24//! pub colon_token: Token![:],
25//! pub ty: Box<Type>,
26//! pub eq_token: Token![=],
27//! pub expr: Box<Expr>,
28//! pub semi_token: Token![;],
29//! }
David Tolnaye79ae182018-01-06 19:23:37 -080030//! ```
31//!
32//! # Parsing
33//!
David Tolnayd8cc0552018-08-31 08:39:17 -070034//! Keywords and punctuation can be parsed through the [`ParseStream::parse`]
35//! method. Delimiter tokens are parsed using the [`parenthesized!`],
36//! [`bracketed!`] and [`braced!`] macros.
David Tolnaye79ae182018-01-06 19:23:37 -080037//!
David Tolnayd8cc0552018-08-31 08:39:17 -070038//! [`ParseStream::parse`]: ../parse/struct.ParseBuffer.html#method.parse
39//! [`parenthesized!`]: ../macro.parenthesized.html
40//! [`bracketed!`]: ../macro.bracketed.html
41//! [`braced!`]: ../macro.braced.html
David Tolnaye79ae182018-01-06 19:23:37 -080042//!
David Tolnay95989db2019-01-01 15:05:57 -050043//! ```edition2018
David Tolnay67fea042018-11-24 14:50:20 -080044//! use syn::{Attribute, Result};
45//! use syn::parse::{Parse, ParseStream};
David Tolnaye79ae182018-01-06 19:23:37 -080046//! #
David Tolnay9b00f652018-09-01 10:31:02 -070047//! # enum ItemStatic {}
David Tolnaye79ae182018-01-06 19:23:37 -080048//!
49//! // Parse the ItemStatic struct shown above.
David Tolnayd8cc0552018-08-31 08:39:17 -070050//! impl Parse for ItemStatic {
51//! fn parse(input: ParseStream) -> Result<Self> {
David Tolnay9b00f652018-09-01 10:31:02 -070052//! # use syn::ItemStatic;
53//! # fn parse(input: ParseStream) -> Result<ItemStatic> {
54//! Ok(ItemStatic {
55//! attrs: input.call(Attribute::parse_outer)?,
56//! vis: input.parse()?,
57//! static_token: input.parse()?,
58//! mutability: input.parse()?,
59//! ident: input.parse()?,
60//! colon_token: input.parse()?,
61//! ty: input.parse()?,
62//! eq_token: input.parse()?,
63//! expr: input.parse()?,
64//! semi_token: input.parse()?,
65//! })
66//! # }
67//! # unimplemented!()
68//! }
David Tolnaye79ae182018-01-06 19:23:37 -080069//! }
David Tolnaye79ae182018-01-06 19:23:37 -080070//! ```
David Tolnay44d0d492019-02-02 08:33:54 -080071//!
72//! # Other operations
73//!
74//! Every keyword and punctuation token supports the following operations.
75//!
76//! - [Peeking] — `input.peek(Token![...])`
77//!
78//! - [Parsing] — `input.parse::<Token![...]>()?`
79//!
80//! - [Printing] — `quote!( ... #the_token ... )`
81//!
82//! - Construction from a [`Span`] — `let the_token = Token![...](sp)`
83//!
84//! - Field access to its span — `let sp = the_token.span`
85//!
86//! [Peeking]: ../parse/struct.ParseBuffer.html#method.peek
87//! [Parsing]: ../parse/struct.ParseBuffer.html#method.parse
88//! [Printing]: https://docs.rs/quote/0.6/quote/trait.ToTokens.html
89//! [`Span`]: ../struct.Span.html
Alex Crichton954046c2017-05-30 21:49:42 -070090
David Tolnay776f8e02018-08-24 22:32:10 -040091use std;
92#[cfg(feature = "extra-traits")]
93use std::cmp;
94#[cfg(feature = "extra-traits")]
95use std::fmt::{self, Debug};
96#[cfg(feature = "extra-traits")]
97use std::hash::{Hash, Hasher};
98
David Tolnay2d84a082018-08-25 16:31:38 -040099#[cfg(feature = "parsing")]
100use proc_macro2::Delimiter;
David Tolnayaf1df8c2018-09-22 13:22:24 -0700101#[cfg(any(feature = "parsing", feature = "printing"))]
102use proc_macro2::Ident;
103use proc_macro2::Span;
David Tolnay776f8e02018-08-24 22:32:10 -0400104#[cfg(feature = "printing")]
David Tolnayabbf8192018-09-22 13:24:46 -0700105use proc_macro2::TokenStream;
106#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400107use quote::{ToTokens, TokenStreamExt};
108
109#[cfg(feature = "parsing")]
David Tolnay00f81fd2018-09-01 10:50:12 -0700110use buffer::Cursor;
111#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400112use error::Result;
David Tolnaya465b2d2018-08-27 08:21:09 -0700113#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayad4b2472018-08-25 08:25:24 -0400114#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400115use lifetime::Lifetime;
David Tolnaya465b2d2018-08-27 08:21:09 -0700116#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400117#[cfg(feature = "parsing")]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400118use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr};
David Tolnay4fb71232018-08-25 23:14:50 -0400119#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400120use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400121#[cfg(feature = "parsing")]
David Tolnay7fb11e72018-09-06 01:02:27 -0700122use parse::{Parse, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400123use span::IntoSpans;
124
125/// Marker trait for types that represent single tokens.
126///
127/// This trait is sealed and cannot be implemented for types outside of Syn.
128#[cfg(feature = "parsing")]
129pub trait Token: private::Sealed {
130 // Not public API.
131 #[doc(hidden)]
David Tolnay00f81fd2018-09-01 10:50:12 -0700132 fn peek(cursor: Cursor) -> bool;
David Tolnay776f8e02018-08-24 22:32:10 -0400133
134 // Not public API.
135 #[doc(hidden)]
David Tolnay2d032802018-09-01 10:51:59 -0700136 fn display() -> &'static str;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700137}
138
139#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400140mod private {
141 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700142}
143
David Tolnay65557f02018-09-01 11:08:27 -0700144#[cfg(feature = "parsing")]
David Tolnay719ad5a2018-09-02 18:01:15 -0700145impl private::Sealed for Ident {}
146
David Tolnayff18ed92018-10-26 02:25:05 -0700147#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay719ad5a2018-09-02 18:01:15 -0700148#[cfg(feature = "parsing")]
David Tolnay65557f02018-09-01 11:08:27 -0700149fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool {
David Tolnayff18ed92018-10-26 02:25:05 -0700150 use std::cell::Cell;
151 use std::rc::Rc;
152
David Tolnay65557f02018-09-01 11:08:27 -0700153 let scope = Span::call_site();
154 let unexpected = Rc::new(Cell::new(None));
155 let buffer = ::private::new_parse_buffer(scope, cursor, unexpected);
156 peek(&buffer)
157}
158
David Tolnayaf1df8c2018-09-22 13:22:24 -0700159#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay776f8e02018-08-24 22:32:10 -0400160macro_rules! impl_token {
David Tolnay4fb71232018-08-25 23:14:50 -0400161 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400162 #[cfg(feature = "parsing")]
163 impl Token for $name {
David Tolnay00f81fd2018-09-01 10:50:12 -0700164 fn peek(cursor: Cursor) -> bool {
David Tolnay65557f02018-09-01 11:08:27 -0700165 fn peek(input: ParseStream) -> bool {
166 <$name as Parse>::parse(input).is_ok()
167 }
168 peek_impl(cursor, peek)
David Tolnay776f8e02018-08-24 22:32:10 -0400169 }
170
David Tolnay2d032802018-09-01 10:51:59 -0700171 fn display() -> &'static str {
172 $display
David Tolnay776f8e02018-08-24 22:32:10 -0400173 }
174 }
175
176 #[cfg(feature = "parsing")]
177 impl private::Sealed for $name {}
178 };
179}
180
David Tolnaya465b2d2018-08-27 08:21:09 -0700181#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400182impl_token!(Lifetime "lifetime");
David Tolnaya465b2d2018-08-27 08:21:09 -0700183#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400184impl_token!(Lit "literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700185#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400186impl_token!(LitStr "string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700187#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400188impl_token!(LitByteStr "byte string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700189#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400190impl_token!(LitByte "byte literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700191#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400192impl_token!(LitChar "character literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700193#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400194impl_token!(LitInt "integer literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700195#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400196impl_token!(LitFloat "floating point literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700197#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400198impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400199
David Tolnay7fb11e72018-09-06 01:02:27 -0700200// Not public API.
201#[cfg(feature = "parsing")]
202#[doc(hidden)]
203pub trait CustomKeyword {
204 fn ident() -> &'static str;
205 fn display() -> &'static str;
206}
207
208#[cfg(feature = "parsing")]
209impl<K: CustomKeyword> private::Sealed for K {}
210
211#[cfg(feature = "parsing")]
212impl<K: CustomKeyword> Token for K {
213 fn peek(cursor: Cursor) -> bool {
214 parsing::peek_keyword(cursor, K::ident())
215 }
216
217 fn display() -> &'static str {
218 K::display()
219 }
220}
221
David Tolnay776f8e02018-08-24 22:32:10 -0400222macro_rules! define_keywords {
223 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
224 $(
225 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
226 #[$doc]
227 ///
228 /// Don't try to remember the name of this type -- use the [`Token!`]
229 /// macro instead.
230 ///
231 /// [`Token!`]: index.html
232 pub struct $name {
233 pub span: Span,
234 }
235
236 #[doc(hidden)]
237 #[allow(non_snake_case)]
238 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
239 $name {
240 span: span.into_spans()[0],
241 }
242 }
243
David Tolnay776f8e02018-08-24 22:32:10 -0400244 impl std::default::Default for $name {
245 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700246 $name {
247 span: Span::call_site(),
248 }
David Tolnay776f8e02018-08-24 22:32:10 -0400249 }
250 }
251
252 #[cfg(feature = "extra-traits")]
253 impl Debug for $name {
254 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255 f.write_str(stringify!($name))
256 }
257 }
258
259 #[cfg(feature = "extra-traits")]
260 impl cmp::Eq for $name {}
261
262 #[cfg(feature = "extra-traits")]
263 impl PartialEq for $name {
264 fn eq(&self, _other: &$name) -> bool {
265 true
266 }
267 }
268
269 #[cfg(feature = "extra-traits")]
270 impl Hash for $name {
271 fn hash<H: Hasher>(&self, _state: &mut H) {}
272 }
273
274 #[cfg(feature = "printing")]
275 impl ToTokens for $name {
276 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800277 printing::keyword($token, self.span, tokens);
David Tolnay776f8e02018-08-24 22:32:10 -0400278 }
279 }
280
281 #[cfg(feature = "parsing")]
282 impl Parse for $name {
283 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700284 Ok($name {
285 span: parsing::keyword(input, $token)?,
286 })
David Tolnay776f8e02018-08-24 22:32:10 -0400287 }
288 }
David Tolnay68274de2018-09-02 17:15:01 -0700289
290 #[cfg(feature = "parsing")]
291 impl Token for $name {
292 fn peek(cursor: Cursor) -> bool {
293 parsing::peek_keyword(cursor, $token)
294 }
295
296 fn display() -> &'static str {
297 concat!("`", $token, "`")
298 }
299 }
300
301 #[cfg(feature = "parsing")]
302 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400303 )*
304 };
305}
306
307macro_rules! define_punctuation_structs {
308 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
309 $(
310 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
311 #[$doc]
312 ///
313 /// Don't try to remember the name of this type -- use the [`Token!`]
314 /// macro instead.
315 ///
316 /// [`Token!`]: index.html
317 pub struct $name {
318 pub spans: [Span; $len],
319 }
320
321 #[doc(hidden)]
322 #[allow(non_snake_case)]
323 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
324 $name {
325 spans: spans.into_spans(),
326 }
327 }
328
David Tolnay776f8e02018-08-24 22:32:10 -0400329 impl std::default::Default for $name {
330 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700331 $name {
332 spans: [Span::call_site(); $len],
333 }
David Tolnay776f8e02018-08-24 22:32:10 -0400334 }
335 }
336
337 #[cfg(feature = "extra-traits")]
338 impl Debug for $name {
339 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
340 f.write_str(stringify!($name))
341 }
342 }
343
344 #[cfg(feature = "extra-traits")]
345 impl cmp::Eq for $name {}
346
347 #[cfg(feature = "extra-traits")]
348 impl PartialEq for $name {
349 fn eq(&self, _other: &$name) -> bool {
350 true
351 }
352 }
353
354 #[cfg(feature = "extra-traits")]
355 impl Hash for $name {
356 fn hash<H: Hasher>(&self, _state: &mut H) {}
357 }
358 )*
359 };
360}
361
362macro_rules! define_punctuation {
363 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
364 $(
365 define_punctuation_structs! {
366 $token pub struct $name/$len #[$doc]
367 }
368
369 #[cfg(feature = "printing")]
370 impl ToTokens for $name {
371 fn to_tokens(&self, tokens: &mut TokenStream) {
372 printing::punct($token, &self.spans, tokens);
373 }
374 }
375
376 #[cfg(feature = "parsing")]
377 impl Parse for $name {
378 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700379 Ok($name {
380 spans: parsing::punct(input, $token)?,
381 })
David Tolnay776f8e02018-08-24 22:32:10 -0400382 }
383 }
David Tolnay68274de2018-09-02 17:15:01 -0700384
385 #[cfg(feature = "parsing")]
386 impl Token for $name {
387 fn peek(cursor: Cursor) -> bool {
388 parsing::peek_punct(cursor, $token)
389 }
390
391 fn display() -> &'static str {
392 concat!("`", $token, "`")
393 }
394 }
395
396 #[cfg(feature = "parsing")]
397 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400398 )*
399 };
400}
401
402macro_rules! define_delimiters {
403 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
404 $(
405 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
406 #[$doc]
407 pub struct $name {
408 pub span: Span,
409 }
410
411 #[doc(hidden)]
412 #[allow(non_snake_case)]
413 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
414 $name {
415 span: span.into_spans()[0],
416 }
417 }
418
419 impl std::default::Default for $name {
420 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700421 $name {
422 span: Span::call_site(),
423 }
David Tolnay776f8e02018-08-24 22:32:10 -0400424 }
425 }
426
427 #[cfg(feature = "extra-traits")]
428 impl Debug for $name {
429 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
430 f.write_str(stringify!($name))
431 }
432 }
433
434 #[cfg(feature = "extra-traits")]
435 impl cmp::Eq for $name {}
436
437 #[cfg(feature = "extra-traits")]
438 impl PartialEq for $name {
439 fn eq(&self, _other: &$name) -> bool {
440 true
441 }
442 }
443
444 #[cfg(feature = "extra-traits")]
445 impl Hash for $name {
446 fn hash<H: Hasher>(&self, _state: &mut H) {}
447 }
448
449 impl $name {
450 #[cfg(feature = "printing")]
451 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
452 where
453 F: FnOnce(&mut TokenStream),
454 {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800455 printing::delim($token, self.span, tokens, f);
David Tolnay776f8e02018-08-24 22:32:10 -0400456 }
David Tolnay776f8e02018-08-24 22:32:10 -0400457 }
David Tolnay2d84a082018-08-25 16:31:38 -0400458
459 #[cfg(feature = "parsing")]
460 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400461 )*
462 };
463}
464
465define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400466 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700467}
468
David Tolnay776f8e02018-08-24 22:32:10 -0400469#[cfg(feature = "printing")]
470impl ToTokens for Underscore {
471 fn to_tokens(&self, tokens: &mut TokenStream) {
472 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700473 }
David Tolnay776f8e02018-08-24 22:32:10 -0400474}
475
476#[cfg(feature = "parsing")]
477impl Parse for Underscore {
478 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700479 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400480 if let Some((ident, rest)) = cursor.ident() {
481 if ident == "_" {
482 return Ok((Underscore(ident.span()), rest));
483 }
484 }
485 if let Some((punct, rest)) = cursor.punct() {
486 if punct.as_char() == '_' {
487 return Ok((Underscore(punct.span()), rest));
488 }
489 }
490 Err(cursor.error("expected `_`"))
491 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700492 }
David Tolnay776f8e02018-08-24 22:32:10 -0400493}
494
David Tolnay2d84a082018-08-25 16:31:38 -0400495#[cfg(feature = "parsing")]
David Tolnay68274de2018-09-02 17:15:01 -0700496impl Token for Underscore {
497 fn peek(cursor: Cursor) -> bool {
498 if let Some((ident, _rest)) = cursor.ident() {
499 return ident == "_";
500 }
501 if let Some((punct, _rest)) = cursor.punct() {
David Tolnay3db288c2018-09-09 22:16:51 -0700502 return punct.as_char() == '_';
David Tolnay68274de2018-09-02 17:15:01 -0700503 }
504 false
505 }
506
507 fn display() -> &'static str {
508 "`_`"
509 }
510}
511
512#[cfg(feature = "parsing")]
513impl private::Sealed for Underscore {}
514
515#[cfg(feature = "parsing")]
David Tolnay2d84a082018-08-25 16:31:38 -0400516impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700517 fn peek(cursor: Cursor) -> bool {
518 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400519 }
520
David Tolnay2d032802018-09-01 10:51:59 -0700521 fn display() -> &'static str {
522 "parentheses"
David Tolnay2d84a082018-08-25 16:31:38 -0400523 }
524}
525
526#[cfg(feature = "parsing")]
527impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700528 fn peek(cursor: Cursor) -> bool {
529 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400530 }
531
David Tolnay2d032802018-09-01 10:51:59 -0700532 fn display() -> &'static str {
533 "curly braces"
David Tolnay2d84a082018-08-25 16:31:38 -0400534 }
535}
536
537#[cfg(feature = "parsing")]
538impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700539 fn peek(cursor: Cursor) -> bool {
540 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400541 }
542
David Tolnay2d032802018-09-01 10:51:59 -0700543 fn display() -> &'static str {
544 "square brackets"
David Tolnay2d84a082018-08-25 16:31:38 -0400545 }
546}
547
David Tolnaya7d69fc2018-08-26 13:30:24 -0400548#[cfg(feature = "parsing")]
549impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700550 fn peek(cursor: Cursor) -> bool {
551 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400552 }
553
David Tolnay2d032802018-09-01 10:51:59 -0700554 fn display() -> &'static str {
555 "invisible group"
David Tolnaya7d69fc2018-08-26 13:30:24 -0400556 }
557}
558
David Tolnay776f8e02018-08-24 22:32:10 -0400559define_keywords! {
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700560 "abstract" pub struct Abstract /// `abstract`
David Tolnay776f8e02018-08-24 22:32:10 -0400561 "as" pub struct As /// `as`
562 "async" pub struct Async /// `async`
563 "auto" pub struct Auto /// `auto`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700564 "become" pub struct Become /// `become`
David Tolnay776f8e02018-08-24 22:32:10 -0400565 "box" pub struct Box /// `box`
566 "break" pub struct Break /// `break`
David Tolnay776f8e02018-08-24 22:32:10 -0400567 "const" pub struct Const /// `const`
568 "continue" pub struct Continue /// `continue`
569 "crate" pub struct Crate /// `crate`
570 "default" pub struct Default /// `default`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700571 "do" pub struct Do /// `do`
David Tolnay776f8e02018-08-24 22:32:10 -0400572 "dyn" pub struct Dyn /// `dyn`
573 "else" pub struct Else /// `else`
574 "enum" pub struct Enum /// `enum`
575 "existential" pub struct Existential /// `existential`
576 "extern" pub struct Extern /// `extern`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700577 "final" pub struct Final /// `final`
David Tolnay776f8e02018-08-24 22:32:10 -0400578 "fn" pub struct Fn /// `fn`
579 "for" pub struct For /// `for`
580 "if" pub struct If /// `if`
581 "impl" pub struct Impl /// `impl`
582 "in" pub struct In /// `in`
583 "let" pub struct Let /// `let`
584 "loop" pub struct Loop /// `loop`
585 "macro" pub struct Macro /// `macro`
586 "match" pub struct Match /// `match`
587 "mod" pub struct Mod /// `mod`
588 "move" pub struct Move /// `move`
589 "mut" pub struct Mut /// `mut`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700590 "override" pub struct Override /// `override`
591 "priv" pub struct Priv /// `priv`
David Tolnay776f8e02018-08-24 22:32:10 -0400592 "pub" pub struct Pub /// `pub`
593 "ref" pub struct Ref /// `ref`
594 "return" pub struct Return /// `return`
David Tolnayc0e742d2018-10-30 02:17:17 -0700595 "Self" pub struct SelfType /// `Self`
csmoef04dcc02018-10-30 16:45:13 +0800596 "self" pub struct SelfValue /// `self`
David Tolnay776f8e02018-08-24 22:32:10 -0400597 "static" pub struct Static /// `static`
598 "struct" pub struct Struct /// `struct`
599 "super" pub struct Super /// `super`
600 "trait" pub struct Trait /// `trait`
601 "try" pub struct Try /// `try`
602 "type" pub struct Type /// `type`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700603 "typeof" pub struct Typeof /// `typeof`
David Tolnay776f8e02018-08-24 22:32:10 -0400604 "union" pub struct Union /// `union`
605 "unsafe" pub struct Unsafe /// `unsafe`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700606 "unsized" pub struct Unsized /// `unsized`
David Tolnay776f8e02018-08-24 22:32:10 -0400607 "use" pub struct Use /// `use`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700608 "virtual" pub struct Virtual /// `virtual`
David Tolnay776f8e02018-08-24 22:32:10 -0400609 "where" pub struct Where /// `where`
610 "while" pub struct While /// `while`
611 "yield" pub struct Yield /// `yield`
612}
613
614define_punctuation! {
615 "+" pub struct Add/1 /// `+`
616 "+=" pub struct AddEq/2 /// `+=`
617 "&" pub struct And/1 /// `&`
618 "&&" pub struct AndAnd/2 /// `&&`
619 "&=" pub struct AndEq/2 /// `&=`
620 "@" pub struct At/1 /// `@`
621 "!" pub struct Bang/1 /// `!`
622 "^" pub struct Caret/1 /// `^`
623 "^=" pub struct CaretEq/2 /// `^=`
624 ":" pub struct Colon/1 /// `:`
625 "::" pub struct Colon2/2 /// `::`
626 "," pub struct Comma/1 /// `,`
627 "/" pub struct Div/1 /// `/`
628 "/=" pub struct DivEq/2 /// `/=`
629 "$" pub struct Dollar/1 /// `$`
630 "." pub struct Dot/1 /// `.`
631 ".." pub struct Dot2/2 /// `..`
632 "..." pub struct Dot3/3 /// `...`
633 "..=" pub struct DotDotEq/3 /// `..=`
634 "=" pub struct Eq/1 /// `=`
635 "==" pub struct EqEq/2 /// `==`
636 ">=" pub struct Ge/2 /// `>=`
637 ">" pub struct Gt/1 /// `>`
638 "<=" pub struct Le/2 /// `<=`
639 "<" pub struct Lt/1 /// `<`
640 "*=" pub struct MulEq/2 /// `*=`
641 "!=" pub struct Ne/2 /// `!=`
642 "|" pub struct Or/1 /// `|`
643 "|=" pub struct OrEq/2 /// `|=`
644 "||" pub struct OrOr/2 /// `||`
645 "#" pub struct Pound/1 /// `#`
646 "?" pub struct Question/1 /// `?`
647 "->" pub struct RArrow/2 /// `->`
648 "<-" pub struct LArrow/2 /// `<-`
649 "%" pub struct Rem/1 /// `%`
650 "%=" pub struct RemEq/2 /// `%=`
651 "=>" pub struct FatArrow/2 /// `=>`
652 ";" pub struct Semi/1 /// `;`
653 "<<" pub struct Shl/2 /// `<<`
654 "<<=" pub struct ShlEq/3 /// `<<=`
655 ">>" pub struct Shr/2 /// `>>`
656 ">>=" pub struct ShrEq/3 /// `>>=`
657 "*" pub struct Star/1 /// `*`
658 "-" pub struct Sub/1 /// `-`
659 "-=" pub struct SubEq/2 /// `-=`
David Tolnayf26be7d2018-09-23 01:32:08 -0700660 "~" pub struct Tilde/1 /// `~`
David Tolnay776f8e02018-08-24 22:32:10 -0400661}
662
663define_delimiters! {
664 "{" pub struct Brace /// `{...}`
665 "[" pub struct Bracket /// `[...]`
666 "(" pub struct Paren /// `(...)`
667 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700668}
669
David Tolnayf005f962018-01-06 21:19:41 -0800670/// A type-macro that expands to the name of the Rust type representation of a
671/// given token.
672///
673/// See the [token module] documentation for details and examples.
674///
675/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800676// Unfortunate duplication due to a rustdoc bug.
677// https://github.com/rust-lang/rust/issues/45939
678#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700679#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800680macro_rules! Token {
David Tolnayc327cd22018-09-09 00:37:28 -0700681 (abstract) => { $crate::token::Abstract };
David Tolnay776f8e02018-08-24 22:32:10 -0400682 (as) => { $crate::token::As };
683 (async) => { $crate::token::Async };
684 (auto) => { $crate::token::Auto };
David Tolnayc327cd22018-09-09 00:37:28 -0700685 (become) => { $crate::token::Become };
David Tolnay776f8e02018-08-24 22:32:10 -0400686 (box) => { $crate::token::Box };
687 (break) => { $crate::token::Break };
David Tolnay776f8e02018-08-24 22:32:10 -0400688 (const) => { $crate::token::Const };
689 (continue) => { $crate::token::Continue };
690 (crate) => { $crate::token::Crate };
691 (default) => { $crate::token::Default };
David Tolnayc327cd22018-09-09 00:37:28 -0700692 (do) => { $crate::token::Do };
David Tolnay776f8e02018-08-24 22:32:10 -0400693 (dyn) => { $crate::token::Dyn };
694 (else) => { $crate::token::Else };
695 (enum) => { $crate::token::Enum };
696 (existential) => { $crate::token::Existential };
697 (extern) => { $crate::token::Extern };
David Tolnayc327cd22018-09-09 00:37:28 -0700698 (final) => { $crate::token::Final };
David Tolnay776f8e02018-08-24 22:32:10 -0400699 (fn) => { $crate::token::Fn };
700 (for) => { $crate::token::For };
701 (if) => { $crate::token::If };
702 (impl) => { $crate::token::Impl };
703 (in) => { $crate::token::In };
704 (let) => { $crate::token::Let };
705 (loop) => { $crate::token::Loop };
706 (macro) => { $crate::token::Macro };
707 (match) => { $crate::token::Match };
708 (mod) => { $crate::token::Mod };
709 (move) => { $crate::token::Move };
710 (mut) => { $crate::token::Mut };
David Tolnayc327cd22018-09-09 00:37:28 -0700711 (override) => { $crate::token::Override };
712 (priv) => { $crate::token::Priv };
David Tolnay776f8e02018-08-24 22:32:10 -0400713 (pub) => { $crate::token::Pub };
714 (ref) => { $crate::token::Ref };
715 (return) => { $crate::token::Return };
David Tolnayc0e742d2018-10-30 02:17:17 -0700716 (Self) => { $crate::token::SelfType };
csmoef04dcc02018-10-30 16:45:13 +0800717 (self) => { $crate::token::SelfValue };
David Tolnay776f8e02018-08-24 22:32:10 -0400718 (static) => { $crate::token::Static };
719 (struct) => { $crate::token::Struct };
720 (super) => { $crate::token::Super };
721 (trait) => { $crate::token::Trait };
722 (try) => { $crate::token::Try };
723 (type) => { $crate::token::Type };
David Tolnayc327cd22018-09-09 00:37:28 -0700724 (typeof) => { $crate::token::Typeof };
David Tolnay776f8e02018-08-24 22:32:10 -0400725 (union) => { $crate::token::Union };
726 (unsafe) => { $crate::token::Unsafe };
David Tolnayc327cd22018-09-09 00:37:28 -0700727 (unsized) => { $crate::token::Unsized };
David Tolnay776f8e02018-08-24 22:32:10 -0400728 (use) => { $crate::token::Use };
David Tolnayc327cd22018-09-09 00:37:28 -0700729 (virtual) => { $crate::token::Virtual };
David Tolnay776f8e02018-08-24 22:32:10 -0400730 (where) => { $crate::token::Where };
731 (while) => { $crate::token::While };
732 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400733 (+) => { $crate::token::Add };
734 (+=) => { $crate::token::AddEq };
735 (&) => { $crate::token::And };
736 (&&) => { $crate::token::AndAnd };
737 (&=) => { $crate::token::AndEq };
738 (@) => { $crate::token::At };
739 (!) => { $crate::token::Bang };
740 (^) => { $crate::token::Caret };
741 (^=) => { $crate::token::CaretEq };
742 (:) => { $crate::token::Colon };
743 (::) => { $crate::token::Colon2 };
744 (,) => { $crate::token::Comma };
745 (/) => { $crate::token::Div };
746 (/=) => { $crate::token::DivEq };
747 (.) => { $crate::token::Dot };
748 (..) => { $crate::token::Dot2 };
749 (...) => { $crate::token::Dot3 };
750 (..=) => { $crate::token::DotDotEq };
751 (=) => { $crate::token::Eq };
752 (==) => { $crate::token::EqEq };
753 (>=) => { $crate::token::Ge };
754 (>) => { $crate::token::Gt };
755 (<=) => { $crate::token::Le };
756 (<) => { $crate::token::Lt };
757 (*=) => { $crate::token::MulEq };
758 (!=) => { $crate::token::Ne };
759 (|) => { $crate::token::Or };
760 (|=) => { $crate::token::OrEq };
761 (||) => { $crate::token::OrOr };
762 (#) => { $crate::token::Pound };
763 (?) => { $crate::token::Question };
764 (->) => { $crate::token::RArrow };
765 (<-) => { $crate::token::LArrow };
766 (%) => { $crate::token::Rem };
767 (%=) => { $crate::token::RemEq };
768 (=>) => { $crate::token::FatArrow };
769 (;) => { $crate::token::Semi };
770 (<<) => { $crate::token::Shl };
771 (<<=) => { $crate::token::ShlEq };
772 (>>) => { $crate::token::Shr };
773 (>>=) => { $crate::token::ShrEq };
774 (*) => { $crate::token::Star };
775 (-) => { $crate::token::Sub };
776 (-=) => { $crate::token::SubEq };
David Tolnayf26be7d2018-09-23 01:32:08 -0700777 (~) => { $crate::token::Tilde };
David Tolnaybb82ef02018-08-24 20:15:45 -0400778 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800779}
780
David Tolnayee612812018-10-30 02:16:03 -0700781// Old names. TODO: remove these re-exports in a breaking change.
782// https://github.com/dtolnay/syn/issues/486
783#[doc(hidden)]
784pub use self::SelfType as CapSelf;
785#[doc(hidden)]
786pub use self::SelfValue as Self_;
787
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700788#[cfg(feature = "parsing")]
789mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700790 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700791
David Tolnay68274de2018-09-02 17:15:01 -0700792 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400793 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400794 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400795 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700796
David Tolnay776f8e02018-08-24 22:32:10 -0400797 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700798 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400799 if let Some((ident, rest)) = cursor.ident() {
800 if ident == token {
801 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700802 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700803 }
David Tolnay776f8e02018-08-24 22:32:10 -0400804 Err(cursor.error(format!("expected `{}`", token)))
805 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700806 }
807
David Tolnay68274de2018-09-02 17:15:01 -0700808 pub fn peek_keyword(cursor: Cursor, token: &str) -> bool {
809 if let Some((ident, _rest)) = cursor.ident() {
810 ident == token
811 } else {
812 false
813 }
814 }
815
David Tolnay776f8e02018-08-24 22:32:10 -0400816 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnay4398c922018-09-01 11:23:10 -0700817 let mut spans = [input.cursor().span(); 3];
818 punct_helper(input, token, &mut spans)?;
819 Ok(S::from_spans(&spans))
820 }
821
822 fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700823 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400824 let mut cursor = *cursor;
David Tolnay776f8e02018-08-24 22:32:10 -0400825 assert!(token.len() <= spans.len());
826
827 for (i, ch) in token.chars().enumerate() {
828 match cursor.punct() {
829 Some((punct, rest)) => {
830 spans[i] = punct.span();
831 if punct.as_char() != ch {
832 break;
833 } else if i == token.len() - 1 {
David Tolnay4398c922018-09-01 11:23:10 -0700834 return Ok(((), rest));
David Tolnay776f8e02018-08-24 22:32:10 -0400835 } else if punct.spacing() != Spacing::Joint {
836 break;
837 }
838 cursor = rest;
839 }
840 None => break,
841 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400842 }
David Tolnay776f8e02018-08-24 22:32:10 -0400843
844 Err(Error::new(spans[0], format!("expected `{}`", token)))
845 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700846 }
David Tolnay68274de2018-09-02 17:15:01 -0700847
848 pub fn peek_punct(mut cursor: Cursor, token: &str) -> bool {
849 for (i, ch) in token.chars().enumerate() {
850 match cursor.punct() {
851 Some((punct, rest)) => {
852 if punct.as_char() != ch {
853 break;
854 } else if i == token.len() - 1 {
855 return true;
856 } else if punct.spacing() != Spacing::Joint {
857 break;
858 }
859 cursor = rest;
860 }
861 None => break,
862 }
863 }
864 false
865 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700866}
867
868#[cfg(feature = "printing")]
869mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700870 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700871 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700872
Alex Crichtona74a1c82018-05-16 10:20:44 -0700873 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700874 assert_eq!(s.len(), spans.len());
875
876 let mut chars = s.chars();
877 let mut spans = spans.iter();
878 let ch = chars.next_back().unwrap();
879 let span = spans.next_back().unwrap();
880 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700881 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700882 op.set_span(*span);
883 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700884 }
885
Alex Crichtona74a1c82018-05-16 10:20:44 -0700886 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700887 op.set_span(*span);
888 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700889 }
890
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800891 pub fn keyword(s: &str, span: Span, tokens: &mut TokenStream) {
892 tokens.append(Ident::new(s, span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700893 }
894
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800895 pub fn delim<F>(s: &str, span: Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500896 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700897 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700898 {
David Tolnay00ab6982017-12-31 18:15:06 -0500899 let delim = match s {
900 "(" => Delimiter::Parenthesis,
901 "[" => Delimiter::Bracket,
902 "{" => Delimiter::Brace,
903 " " => Delimiter::None,
904 _ => panic!("unknown delimiter: {}", s),
905 };
hcplaa511792018-05-29 07:13:01 +0300906 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500907 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700908 let mut g = Group::new(delim, inner);
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800909 g.set_span(span);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700910 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700911 }
912}