blob: f54d02cb2189ff953f9406a9fc0921aa8cf63cd1 [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//! ```
Alex Crichton954046c2017-05-30 21:49:42 -070071
David Tolnay776f8e02018-08-24 22:32:10 -040072use std;
73#[cfg(feature = "extra-traits")]
74use std::cmp;
75#[cfg(feature = "extra-traits")]
76use std::fmt::{self, Debug};
77#[cfg(feature = "extra-traits")]
78use std::hash::{Hash, Hasher};
79
David Tolnay2d84a082018-08-25 16:31:38 -040080#[cfg(feature = "parsing")]
81use proc_macro2::Delimiter;
David Tolnayaf1df8c2018-09-22 13:22:24 -070082#[cfg(any(feature = "parsing", feature = "printing"))]
83use proc_macro2::Ident;
84use proc_macro2::Span;
David Tolnay776f8e02018-08-24 22:32:10 -040085#[cfg(feature = "printing")]
David Tolnayabbf8192018-09-22 13:24:46 -070086use proc_macro2::TokenStream;
87#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -040088use quote::{ToTokens, TokenStreamExt};
89
90#[cfg(feature = "parsing")]
David Tolnay00f81fd2018-09-01 10:50:12 -070091use buffer::Cursor;
92#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -040093use error::Result;
David Tolnaya465b2d2018-08-27 08:21:09 -070094#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayad4b2472018-08-25 08:25:24 -040095#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -040096use lifetime::Lifetime;
David Tolnaya465b2d2018-08-27 08:21:09 -070097#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -040098#[cfg(feature = "parsing")]
David Tolnaya7d69fc2018-08-26 13:30:24 -040099use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr};
David Tolnay4fb71232018-08-25 23:14:50 -0400100#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400101use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400102#[cfg(feature = "parsing")]
David Tolnay7fb11e72018-09-06 01:02:27 -0700103use parse::{Parse, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400104use span::IntoSpans;
105
106/// Marker trait for types that represent single tokens.
107///
108/// This trait is sealed and cannot be implemented for types outside of Syn.
109#[cfg(feature = "parsing")]
110pub trait Token: private::Sealed {
111 // Not public API.
112 #[doc(hidden)]
David Tolnay00f81fd2018-09-01 10:50:12 -0700113 fn peek(cursor: Cursor) -> bool;
David Tolnay776f8e02018-08-24 22:32:10 -0400114
115 // Not public API.
116 #[doc(hidden)]
David Tolnay2d032802018-09-01 10:51:59 -0700117 fn display() -> &'static str;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700118}
119
120#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400121mod private {
122 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700123}
124
David Tolnay65557f02018-09-01 11:08:27 -0700125#[cfg(feature = "parsing")]
David Tolnay719ad5a2018-09-02 18:01:15 -0700126impl private::Sealed for Ident {}
127
David Tolnayff18ed92018-10-26 02:25:05 -0700128#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay719ad5a2018-09-02 18:01:15 -0700129#[cfg(feature = "parsing")]
David Tolnay65557f02018-09-01 11:08:27 -0700130fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool {
David Tolnayff18ed92018-10-26 02:25:05 -0700131 use std::cell::Cell;
132 use std::rc::Rc;
133
David Tolnay65557f02018-09-01 11:08:27 -0700134 let scope = Span::call_site();
135 let unexpected = Rc::new(Cell::new(None));
136 let buffer = ::private::new_parse_buffer(scope, cursor, unexpected);
137 peek(&buffer)
138}
139
David Tolnayaf1df8c2018-09-22 13:22:24 -0700140#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay776f8e02018-08-24 22:32:10 -0400141macro_rules! impl_token {
David Tolnay4fb71232018-08-25 23:14:50 -0400142 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400143 #[cfg(feature = "parsing")]
144 impl Token for $name {
David Tolnay00f81fd2018-09-01 10:50:12 -0700145 fn peek(cursor: Cursor) -> bool {
David Tolnay65557f02018-09-01 11:08:27 -0700146 fn peek(input: ParseStream) -> bool {
147 <$name as Parse>::parse(input).is_ok()
148 }
149 peek_impl(cursor, peek)
David Tolnay776f8e02018-08-24 22:32:10 -0400150 }
151
David Tolnay2d032802018-09-01 10:51:59 -0700152 fn display() -> &'static str {
153 $display
David Tolnay776f8e02018-08-24 22:32:10 -0400154 }
155 }
156
157 #[cfg(feature = "parsing")]
158 impl private::Sealed for $name {}
159 };
160}
161
David Tolnaya465b2d2018-08-27 08:21:09 -0700162#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400163impl_token!(Lifetime "lifetime");
David Tolnaya465b2d2018-08-27 08:21:09 -0700164#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400165impl_token!(Lit "literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700166#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400167impl_token!(LitStr "string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700168#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400169impl_token!(LitByteStr "byte string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700170#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400171impl_token!(LitByte "byte literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700172#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400173impl_token!(LitChar "character literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700174#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400175impl_token!(LitInt "integer literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700176#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400177impl_token!(LitFloat "floating point literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700178#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400179impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400180
David Tolnay7fb11e72018-09-06 01:02:27 -0700181// Not public API.
182#[cfg(feature = "parsing")]
183#[doc(hidden)]
184pub trait CustomKeyword {
185 fn ident() -> &'static str;
186 fn display() -> &'static str;
187}
188
189#[cfg(feature = "parsing")]
190impl<K: CustomKeyword> private::Sealed for K {}
191
192#[cfg(feature = "parsing")]
193impl<K: CustomKeyword> Token for K {
194 fn peek(cursor: Cursor) -> bool {
195 parsing::peek_keyword(cursor, K::ident())
196 }
197
198 fn display() -> &'static str {
199 K::display()
200 }
201}
202
David Tolnay776f8e02018-08-24 22:32:10 -0400203macro_rules! define_keywords {
204 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
205 $(
206 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
207 #[$doc]
208 ///
209 /// Don't try to remember the name of this type -- use the [`Token!`]
210 /// macro instead.
211 ///
212 /// [`Token!`]: index.html
213 pub struct $name {
214 pub span: Span,
215 }
216
217 #[doc(hidden)]
218 #[allow(non_snake_case)]
219 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
220 $name {
221 span: span.into_spans()[0],
222 }
223 }
224
David Tolnay776f8e02018-08-24 22:32:10 -0400225 impl std::default::Default for $name {
226 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700227 $name {
228 span: Span::call_site(),
229 }
David Tolnay776f8e02018-08-24 22:32:10 -0400230 }
231 }
232
233 #[cfg(feature = "extra-traits")]
234 impl Debug for $name {
235 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
236 f.write_str(stringify!($name))
237 }
238 }
239
240 #[cfg(feature = "extra-traits")]
241 impl cmp::Eq for $name {}
242
243 #[cfg(feature = "extra-traits")]
244 impl PartialEq for $name {
245 fn eq(&self, _other: &$name) -> bool {
246 true
247 }
248 }
249
250 #[cfg(feature = "extra-traits")]
251 impl Hash for $name {
252 fn hash<H: Hasher>(&self, _state: &mut H) {}
253 }
254
255 #[cfg(feature = "printing")]
256 impl ToTokens for $name {
257 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800258 printing::keyword($token, self.span, tokens);
David Tolnay776f8e02018-08-24 22:32:10 -0400259 }
260 }
261
262 #[cfg(feature = "parsing")]
263 impl Parse for $name {
264 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700265 Ok($name {
266 span: parsing::keyword(input, $token)?,
267 })
David Tolnay776f8e02018-08-24 22:32:10 -0400268 }
269 }
David Tolnay68274de2018-09-02 17:15:01 -0700270
271 #[cfg(feature = "parsing")]
272 impl Token for $name {
273 fn peek(cursor: Cursor) -> bool {
274 parsing::peek_keyword(cursor, $token)
275 }
276
277 fn display() -> &'static str {
278 concat!("`", $token, "`")
279 }
280 }
281
282 #[cfg(feature = "parsing")]
283 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400284 )*
285 };
286}
287
288macro_rules! define_punctuation_structs {
289 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
290 $(
291 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
292 #[$doc]
293 ///
294 /// Don't try to remember the name of this type -- use the [`Token!`]
295 /// macro instead.
296 ///
297 /// [`Token!`]: index.html
298 pub struct $name {
299 pub spans: [Span; $len],
300 }
301
302 #[doc(hidden)]
303 #[allow(non_snake_case)]
304 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
305 $name {
306 spans: spans.into_spans(),
307 }
308 }
309
David Tolnay776f8e02018-08-24 22:32:10 -0400310 impl std::default::Default for $name {
311 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700312 $name {
313 spans: [Span::call_site(); $len],
314 }
David Tolnay776f8e02018-08-24 22:32:10 -0400315 }
316 }
317
318 #[cfg(feature = "extra-traits")]
319 impl Debug for $name {
320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
321 f.write_str(stringify!($name))
322 }
323 }
324
325 #[cfg(feature = "extra-traits")]
326 impl cmp::Eq for $name {}
327
328 #[cfg(feature = "extra-traits")]
329 impl PartialEq for $name {
330 fn eq(&self, _other: &$name) -> bool {
331 true
332 }
333 }
334
335 #[cfg(feature = "extra-traits")]
336 impl Hash for $name {
337 fn hash<H: Hasher>(&self, _state: &mut H) {}
338 }
339 )*
340 };
341}
342
343macro_rules! define_punctuation {
344 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
345 $(
346 define_punctuation_structs! {
347 $token pub struct $name/$len #[$doc]
348 }
349
350 #[cfg(feature = "printing")]
351 impl ToTokens for $name {
352 fn to_tokens(&self, tokens: &mut TokenStream) {
353 printing::punct($token, &self.spans, tokens);
354 }
355 }
356
357 #[cfg(feature = "parsing")]
358 impl Parse for $name {
359 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700360 Ok($name {
361 spans: parsing::punct(input, $token)?,
362 })
David Tolnay776f8e02018-08-24 22:32:10 -0400363 }
364 }
David Tolnay68274de2018-09-02 17:15:01 -0700365
366 #[cfg(feature = "parsing")]
367 impl Token for $name {
368 fn peek(cursor: Cursor) -> bool {
369 parsing::peek_punct(cursor, $token)
370 }
371
372 fn display() -> &'static str {
373 concat!("`", $token, "`")
374 }
375 }
376
377 #[cfg(feature = "parsing")]
378 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400379 )*
380 };
381}
382
383macro_rules! define_delimiters {
384 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
385 $(
386 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
387 #[$doc]
388 pub struct $name {
389 pub span: Span,
390 }
391
392 #[doc(hidden)]
393 #[allow(non_snake_case)]
394 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
395 $name {
396 span: span.into_spans()[0],
397 }
398 }
399
400 impl std::default::Default for $name {
401 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700402 $name {
403 span: Span::call_site(),
404 }
David Tolnay776f8e02018-08-24 22:32:10 -0400405 }
406 }
407
408 #[cfg(feature = "extra-traits")]
409 impl Debug for $name {
410 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
411 f.write_str(stringify!($name))
412 }
413 }
414
415 #[cfg(feature = "extra-traits")]
416 impl cmp::Eq for $name {}
417
418 #[cfg(feature = "extra-traits")]
419 impl PartialEq for $name {
420 fn eq(&self, _other: &$name) -> bool {
421 true
422 }
423 }
424
425 #[cfg(feature = "extra-traits")]
426 impl Hash for $name {
427 fn hash<H: Hasher>(&self, _state: &mut H) {}
428 }
429
430 impl $name {
431 #[cfg(feature = "printing")]
432 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
433 where
434 F: FnOnce(&mut TokenStream),
435 {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800436 printing::delim($token, self.span, tokens, f);
David Tolnay776f8e02018-08-24 22:32:10 -0400437 }
David Tolnay776f8e02018-08-24 22:32:10 -0400438 }
David Tolnay2d84a082018-08-25 16:31:38 -0400439
440 #[cfg(feature = "parsing")]
441 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400442 )*
443 };
444}
445
446define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400447 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700448}
449
David Tolnay776f8e02018-08-24 22:32:10 -0400450#[cfg(feature = "printing")]
451impl ToTokens for Underscore {
452 fn to_tokens(&self, tokens: &mut TokenStream) {
453 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700454 }
David Tolnay776f8e02018-08-24 22:32:10 -0400455}
456
457#[cfg(feature = "parsing")]
458impl Parse for Underscore {
459 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700460 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400461 if let Some((ident, rest)) = cursor.ident() {
462 if ident == "_" {
463 return Ok((Underscore(ident.span()), rest));
464 }
465 }
466 if let Some((punct, rest)) = cursor.punct() {
467 if punct.as_char() == '_' {
468 return Ok((Underscore(punct.span()), rest));
469 }
470 }
471 Err(cursor.error("expected `_`"))
472 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700473 }
David Tolnay776f8e02018-08-24 22:32:10 -0400474}
475
David Tolnay2d84a082018-08-25 16:31:38 -0400476#[cfg(feature = "parsing")]
David Tolnay68274de2018-09-02 17:15:01 -0700477impl Token for Underscore {
478 fn peek(cursor: Cursor) -> bool {
479 if let Some((ident, _rest)) = cursor.ident() {
480 return ident == "_";
481 }
482 if let Some((punct, _rest)) = cursor.punct() {
David Tolnay3db288c2018-09-09 22:16:51 -0700483 return punct.as_char() == '_';
David Tolnay68274de2018-09-02 17:15:01 -0700484 }
485 false
486 }
487
488 fn display() -> &'static str {
489 "`_`"
490 }
491}
492
493#[cfg(feature = "parsing")]
494impl private::Sealed for Underscore {}
495
496#[cfg(feature = "parsing")]
David Tolnay2d84a082018-08-25 16:31:38 -0400497impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700498 fn peek(cursor: Cursor) -> bool {
499 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400500 }
501
David Tolnay2d032802018-09-01 10:51:59 -0700502 fn display() -> &'static str {
503 "parentheses"
David Tolnay2d84a082018-08-25 16:31:38 -0400504 }
505}
506
507#[cfg(feature = "parsing")]
508impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700509 fn peek(cursor: Cursor) -> bool {
510 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400511 }
512
David Tolnay2d032802018-09-01 10:51:59 -0700513 fn display() -> &'static str {
514 "curly braces"
David Tolnay2d84a082018-08-25 16:31:38 -0400515 }
516}
517
518#[cfg(feature = "parsing")]
519impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700520 fn peek(cursor: Cursor) -> bool {
521 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400522 }
523
David Tolnay2d032802018-09-01 10:51:59 -0700524 fn display() -> &'static str {
525 "square brackets"
David Tolnay2d84a082018-08-25 16:31:38 -0400526 }
527}
528
David Tolnaya7d69fc2018-08-26 13:30:24 -0400529#[cfg(feature = "parsing")]
530impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700531 fn peek(cursor: Cursor) -> bool {
532 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400533 }
534
David Tolnay2d032802018-09-01 10:51:59 -0700535 fn display() -> &'static str {
536 "invisible group"
David Tolnaya7d69fc2018-08-26 13:30:24 -0400537 }
538}
539
David Tolnay776f8e02018-08-24 22:32:10 -0400540define_keywords! {
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700541 "abstract" pub struct Abstract /// `abstract`
David Tolnay776f8e02018-08-24 22:32:10 -0400542 "as" pub struct As /// `as`
543 "async" pub struct Async /// `async`
544 "auto" pub struct Auto /// `auto`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700545 "become" pub struct Become /// `become`
David Tolnay776f8e02018-08-24 22:32:10 -0400546 "box" pub struct Box /// `box`
547 "break" pub struct Break /// `break`
David Tolnay776f8e02018-08-24 22:32:10 -0400548 "const" pub struct Const /// `const`
549 "continue" pub struct Continue /// `continue`
550 "crate" pub struct Crate /// `crate`
551 "default" pub struct Default /// `default`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700552 "do" pub struct Do /// `do`
David Tolnay776f8e02018-08-24 22:32:10 -0400553 "dyn" pub struct Dyn /// `dyn`
554 "else" pub struct Else /// `else`
555 "enum" pub struct Enum /// `enum`
556 "existential" pub struct Existential /// `existential`
557 "extern" pub struct Extern /// `extern`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700558 "final" pub struct Final /// `final`
David Tolnay776f8e02018-08-24 22:32:10 -0400559 "fn" pub struct Fn /// `fn`
560 "for" pub struct For /// `for`
561 "if" pub struct If /// `if`
562 "impl" pub struct Impl /// `impl`
563 "in" pub struct In /// `in`
564 "let" pub struct Let /// `let`
565 "loop" pub struct Loop /// `loop`
566 "macro" pub struct Macro /// `macro`
567 "match" pub struct Match /// `match`
568 "mod" pub struct Mod /// `mod`
569 "move" pub struct Move /// `move`
570 "mut" pub struct Mut /// `mut`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700571 "override" pub struct Override /// `override`
572 "priv" pub struct Priv /// `priv`
David Tolnay776f8e02018-08-24 22:32:10 -0400573 "pub" pub struct Pub /// `pub`
574 "ref" pub struct Ref /// `ref`
575 "return" pub struct Return /// `return`
David Tolnayc0e742d2018-10-30 02:17:17 -0700576 "Self" pub struct SelfType /// `Self`
csmoef04dcc02018-10-30 16:45:13 +0800577 "self" pub struct SelfValue /// `self`
David Tolnay776f8e02018-08-24 22:32:10 -0400578 "static" pub struct Static /// `static`
579 "struct" pub struct Struct /// `struct`
580 "super" pub struct Super /// `super`
581 "trait" pub struct Trait /// `trait`
582 "try" pub struct Try /// `try`
583 "type" pub struct Type /// `type`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700584 "typeof" pub struct Typeof /// `typeof`
David Tolnay776f8e02018-08-24 22:32:10 -0400585 "union" pub struct Union /// `union`
586 "unsafe" pub struct Unsafe /// `unsafe`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700587 "unsized" pub struct Unsized /// `unsized`
David Tolnay776f8e02018-08-24 22:32:10 -0400588 "use" pub struct Use /// `use`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700589 "virtual" pub struct Virtual /// `virtual`
David Tolnay776f8e02018-08-24 22:32:10 -0400590 "where" pub struct Where /// `where`
591 "while" pub struct While /// `while`
592 "yield" pub struct Yield /// `yield`
593}
594
595define_punctuation! {
596 "+" pub struct Add/1 /// `+`
597 "+=" pub struct AddEq/2 /// `+=`
598 "&" pub struct And/1 /// `&`
599 "&&" pub struct AndAnd/2 /// `&&`
600 "&=" pub struct AndEq/2 /// `&=`
601 "@" pub struct At/1 /// `@`
602 "!" pub struct Bang/1 /// `!`
603 "^" pub struct Caret/1 /// `^`
604 "^=" pub struct CaretEq/2 /// `^=`
605 ":" pub struct Colon/1 /// `:`
606 "::" pub struct Colon2/2 /// `::`
607 "," pub struct Comma/1 /// `,`
608 "/" pub struct Div/1 /// `/`
609 "/=" pub struct DivEq/2 /// `/=`
610 "$" pub struct Dollar/1 /// `$`
611 "." pub struct Dot/1 /// `.`
612 ".." pub struct Dot2/2 /// `..`
613 "..." pub struct Dot3/3 /// `...`
614 "..=" pub struct DotDotEq/3 /// `..=`
615 "=" pub struct Eq/1 /// `=`
616 "==" pub struct EqEq/2 /// `==`
617 ">=" pub struct Ge/2 /// `>=`
618 ">" pub struct Gt/1 /// `>`
619 "<=" pub struct Le/2 /// `<=`
620 "<" pub struct Lt/1 /// `<`
621 "*=" pub struct MulEq/2 /// `*=`
622 "!=" pub struct Ne/2 /// `!=`
623 "|" pub struct Or/1 /// `|`
624 "|=" pub struct OrEq/2 /// `|=`
625 "||" pub struct OrOr/2 /// `||`
626 "#" pub struct Pound/1 /// `#`
627 "?" pub struct Question/1 /// `?`
628 "->" pub struct RArrow/2 /// `->`
629 "<-" pub struct LArrow/2 /// `<-`
630 "%" pub struct Rem/1 /// `%`
631 "%=" pub struct RemEq/2 /// `%=`
632 "=>" pub struct FatArrow/2 /// `=>`
633 ";" pub struct Semi/1 /// `;`
634 "<<" pub struct Shl/2 /// `<<`
635 "<<=" pub struct ShlEq/3 /// `<<=`
636 ">>" pub struct Shr/2 /// `>>`
637 ">>=" pub struct ShrEq/3 /// `>>=`
638 "*" pub struct Star/1 /// `*`
639 "-" pub struct Sub/1 /// `-`
640 "-=" pub struct SubEq/2 /// `-=`
David Tolnayf26be7d2018-09-23 01:32:08 -0700641 "~" pub struct Tilde/1 /// `~`
David Tolnay776f8e02018-08-24 22:32:10 -0400642}
643
644define_delimiters! {
645 "{" pub struct Brace /// `{...}`
646 "[" pub struct Bracket /// `[...]`
647 "(" pub struct Paren /// `(...)`
648 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700649}
650
David Tolnayf005f962018-01-06 21:19:41 -0800651/// A type-macro that expands to the name of the Rust type representation of a
652/// given token.
653///
654/// See the [token module] documentation for details and examples.
655///
656/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800657// Unfortunate duplication due to a rustdoc bug.
658// https://github.com/rust-lang/rust/issues/45939
659#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700660#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800661macro_rules! Token {
David Tolnayc327cd22018-09-09 00:37:28 -0700662 (abstract) => { $crate::token::Abstract };
David Tolnay776f8e02018-08-24 22:32:10 -0400663 (as) => { $crate::token::As };
664 (async) => { $crate::token::Async };
665 (auto) => { $crate::token::Auto };
David Tolnayc327cd22018-09-09 00:37:28 -0700666 (become) => { $crate::token::Become };
David Tolnay776f8e02018-08-24 22:32:10 -0400667 (box) => { $crate::token::Box };
668 (break) => { $crate::token::Break };
David Tolnay776f8e02018-08-24 22:32:10 -0400669 (const) => { $crate::token::Const };
670 (continue) => { $crate::token::Continue };
671 (crate) => { $crate::token::Crate };
672 (default) => { $crate::token::Default };
David Tolnayc327cd22018-09-09 00:37:28 -0700673 (do) => { $crate::token::Do };
David Tolnay776f8e02018-08-24 22:32:10 -0400674 (dyn) => { $crate::token::Dyn };
675 (else) => { $crate::token::Else };
676 (enum) => { $crate::token::Enum };
677 (existential) => { $crate::token::Existential };
678 (extern) => { $crate::token::Extern };
David Tolnayc327cd22018-09-09 00:37:28 -0700679 (final) => { $crate::token::Final };
David Tolnay776f8e02018-08-24 22:32:10 -0400680 (fn) => { $crate::token::Fn };
681 (for) => { $crate::token::For };
682 (if) => { $crate::token::If };
683 (impl) => { $crate::token::Impl };
684 (in) => { $crate::token::In };
685 (let) => { $crate::token::Let };
686 (loop) => { $crate::token::Loop };
687 (macro) => { $crate::token::Macro };
688 (match) => { $crate::token::Match };
689 (mod) => { $crate::token::Mod };
690 (move) => { $crate::token::Move };
691 (mut) => { $crate::token::Mut };
David Tolnayc327cd22018-09-09 00:37:28 -0700692 (override) => { $crate::token::Override };
693 (priv) => { $crate::token::Priv };
David Tolnay776f8e02018-08-24 22:32:10 -0400694 (pub) => { $crate::token::Pub };
695 (ref) => { $crate::token::Ref };
696 (return) => { $crate::token::Return };
David Tolnayc0e742d2018-10-30 02:17:17 -0700697 (Self) => { $crate::token::SelfType };
csmoef04dcc02018-10-30 16:45:13 +0800698 (self) => { $crate::token::SelfValue };
David Tolnay776f8e02018-08-24 22:32:10 -0400699 (static) => { $crate::token::Static };
700 (struct) => { $crate::token::Struct };
701 (super) => { $crate::token::Super };
702 (trait) => { $crate::token::Trait };
703 (try) => { $crate::token::Try };
704 (type) => { $crate::token::Type };
David Tolnayc327cd22018-09-09 00:37:28 -0700705 (typeof) => { $crate::token::Typeof };
David Tolnay776f8e02018-08-24 22:32:10 -0400706 (union) => { $crate::token::Union };
707 (unsafe) => { $crate::token::Unsafe };
David Tolnayc327cd22018-09-09 00:37:28 -0700708 (unsized) => { $crate::token::Unsized };
David Tolnay776f8e02018-08-24 22:32:10 -0400709 (use) => { $crate::token::Use };
David Tolnayc327cd22018-09-09 00:37:28 -0700710 (virtual) => { $crate::token::Virtual };
David Tolnay776f8e02018-08-24 22:32:10 -0400711 (where) => { $crate::token::Where };
712 (while) => { $crate::token::While };
713 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400714 (+) => { $crate::token::Add };
715 (+=) => { $crate::token::AddEq };
716 (&) => { $crate::token::And };
717 (&&) => { $crate::token::AndAnd };
718 (&=) => { $crate::token::AndEq };
719 (@) => { $crate::token::At };
720 (!) => { $crate::token::Bang };
721 (^) => { $crate::token::Caret };
722 (^=) => { $crate::token::CaretEq };
723 (:) => { $crate::token::Colon };
724 (::) => { $crate::token::Colon2 };
725 (,) => { $crate::token::Comma };
726 (/) => { $crate::token::Div };
727 (/=) => { $crate::token::DivEq };
728 (.) => { $crate::token::Dot };
729 (..) => { $crate::token::Dot2 };
730 (...) => { $crate::token::Dot3 };
731 (..=) => { $crate::token::DotDotEq };
732 (=) => { $crate::token::Eq };
733 (==) => { $crate::token::EqEq };
734 (>=) => { $crate::token::Ge };
735 (>) => { $crate::token::Gt };
736 (<=) => { $crate::token::Le };
737 (<) => { $crate::token::Lt };
738 (*=) => { $crate::token::MulEq };
739 (!=) => { $crate::token::Ne };
740 (|) => { $crate::token::Or };
741 (|=) => { $crate::token::OrEq };
742 (||) => { $crate::token::OrOr };
743 (#) => { $crate::token::Pound };
744 (?) => { $crate::token::Question };
745 (->) => { $crate::token::RArrow };
746 (<-) => { $crate::token::LArrow };
747 (%) => { $crate::token::Rem };
748 (%=) => { $crate::token::RemEq };
749 (=>) => { $crate::token::FatArrow };
750 (;) => { $crate::token::Semi };
751 (<<) => { $crate::token::Shl };
752 (<<=) => { $crate::token::ShlEq };
753 (>>) => { $crate::token::Shr };
754 (>>=) => { $crate::token::ShrEq };
755 (*) => { $crate::token::Star };
756 (-) => { $crate::token::Sub };
757 (-=) => { $crate::token::SubEq };
David Tolnayf26be7d2018-09-23 01:32:08 -0700758 (~) => { $crate::token::Tilde };
David Tolnaybb82ef02018-08-24 20:15:45 -0400759 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800760}
761
David Tolnayee612812018-10-30 02:16:03 -0700762// Old names. TODO: remove these re-exports in a breaking change.
763// https://github.com/dtolnay/syn/issues/486
764#[doc(hidden)]
765pub use self::SelfType as CapSelf;
766#[doc(hidden)]
767pub use self::SelfValue as Self_;
768
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700769#[cfg(feature = "parsing")]
770mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700771 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700772
David Tolnay68274de2018-09-02 17:15:01 -0700773 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400774 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400775 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400776 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700777
David Tolnay776f8e02018-08-24 22:32:10 -0400778 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700779 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400780 if let Some((ident, rest)) = cursor.ident() {
781 if ident == token {
782 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700783 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700784 }
David Tolnay776f8e02018-08-24 22:32:10 -0400785 Err(cursor.error(format!("expected `{}`", token)))
786 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700787 }
788
David Tolnay68274de2018-09-02 17:15:01 -0700789 pub fn peek_keyword(cursor: Cursor, token: &str) -> bool {
790 if let Some((ident, _rest)) = cursor.ident() {
791 ident == token
792 } else {
793 false
794 }
795 }
796
David Tolnay776f8e02018-08-24 22:32:10 -0400797 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnay4398c922018-09-01 11:23:10 -0700798 let mut spans = [input.cursor().span(); 3];
799 punct_helper(input, token, &mut spans)?;
800 Ok(S::from_spans(&spans))
801 }
802
803 fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700804 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400805 let mut cursor = *cursor;
David Tolnay776f8e02018-08-24 22:32:10 -0400806 assert!(token.len() <= spans.len());
807
808 for (i, ch) in token.chars().enumerate() {
809 match cursor.punct() {
810 Some((punct, rest)) => {
811 spans[i] = punct.span();
812 if punct.as_char() != ch {
813 break;
814 } else if i == token.len() - 1 {
David Tolnay4398c922018-09-01 11:23:10 -0700815 return Ok(((), rest));
David Tolnay776f8e02018-08-24 22:32:10 -0400816 } else if punct.spacing() != Spacing::Joint {
817 break;
818 }
819 cursor = rest;
820 }
821 None => break,
822 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400823 }
David Tolnay776f8e02018-08-24 22:32:10 -0400824
825 Err(Error::new(spans[0], format!("expected `{}`", token)))
826 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700827 }
David Tolnay68274de2018-09-02 17:15:01 -0700828
829 pub fn peek_punct(mut cursor: Cursor, token: &str) -> bool {
830 for (i, ch) in token.chars().enumerate() {
831 match cursor.punct() {
832 Some((punct, rest)) => {
833 if punct.as_char() != ch {
834 break;
835 } else if i == token.len() - 1 {
836 return true;
837 } else if punct.spacing() != Spacing::Joint {
838 break;
839 }
840 cursor = rest;
841 }
842 None => break,
843 }
844 }
845 false
846 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700847}
848
849#[cfg(feature = "printing")]
850mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700851 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700852 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700853
Alex Crichtona74a1c82018-05-16 10:20:44 -0700854 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700855 assert_eq!(s.len(), spans.len());
856
857 let mut chars = s.chars();
858 let mut spans = spans.iter();
859 let ch = chars.next_back().unwrap();
860 let span = spans.next_back().unwrap();
861 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700862 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700863 op.set_span(*span);
864 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700865 }
866
Alex Crichtona74a1c82018-05-16 10:20:44 -0700867 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700868 op.set_span(*span);
869 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700870 }
871
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800872 pub fn keyword(s: &str, span: Span, tokens: &mut TokenStream) {
873 tokens.append(Ident::new(s, span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700874 }
875
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800876 pub fn delim<F>(s: &str, span: Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500877 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700878 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700879 {
David Tolnay00ab6982017-12-31 18:15:06 -0500880 let delim = match s {
881 "(" => Delimiter::Parenthesis,
882 "[" => Delimiter::Bracket,
883 "{" => Delimiter::Brace,
884 " " => Delimiter::None,
885 _ => panic!("unknown delimiter: {}", s),
886 };
hcplaa511792018-05-29 07:13:01 +0300887 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500888 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700889 let mut g = Group::new(delim, inner);
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800890 g.set_span(span);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700891 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700892 }
893}