blob: 6409c5106f74975c0e7009d3072e4488d25d1f58 [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//!
15//! ```
David Tolnaya1c98072018-09-06 08:58:10 -070016//! # #[macro_use]
David Tolnaye79ae182018-01-06 19:23:37 -080017//! # extern crate syn;
18//! #
David Tolnaya1c98072018-09-06 08:58:10 -070019//! # use syn::{Attribute, Expr, Ident, Type, Visibility};
David Tolnaye79ae182018-01-06 19:23:37 -080020//! #
21//! pub struct ItemStatic {
22//! pub attrs: Vec<Attribute>,
23//! pub vis: Visibility,
24//! pub static_token: Token![static],
25//! pub mutability: Option<Token![mut]>,
26//! pub ident: Ident,
27//! pub colon_token: Token![:],
28//! pub ty: Box<Type>,
29//! pub eq_token: Token![=],
30//! pub expr: Box<Expr>,
31//! pub semi_token: Token![;],
32//! }
33//! #
34//! # fn main() {}
35//! ```
36//!
37//! # Parsing
38//!
David Tolnayd8cc0552018-08-31 08:39:17 -070039//! Keywords and punctuation can be parsed through the [`ParseStream::parse`]
40//! method. Delimiter tokens are parsed using the [`parenthesized!`],
41//! [`bracketed!`] and [`braced!`] macros.
David Tolnaye79ae182018-01-06 19:23:37 -080042//!
David Tolnayd8cc0552018-08-31 08:39:17 -070043//! [`ParseStream::parse`]: ../parse/struct.ParseBuffer.html#method.parse
44//! [`parenthesized!`]: ../macro.parenthesized.html
45//! [`bracketed!`]: ../macro.bracketed.html
46//! [`braced!`]: ../macro.braced.html
David Tolnaye79ae182018-01-06 19:23:37 -080047//!
48//! ```
David Tolnay9b00f652018-09-01 10:31:02 -070049//! # extern crate syn;
50//! #
David Tolnay67fea042018-11-24 14:50:20 -080051//! use syn::{Attribute, Result};
52//! use syn::parse::{Parse, ParseStream};
David Tolnaye79ae182018-01-06 19:23:37 -080053//! #
David Tolnay9b00f652018-09-01 10:31:02 -070054//! # enum ItemStatic {}
David Tolnaye79ae182018-01-06 19:23:37 -080055//!
56//! // Parse the ItemStatic struct shown above.
David Tolnayd8cc0552018-08-31 08:39:17 -070057//! impl Parse for ItemStatic {
58//! fn parse(input: ParseStream) -> Result<Self> {
David Tolnay9b00f652018-09-01 10:31:02 -070059//! # use syn::ItemStatic;
60//! # fn parse(input: ParseStream) -> Result<ItemStatic> {
61//! Ok(ItemStatic {
62//! attrs: input.call(Attribute::parse_outer)?,
63//! vis: input.parse()?,
64//! static_token: input.parse()?,
65//! mutability: input.parse()?,
66//! ident: input.parse()?,
67//! colon_token: input.parse()?,
68//! ty: input.parse()?,
69//! eq_token: input.parse()?,
70//! expr: input.parse()?,
71//! semi_token: input.parse()?,
72//! })
73//! # }
74//! # unimplemented!()
75//! }
David Tolnaye79ae182018-01-06 19:23:37 -080076//! }
77//! #
78//! # fn main() {}
79//! ```
Alex Crichton954046c2017-05-30 21:49:42 -070080
David Tolnay776f8e02018-08-24 22:32:10 -040081use std;
82#[cfg(feature = "extra-traits")]
83use std::cmp;
84#[cfg(feature = "extra-traits")]
85use std::fmt::{self, Debug};
86#[cfg(feature = "extra-traits")]
87use std::hash::{Hash, Hasher};
88
David Tolnay2d84a082018-08-25 16:31:38 -040089#[cfg(feature = "parsing")]
90use proc_macro2::Delimiter;
David Tolnayaf1df8c2018-09-22 13:22:24 -070091#[cfg(any(feature = "parsing", feature = "printing"))]
92use proc_macro2::Ident;
93use proc_macro2::Span;
David Tolnay776f8e02018-08-24 22:32:10 -040094#[cfg(feature = "printing")]
David Tolnayabbf8192018-09-22 13:24:46 -070095use proc_macro2::TokenStream;
96#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -040097use quote::{ToTokens, TokenStreamExt};
98
99#[cfg(feature = "parsing")]
David Tolnay00f81fd2018-09-01 10:50:12 -0700100use buffer::Cursor;
101#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400102use error::Result;
David Tolnaya465b2d2018-08-27 08:21:09 -0700103#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayad4b2472018-08-25 08:25:24 -0400104#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400105use lifetime::Lifetime;
David Tolnaya465b2d2018-08-27 08:21:09 -0700106#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400107#[cfg(feature = "parsing")]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400108use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr};
David Tolnay4fb71232018-08-25 23:14:50 -0400109#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400110use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400111#[cfg(feature = "parsing")]
David Tolnay7fb11e72018-09-06 01:02:27 -0700112use parse::{Parse, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400113use span::IntoSpans;
114
115/// Marker trait for types that represent single tokens.
116///
117/// This trait is sealed and cannot be implemented for types outside of Syn.
118#[cfg(feature = "parsing")]
119pub trait Token: private::Sealed {
120 // Not public API.
121 #[doc(hidden)]
David Tolnay00f81fd2018-09-01 10:50:12 -0700122 fn peek(cursor: Cursor) -> bool;
David Tolnay776f8e02018-08-24 22:32:10 -0400123
124 // Not public API.
125 #[doc(hidden)]
David Tolnay2d032802018-09-01 10:51:59 -0700126 fn display() -> &'static str;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700127}
128
129#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400130mod private {
131 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700132}
133
David Tolnay65557f02018-09-01 11:08:27 -0700134#[cfg(feature = "parsing")]
David Tolnay719ad5a2018-09-02 18:01:15 -0700135impl private::Sealed for Ident {}
136
David Tolnayff18ed92018-10-26 02:25:05 -0700137#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay719ad5a2018-09-02 18:01:15 -0700138#[cfg(feature = "parsing")]
David Tolnay65557f02018-09-01 11:08:27 -0700139fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool {
David Tolnayff18ed92018-10-26 02:25:05 -0700140 use std::cell::Cell;
141 use std::rc::Rc;
142
David Tolnay65557f02018-09-01 11:08:27 -0700143 let scope = Span::call_site();
144 let unexpected = Rc::new(Cell::new(None));
145 let buffer = ::private::new_parse_buffer(scope, cursor, unexpected);
146 peek(&buffer)
147}
148
David Tolnayaf1df8c2018-09-22 13:22:24 -0700149#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay776f8e02018-08-24 22:32:10 -0400150macro_rules! impl_token {
David Tolnay4fb71232018-08-25 23:14:50 -0400151 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400152 #[cfg(feature = "parsing")]
153 impl Token for $name {
David Tolnay00f81fd2018-09-01 10:50:12 -0700154 fn peek(cursor: Cursor) -> bool {
David Tolnay65557f02018-09-01 11:08:27 -0700155 fn peek(input: ParseStream) -> bool {
156 <$name as Parse>::parse(input).is_ok()
157 }
158 peek_impl(cursor, peek)
David Tolnay776f8e02018-08-24 22:32:10 -0400159 }
160
David Tolnay2d032802018-09-01 10:51:59 -0700161 fn display() -> &'static str {
162 $display
David Tolnay776f8e02018-08-24 22:32:10 -0400163 }
164 }
165
166 #[cfg(feature = "parsing")]
167 impl private::Sealed for $name {}
168 };
169}
170
David Tolnaya465b2d2018-08-27 08:21:09 -0700171#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400172impl_token!(Lifetime "lifetime");
David Tolnaya465b2d2018-08-27 08:21:09 -0700173#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400174impl_token!(Lit "literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700175#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400176impl_token!(LitStr "string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700177#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400178impl_token!(LitByteStr "byte 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!(LitByte "byte literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700181#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400182impl_token!(LitChar "character literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700183#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400184impl_token!(LitInt "integer literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700185#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400186impl_token!(LitFloat "floating point literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700187#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400188impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400189
David Tolnay7fb11e72018-09-06 01:02:27 -0700190// Not public API.
191#[cfg(feature = "parsing")]
192#[doc(hidden)]
193pub trait CustomKeyword {
194 fn ident() -> &'static str;
195 fn display() -> &'static str;
196}
197
198#[cfg(feature = "parsing")]
199impl<K: CustomKeyword> private::Sealed for K {}
200
201#[cfg(feature = "parsing")]
202impl<K: CustomKeyword> Token for K {
203 fn peek(cursor: Cursor) -> bool {
204 parsing::peek_keyword(cursor, K::ident())
205 }
206
207 fn display() -> &'static str {
208 K::display()
209 }
210}
211
David Tolnay776f8e02018-08-24 22:32:10 -0400212macro_rules! define_keywords {
213 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
214 $(
215 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
216 #[$doc]
217 ///
218 /// Don't try to remember the name of this type -- use the [`Token!`]
219 /// macro instead.
220 ///
221 /// [`Token!`]: index.html
222 pub struct $name {
223 pub span: Span,
224 }
225
226 #[doc(hidden)]
227 #[allow(non_snake_case)]
228 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
229 $name {
230 span: span.into_spans()[0],
231 }
232 }
233
David Tolnay776f8e02018-08-24 22:32:10 -0400234 impl std::default::Default for $name {
235 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700236 $name {
237 span: Span::call_site(),
238 }
David Tolnay776f8e02018-08-24 22:32:10 -0400239 }
240 }
241
242 #[cfg(feature = "extra-traits")]
243 impl Debug for $name {
244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
245 f.write_str(stringify!($name))
246 }
247 }
248
249 #[cfg(feature = "extra-traits")]
250 impl cmp::Eq for $name {}
251
252 #[cfg(feature = "extra-traits")]
253 impl PartialEq for $name {
254 fn eq(&self, _other: &$name) -> bool {
255 true
256 }
257 }
258
259 #[cfg(feature = "extra-traits")]
260 impl Hash for $name {
261 fn hash<H: Hasher>(&self, _state: &mut H) {}
262 }
263
264 #[cfg(feature = "printing")]
265 impl ToTokens for $name {
266 fn to_tokens(&self, tokens: &mut TokenStream) {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800267 printing::keyword($token, self.span, tokens);
David Tolnay776f8e02018-08-24 22:32:10 -0400268 }
269 }
270
271 #[cfg(feature = "parsing")]
272 impl Parse for $name {
273 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700274 Ok($name {
275 span: parsing::keyword(input, $token)?,
276 })
David Tolnay776f8e02018-08-24 22:32:10 -0400277 }
278 }
David Tolnay68274de2018-09-02 17:15:01 -0700279
280 #[cfg(feature = "parsing")]
281 impl Token for $name {
282 fn peek(cursor: Cursor) -> bool {
283 parsing::peek_keyword(cursor, $token)
284 }
285
286 fn display() -> &'static str {
287 concat!("`", $token, "`")
288 }
289 }
290
291 #[cfg(feature = "parsing")]
292 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400293 )*
294 };
295}
296
297macro_rules! define_punctuation_structs {
298 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
299 $(
300 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
301 #[$doc]
302 ///
303 /// Don't try to remember the name of this type -- use the [`Token!`]
304 /// macro instead.
305 ///
306 /// [`Token!`]: index.html
307 pub struct $name {
308 pub spans: [Span; $len],
309 }
310
311 #[doc(hidden)]
312 #[allow(non_snake_case)]
313 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
314 $name {
315 spans: spans.into_spans(),
316 }
317 }
318
David Tolnay776f8e02018-08-24 22:32:10 -0400319 impl std::default::Default for $name {
320 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700321 $name {
322 spans: [Span::call_site(); $len],
323 }
David Tolnay776f8e02018-08-24 22:32:10 -0400324 }
325 }
326
327 #[cfg(feature = "extra-traits")]
328 impl Debug for $name {
329 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330 f.write_str(stringify!($name))
331 }
332 }
333
334 #[cfg(feature = "extra-traits")]
335 impl cmp::Eq for $name {}
336
337 #[cfg(feature = "extra-traits")]
338 impl PartialEq for $name {
339 fn eq(&self, _other: &$name) -> bool {
340 true
341 }
342 }
343
344 #[cfg(feature = "extra-traits")]
345 impl Hash for $name {
346 fn hash<H: Hasher>(&self, _state: &mut H) {}
347 }
348 )*
349 };
350}
351
352macro_rules! define_punctuation {
353 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
354 $(
355 define_punctuation_structs! {
356 $token pub struct $name/$len #[$doc]
357 }
358
359 #[cfg(feature = "printing")]
360 impl ToTokens for $name {
361 fn to_tokens(&self, tokens: &mut TokenStream) {
362 printing::punct($token, &self.spans, tokens);
363 }
364 }
365
366 #[cfg(feature = "parsing")]
367 impl Parse for $name {
368 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700369 Ok($name {
370 spans: parsing::punct(input, $token)?,
371 })
David Tolnay776f8e02018-08-24 22:32:10 -0400372 }
373 }
David Tolnay68274de2018-09-02 17:15:01 -0700374
375 #[cfg(feature = "parsing")]
376 impl Token for $name {
377 fn peek(cursor: Cursor) -> bool {
378 parsing::peek_punct(cursor, $token)
379 }
380
381 fn display() -> &'static str {
382 concat!("`", $token, "`")
383 }
384 }
385
386 #[cfg(feature = "parsing")]
387 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400388 )*
389 };
390}
391
392macro_rules! define_delimiters {
393 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
394 $(
395 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
396 #[$doc]
397 pub struct $name {
398 pub span: Span,
399 }
400
401 #[doc(hidden)]
402 #[allow(non_snake_case)]
403 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
404 $name {
405 span: span.into_spans()[0],
406 }
407 }
408
409 impl std::default::Default for $name {
410 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700411 $name {
412 span: Span::call_site(),
413 }
David Tolnay776f8e02018-08-24 22:32:10 -0400414 }
415 }
416
417 #[cfg(feature = "extra-traits")]
418 impl Debug for $name {
419 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
420 f.write_str(stringify!($name))
421 }
422 }
423
424 #[cfg(feature = "extra-traits")]
425 impl cmp::Eq for $name {}
426
427 #[cfg(feature = "extra-traits")]
428 impl PartialEq for $name {
429 fn eq(&self, _other: &$name) -> bool {
430 true
431 }
432 }
433
434 #[cfg(feature = "extra-traits")]
435 impl Hash for $name {
436 fn hash<H: Hasher>(&self, _state: &mut H) {}
437 }
438
439 impl $name {
440 #[cfg(feature = "printing")]
441 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
442 where
443 F: FnOnce(&mut TokenStream),
444 {
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800445 printing::delim($token, self.span, tokens, f);
David Tolnay776f8e02018-08-24 22:32:10 -0400446 }
David Tolnay776f8e02018-08-24 22:32:10 -0400447 }
David Tolnay2d84a082018-08-25 16:31:38 -0400448
449 #[cfg(feature = "parsing")]
450 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400451 )*
452 };
453}
454
455define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400456 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700457}
458
David Tolnay776f8e02018-08-24 22:32:10 -0400459#[cfg(feature = "printing")]
460impl ToTokens for Underscore {
461 fn to_tokens(&self, tokens: &mut TokenStream) {
462 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700463 }
David Tolnay776f8e02018-08-24 22:32:10 -0400464}
465
466#[cfg(feature = "parsing")]
467impl Parse for Underscore {
468 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700469 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400470 if let Some((ident, rest)) = cursor.ident() {
471 if ident == "_" {
472 return Ok((Underscore(ident.span()), rest));
473 }
474 }
475 if let Some((punct, rest)) = cursor.punct() {
476 if punct.as_char() == '_' {
477 return Ok((Underscore(punct.span()), rest));
478 }
479 }
480 Err(cursor.error("expected `_`"))
481 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700482 }
David Tolnay776f8e02018-08-24 22:32:10 -0400483}
484
David Tolnay2d84a082018-08-25 16:31:38 -0400485#[cfg(feature = "parsing")]
David Tolnay68274de2018-09-02 17:15:01 -0700486impl Token for Underscore {
487 fn peek(cursor: Cursor) -> bool {
488 if let Some((ident, _rest)) = cursor.ident() {
489 return ident == "_";
490 }
491 if let Some((punct, _rest)) = cursor.punct() {
David Tolnay3db288c2018-09-09 22:16:51 -0700492 return punct.as_char() == '_';
David Tolnay68274de2018-09-02 17:15:01 -0700493 }
494 false
495 }
496
497 fn display() -> &'static str {
498 "`_`"
499 }
500}
501
502#[cfg(feature = "parsing")]
503impl private::Sealed for Underscore {}
504
505#[cfg(feature = "parsing")]
David Tolnay2d84a082018-08-25 16:31:38 -0400506impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700507 fn peek(cursor: Cursor) -> bool {
508 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400509 }
510
David Tolnay2d032802018-09-01 10:51:59 -0700511 fn display() -> &'static str {
512 "parentheses"
David Tolnay2d84a082018-08-25 16:31:38 -0400513 }
514}
515
516#[cfg(feature = "parsing")]
517impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700518 fn peek(cursor: Cursor) -> bool {
519 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400520 }
521
David Tolnay2d032802018-09-01 10:51:59 -0700522 fn display() -> &'static str {
523 "curly braces"
David Tolnay2d84a082018-08-25 16:31:38 -0400524 }
525}
526
527#[cfg(feature = "parsing")]
528impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700529 fn peek(cursor: Cursor) -> bool {
530 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400531 }
532
David Tolnay2d032802018-09-01 10:51:59 -0700533 fn display() -> &'static str {
534 "square brackets"
David Tolnay2d84a082018-08-25 16:31:38 -0400535 }
536}
537
David Tolnaya7d69fc2018-08-26 13:30:24 -0400538#[cfg(feature = "parsing")]
539impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700540 fn peek(cursor: Cursor) -> bool {
541 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400542 }
543
David Tolnay2d032802018-09-01 10:51:59 -0700544 fn display() -> &'static str {
545 "invisible group"
David Tolnaya7d69fc2018-08-26 13:30:24 -0400546 }
547}
548
David Tolnay776f8e02018-08-24 22:32:10 -0400549define_keywords! {
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700550 "abstract" pub struct Abstract /// `abstract`
David Tolnay776f8e02018-08-24 22:32:10 -0400551 "as" pub struct As /// `as`
552 "async" pub struct Async /// `async`
553 "auto" pub struct Auto /// `auto`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700554 "become" pub struct Become /// `become`
David Tolnay776f8e02018-08-24 22:32:10 -0400555 "box" pub struct Box /// `box`
556 "break" pub struct Break /// `break`
David Tolnay776f8e02018-08-24 22:32:10 -0400557 "const" pub struct Const /// `const`
558 "continue" pub struct Continue /// `continue`
559 "crate" pub struct Crate /// `crate`
560 "default" pub struct Default /// `default`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700561 "do" pub struct Do /// `do`
David Tolnay776f8e02018-08-24 22:32:10 -0400562 "dyn" pub struct Dyn /// `dyn`
563 "else" pub struct Else /// `else`
564 "enum" pub struct Enum /// `enum`
565 "existential" pub struct Existential /// `existential`
566 "extern" pub struct Extern /// `extern`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700567 "final" pub struct Final /// `final`
David Tolnay776f8e02018-08-24 22:32:10 -0400568 "fn" pub struct Fn /// `fn`
569 "for" pub struct For /// `for`
570 "if" pub struct If /// `if`
571 "impl" pub struct Impl /// `impl`
572 "in" pub struct In /// `in`
573 "let" pub struct Let /// `let`
574 "loop" pub struct Loop /// `loop`
575 "macro" pub struct Macro /// `macro`
576 "match" pub struct Match /// `match`
577 "mod" pub struct Mod /// `mod`
578 "move" pub struct Move /// `move`
579 "mut" pub struct Mut /// `mut`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700580 "override" pub struct Override /// `override`
581 "priv" pub struct Priv /// `priv`
David Tolnay776f8e02018-08-24 22:32:10 -0400582 "pub" pub struct Pub /// `pub`
583 "ref" pub struct Ref /// `ref`
584 "return" pub struct Return /// `return`
David Tolnayc0e742d2018-10-30 02:17:17 -0700585 "Self" pub struct SelfType /// `Self`
csmoef04dcc02018-10-30 16:45:13 +0800586 "self" pub struct SelfValue /// `self`
David Tolnay776f8e02018-08-24 22:32:10 -0400587 "static" pub struct Static /// `static`
588 "struct" pub struct Struct /// `struct`
589 "super" pub struct Super /// `super`
590 "trait" pub struct Trait /// `trait`
591 "try" pub struct Try /// `try`
592 "type" pub struct Type /// `type`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700593 "typeof" pub struct Typeof /// `typeof`
David Tolnay776f8e02018-08-24 22:32:10 -0400594 "union" pub struct Union /// `union`
595 "unsafe" pub struct Unsafe /// `unsafe`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700596 "unsized" pub struct Unsized /// `unsized`
David Tolnay776f8e02018-08-24 22:32:10 -0400597 "use" pub struct Use /// `use`
David Tolnayb1cbf7e2018-09-09 00:00:17 -0700598 "virtual" pub struct Virtual /// `virtual`
David Tolnay776f8e02018-08-24 22:32:10 -0400599 "where" pub struct Where /// `where`
600 "while" pub struct While /// `while`
601 "yield" pub struct Yield /// `yield`
602}
603
604define_punctuation! {
605 "+" pub struct Add/1 /// `+`
606 "+=" pub struct AddEq/2 /// `+=`
607 "&" pub struct And/1 /// `&`
608 "&&" pub struct AndAnd/2 /// `&&`
609 "&=" pub struct AndEq/2 /// `&=`
610 "@" pub struct At/1 /// `@`
611 "!" pub struct Bang/1 /// `!`
612 "^" pub struct Caret/1 /// `^`
613 "^=" pub struct CaretEq/2 /// `^=`
614 ":" pub struct Colon/1 /// `:`
615 "::" pub struct Colon2/2 /// `::`
616 "," pub struct Comma/1 /// `,`
617 "/" pub struct Div/1 /// `/`
618 "/=" pub struct DivEq/2 /// `/=`
619 "$" pub struct Dollar/1 /// `$`
620 "." pub struct Dot/1 /// `.`
621 ".." pub struct Dot2/2 /// `..`
622 "..." pub struct Dot3/3 /// `...`
623 "..=" pub struct DotDotEq/3 /// `..=`
624 "=" pub struct Eq/1 /// `=`
625 "==" pub struct EqEq/2 /// `==`
626 ">=" pub struct Ge/2 /// `>=`
627 ">" pub struct Gt/1 /// `>`
628 "<=" pub struct Le/2 /// `<=`
629 "<" pub struct Lt/1 /// `<`
630 "*=" pub struct MulEq/2 /// `*=`
631 "!=" pub struct Ne/2 /// `!=`
632 "|" pub struct Or/1 /// `|`
633 "|=" pub struct OrEq/2 /// `|=`
634 "||" pub struct OrOr/2 /// `||`
635 "#" pub struct Pound/1 /// `#`
636 "?" pub struct Question/1 /// `?`
637 "->" pub struct RArrow/2 /// `->`
638 "<-" pub struct LArrow/2 /// `<-`
639 "%" pub struct Rem/1 /// `%`
640 "%=" pub struct RemEq/2 /// `%=`
641 "=>" pub struct FatArrow/2 /// `=>`
642 ";" pub struct Semi/1 /// `;`
643 "<<" pub struct Shl/2 /// `<<`
644 "<<=" pub struct ShlEq/3 /// `<<=`
645 ">>" pub struct Shr/2 /// `>>`
646 ">>=" pub struct ShrEq/3 /// `>>=`
647 "*" pub struct Star/1 /// `*`
648 "-" pub struct Sub/1 /// `-`
649 "-=" pub struct SubEq/2 /// `-=`
David Tolnayf26be7d2018-09-23 01:32:08 -0700650 "~" pub struct Tilde/1 /// `~`
David Tolnay776f8e02018-08-24 22:32:10 -0400651}
652
653define_delimiters! {
654 "{" pub struct Brace /// `{...}`
655 "[" pub struct Bracket /// `[...]`
656 "(" pub struct Paren /// `(...)`
657 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700658}
659
David Tolnayf005f962018-01-06 21:19:41 -0800660/// A type-macro that expands to the name of the Rust type representation of a
661/// given token.
662///
663/// See the [token module] documentation for details and examples.
664///
665/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800666// Unfortunate duplication due to a rustdoc bug.
667// https://github.com/rust-lang/rust/issues/45939
668#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700669#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800670macro_rules! Token {
David Tolnayc327cd22018-09-09 00:37:28 -0700671 (abstract) => { $crate::token::Abstract };
David Tolnay776f8e02018-08-24 22:32:10 -0400672 (as) => { $crate::token::As };
673 (async) => { $crate::token::Async };
674 (auto) => { $crate::token::Auto };
David Tolnayc327cd22018-09-09 00:37:28 -0700675 (become) => { $crate::token::Become };
David Tolnay776f8e02018-08-24 22:32:10 -0400676 (box) => { $crate::token::Box };
677 (break) => { $crate::token::Break };
David Tolnay776f8e02018-08-24 22:32:10 -0400678 (const) => { $crate::token::Const };
679 (continue) => { $crate::token::Continue };
680 (crate) => { $crate::token::Crate };
681 (default) => { $crate::token::Default };
David Tolnayc327cd22018-09-09 00:37:28 -0700682 (do) => { $crate::token::Do };
David Tolnay776f8e02018-08-24 22:32:10 -0400683 (dyn) => { $crate::token::Dyn };
684 (else) => { $crate::token::Else };
685 (enum) => { $crate::token::Enum };
686 (existential) => { $crate::token::Existential };
687 (extern) => { $crate::token::Extern };
David Tolnayc327cd22018-09-09 00:37:28 -0700688 (final) => { $crate::token::Final };
David Tolnay776f8e02018-08-24 22:32:10 -0400689 (fn) => { $crate::token::Fn };
690 (for) => { $crate::token::For };
691 (if) => { $crate::token::If };
692 (impl) => { $crate::token::Impl };
693 (in) => { $crate::token::In };
694 (let) => { $crate::token::Let };
695 (loop) => { $crate::token::Loop };
696 (macro) => { $crate::token::Macro };
697 (match) => { $crate::token::Match };
698 (mod) => { $crate::token::Mod };
699 (move) => { $crate::token::Move };
700 (mut) => { $crate::token::Mut };
David Tolnayc327cd22018-09-09 00:37:28 -0700701 (override) => { $crate::token::Override };
702 (priv) => { $crate::token::Priv };
David Tolnay776f8e02018-08-24 22:32:10 -0400703 (pub) => { $crate::token::Pub };
704 (ref) => { $crate::token::Ref };
705 (return) => { $crate::token::Return };
David Tolnayc0e742d2018-10-30 02:17:17 -0700706 (Self) => { $crate::token::SelfType };
csmoef04dcc02018-10-30 16:45:13 +0800707 (self) => { $crate::token::SelfValue };
David Tolnay776f8e02018-08-24 22:32:10 -0400708 (static) => { $crate::token::Static };
709 (struct) => { $crate::token::Struct };
710 (super) => { $crate::token::Super };
711 (trait) => { $crate::token::Trait };
712 (try) => { $crate::token::Try };
713 (type) => { $crate::token::Type };
David Tolnayc327cd22018-09-09 00:37:28 -0700714 (typeof) => { $crate::token::Typeof };
David Tolnay776f8e02018-08-24 22:32:10 -0400715 (union) => { $crate::token::Union };
716 (unsafe) => { $crate::token::Unsafe };
David Tolnayc327cd22018-09-09 00:37:28 -0700717 (unsized) => { $crate::token::Unsized };
David Tolnay776f8e02018-08-24 22:32:10 -0400718 (use) => { $crate::token::Use };
David Tolnayc327cd22018-09-09 00:37:28 -0700719 (virtual) => { $crate::token::Virtual };
David Tolnay776f8e02018-08-24 22:32:10 -0400720 (where) => { $crate::token::Where };
721 (while) => { $crate::token::While };
722 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400723 (+) => { $crate::token::Add };
724 (+=) => { $crate::token::AddEq };
725 (&) => { $crate::token::And };
726 (&&) => { $crate::token::AndAnd };
727 (&=) => { $crate::token::AndEq };
728 (@) => { $crate::token::At };
729 (!) => { $crate::token::Bang };
730 (^) => { $crate::token::Caret };
731 (^=) => { $crate::token::CaretEq };
732 (:) => { $crate::token::Colon };
733 (::) => { $crate::token::Colon2 };
734 (,) => { $crate::token::Comma };
735 (/) => { $crate::token::Div };
736 (/=) => { $crate::token::DivEq };
737 (.) => { $crate::token::Dot };
738 (..) => { $crate::token::Dot2 };
739 (...) => { $crate::token::Dot3 };
740 (..=) => { $crate::token::DotDotEq };
741 (=) => { $crate::token::Eq };
742 (==) => { $crate::token::EqEq };
743 (>=) => { $crate::token::Ge };
744 (>) => { $crate::token::Gt };
745 (<=) => { $crate::token::Le };
746 (<) => { $crate::token::Lt };
747 (*=) => { $crate::token::MulEq };
748 (!=) => { $crate::token::Ne };
749 (|) => { $crate::token::Or };
750 (|=) => { $crate::token::OrEq };
751 (||) => { $crate::token::OrOr };
752 (#) => { $crate::token::Pound };
753 (?) => { $crate::token::Question };
754 (->) => { $crate::token::RArrow };
755 (<-) => { $crate::token::LArrow };
756 (%) => { $crate::token::Rem };
757 (%=) => { $crate::token::RemEq };
758 (=>) => { $crate::token::FatArrow };
759 (;) => { $crate::token::Semi };
760 (<<) => { $crate::token::Shl };
761 (<<=) => { $crate::token::ShlEq };
762 (>>) => { $crate::token::Shr };
763 (>>=) => { $crate::token::ShrEq };
764 (*) => { $crate::token::Star };
765 (-) => { $crate::token::Sub };
766 (-=) => { $crate::token::SubEq };
David Tolnayf26be7d2018-09-23 01:32:08 -0700767 (~) => { $crate::token::Tilde };
David Tolnaybb82ef02018-08-24 20:15:45 -0400768 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800769}
770
David Tolnayee612812018-10-30 02:16:03 -0700771// Old names. TODO: remove these re-exports in a breaking change.
772// https://github.com/dtolnay/syn/issues/486
773#[doc(hidden)]
774pub use self::SelfType as CapSelf;
775#[doc(hidden)]
776pub use self::SelfValue as Self_;
777
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700778#[cfg(feature = "parsing")]
779mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700780 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700781
David Tolnay68274de2018-09-02 17:15:01 -0700782 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400783 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400784 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400785 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700786
David Tolnay776f8e02018-08-24 22:32:10 -0400787 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700788 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400789 if let Some((ident, rest)) = cursor.ident() {
790 if ident == token {
791 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700792 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700793 }
David Tolnay776f8e02018-08-24 22:32:10 -0400794 Err(cursor.error(format!("expected `{}`", token)))
795 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700796 }
797
David Tolnay68274de2018-09-02 17:15:01 -0700798 pub fn peek_keyword(cursor: Cursor, token: &str) -> bool {
799 if let Some((ident, _rest)) = cursor.ident() {
800 ident == token
801 } else {
802 false
803 }
804 }
805
David Tolnay776f8e02018-08-24 22:32:10 -0400806 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnay4398c922018-09-01 11:23:10 -0700807 let mut spans = [input.cursor().span(); 3];
808 punct_helper(input, token, &mut spans)?;
809 Ok(S::from_spans(&spans))
810 }
811
812 fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700813 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400814 let mut cursor = *cursor;
David Tolnay776f8e02018-08-24 22:32:10 -0400815 assert!(token.len() <= spans.len());
816
817 for (i, ch) in token.chars().enumerate() {
818 match cursor.punct() {
819 Some((punct, rest)) => {
820 spans[i] = punct.span();
821 if punct.as_char() != ch {
822 break;
823 } else if i == token.len() - 1 {
David Tolnay4398c922018-09-01 11:23:10 -0700824 return Ok(((), rest));
David Tolnay776f8e02018-08-24 22:32:10 -0400825 } else if punct.spacing() != Spacing::Joint {
826 break;
827 }
828 cursor = rest;
829 }
830 None => break,
831 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400832 }
David Tolnay776f8e02018-08-24 22:32:10 -0400833
834 Err(Error::new(spans[0], format!("expected `{}`", token)))
835 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700836 }
David Tolnay68274de2018-09-02 17:15:01 -0700837
838 pub fn peek_punct(mut cursor: Cursor, token: &str) -> bool {
839 for (i, ch) in token.chars().enumerate() {
840 match cursor.punct() {
841 Some((punct, rest)) => {
842 if punct.as_char() != ch {
843 break;
844 } else if i == token.len() - 1 {
845 return true;
846 } else if punct.spacing() != Spacing::Joint {
847 break;
848 }
849 cursor = rest;
850 }
851 None => break,
852 }
853 }
854 false
855 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700856}
857
858#[cfg(feature = "printing")]
859mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700860 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700861 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700862
Alex Crichtona74a1c82018-05-16 10:20:44 -0700863 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700864 assert_eq!(s.len(), spans.len());
865
866 let mut chars = s.chars();
867 let mut spans = spans.iter();
868 let ch = chars.next_back().unwrap();
869 let span = spans.next_back().unwrap();
870 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700871 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700872 op.set_span(*span);
873 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700874 }
875
Alex Crichtona74a1c82018-05-16 10:20:44 -0700876 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700877 op.set_span(*span);
878 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700879 }
880
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800881 pub fn keyword(s: &str, span: Span, tokens: &mut TokenStream) {
882 tokens.append(Ident::new(s, span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700883 }
884
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800885 pub fn delim<F>(s: &str, span: Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500886 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700887 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700888 {
David Tolnay00ab6982017-12-31 18:15:06 -0500889 let delim = match s {
890 "(" => Delimiter::Parenthesis,
891 "[" => Delimiter::Bracket,
892 "{" => Delimiter::Brace,
893 " " => Delimiter::None,
894 _ => panic!("unknown delimiter: {}", s),
895 };
hcplaa511792018-05-29 07:13:01 +0300896 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500897 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700898 let mut g = Group::new(delim, inner);
David Tolnay7f7eb0e2018-11-21 01:03:47 -0800899 g.set_span(span);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700900 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700901 }
902}