blob: 8892c3309118c8851da8e432111237386c913be0 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnaye79ae182018-01-06 19:23:37 -08009//! Tokens representing Rust punctuation, keywords, and delimiters.
Alex Crichton954046c2017-05-30 21:49:42 -070010//!
David Tolnaye79ae182018-01-06 19:23:37 -080011//! The type names in this module can be difficult to keep straight, so we
12//! prefer to use the [`Token!`] macro instead. This is a type-macro that
13//! expands to the token type of the given token.
14//!
15//! [`Token!`]: ../macro.Token.html
16//!
17//! # Example
18//!
19//! The [`ItemStatic`] syntax tree node is defined like this.
20//!
21//! [`ItemStatic`]: ../struct.ItemStatic.html
22//!
23//! ```
David Tolnaye79ae182018-01-06 19:23:37 -080024//! # extern crate syn;
25//! #
David Tolnay9b00f652018-09-01 10:31:02 -070026//! # use syn::{Attribute, Expr, Ident, Token, Type, Visibility};
David Tolnaye79ae182018-01-06 19:23:37 -080027//! #
28//! pub struct ItemStatic {
29//! pub attrs: Vec<Attribute>,
30//! pub vis: Visibility,
31//! pub static_token: Token![static],
32//! pub mutability: Option<Token![mut]>,
33//! pub ident: Ident,
34//! pub colon_token: Token![:],
35//! pub ty: Box<Type>,
36//! pub eq_token: Token![=],
37//! pub expr: Box<Expr>,
38//! pub semi_token: Token![;],
39//! }
40//! #
41//! # fn main() {}
42//! ```
43//!
44//! # Parsing
45//!
David Tolnayd8cc0552018-08-31 08:39:17 -070046//! Keywords and punctuation can be parsed through the [`ParseStream::parse`]
47//! method. Delimiter tokens are parsed using the [`parenthesized!`],
48//! [`bracketed!`] and [`braced!`] macros.
David Tolnaye79ae182018-01-06 19:23:37 -080049//!
David Tolnayd8cc0552018-08-31 08:39:17 -070050//! [`ParseStream::parse`]: ../parse/struct.ParseBuffer.html#method.parse
51//! [`parenthesized!`]: ../macro.parenthesized.html
52//! [`bracketed!`]: ../macro.bracketed.html
53//! [`braced!`]: ../macro.braced.html
David Tolnaye79ae182018-01-06 19:23:37 -080054//!
55//! ```
David Tolnay9b00f652018-09-01 10:31:02 -070056//! # extern crate syn;
57//! #
David Tolnayd8cc0552018-08-31 08:39:17 -070058//! use syn::Attribute;
59//! use syn::parse::{Parse, ParseStream, Result};
David Tolnaye79ae182018-01-06 19:23:37 -080060//! #
David Tolnay9b00f652018-09-01 10:31:02 -070061//! # enum ItemStatic {}
David Tolnaye79ae182018-01-06 19:23:37 -080062//!
63//! // Parse the ItemStatic struct shown above.
David Tolnayd8cc0552018-08-31 08:39:17 -070064//! impl Parse for ItemStatic {
65//! fn parse(input: ParseStream) -> Result<Self> {
David Tolnay9b00f652018-09-01 10:31:02 -070066//! # use syn::ItemStatic;
67//! # fn parse(input: ParseStream) -> Result<ItemStatic> {
68//! Ok(ItemStatic {
69//! attrs: input.call(Attribute::parse_outer)?,
70//! vis: input.parse()?,
71//! static_token: input.parse()?,
72//! mutability: input.parse()?,
73//! ident: input.parse()?,
74//! colon_token: input.parse()?,
75//! ty: input.parse()?,
76//! eq_token: input.parse()?,
77//! expr: input.parse()?,
78//! semi_token: input.parse()?,
79//! })
80//! # }
81//! # unimplemented!()
82//! }
David Tolnaye79ae182018-01-06 19:23:37 -080083//! }
84//! #
85//! # fn main() {}
86//! ```
Alex Crichton954046c2017-05-30 21:49:42 -070087
David Tolnay776f8e02018-08-24 22:32:10 -040088use std;
David Tolnayd9836922018-08-25 18:05:36 -040089#[cfg(feature = "parsing")]
90use std::cell::Cell;
David Tolnay776f8e02018-08-24 22:32:10 -040091#[cfg(feature = "extra-traits")]
92use std::cmp;
93#[cfg(feature = "extra-traits")]
94use std::fmt::{self, Debug};
95#[cfg(feature = "extra-traits")]
96use std::hash::{Hash, Hasher};
David Tolnayd9836922018-08-25 18:05:36 -040097#[cfg(feature = "parsing")]
98use std::rc::Rc;
David Tolnay776f8e02018-08-24 22:32:10 -040099
David Tolnay2d84a082018-08-25 16:31:38 -0400100#[cfg(feature = "parsing")]
101use proc_macro2::Delimiter;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700102#[cfg(feature = "printing")]
David Tolnay78612672018-08-31 08:47:41 -0700103use proc_macro2::TokenStream;
104use proc_macro2::{Ident, Span};
David Tolnay776f8e02018-08-24 22:32:10 -0400105#[cfg(feature = "printing")]
106use quote::{ToTokens, TokenStreamExt};
107
108#[cfg(feature = "parsing")]
David Tolnay00f81fd2018-09-01 10:50:12 -0700109use buffer::Cursor;
110#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400111use error::Result;
David Tolnaya465b2d2018-08-27 08:21:09 -0700112#[cfg(any(feature = "full", feature = "derive"))]
David Tolnayad4b2472018-08-25 08:25:24 -0400113#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400114use lifetime::Lifetime;
David Tolnaya465b2d2018-08-27 08:21:09 -0700115#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400116#[cfg(feature = "parsing")]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400117use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr};
David Tolnay4fb71232018-08-25 23:14:50 -0400118#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400119use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400120#[cfg(feature = "parsing")]
David Tolnay7fb11e72018-09-06 01:02:27 -0700121use parse::{Parse, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400122use span::IntoSpans;
123
124/// Marker trait for types that represent single tokens.
125///
126/// This trait is sealed and cannot be implemented for types outside of Syn.
127#[cfg(feature = "parsing")]
128pub trait Token: private::Sealed {
129 // Not public API.
130 #[doc(hidden)]
David Tolnay00f81fd2018-09-01 10:50:12 -0700131 fn peek(cursor: Cursor) -> bool;
David Tolnay776f8e02018-08-24 22:32:10 -0400132
133 // Not public API.
134 #[doc(hidden)]
David Tolnay2d032802018-09-01 10:51:59 -0700135 fn display() -> &'static str;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700136}
137
138#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400139mod private {
140 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700141}
142
David Tolnay65557f02018-09-01 11:08:27 -0700143#[cfg(feature = "parsing")]
David Tolnay719ad5a2018-09-02 18:01:15 -0700144impl private::Sealed for Ident {}
145
146#[cfg(feature = "parsing")]
David Tolnay65557f02018-09-01 11:08:27 -0700147fn peek_impl(cursor: Cursor, peek: fn(ParseStream) -> bool) -> bool {
148 let scope = Span::call_site();
149 let unexpected = Rc::new(Cell::new(None));
150 let buffer = ::private::new_parse_buffer(scope, cursor, unexpected);
151 peek(&buffer)
152}
153
David Tolnay776f8e02018-08-24 22:32:10 -0400154macro_rules! impl_token {
David Tolnay4fb71232018-08-25 23:14:50 -0400155 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400156 #[cfg(feature = "parsing")]
157 impl Token for $name {
David Tolnay00f81fd2018-09-01 10:50:12 -0700158 fn peek(cursor: Cursor) -> bool {
David Tolnay65557f02018-09-01 11:08:27 -0700159 fn peek(input: ParseStream) -> bool {
160 <$name as Parse>::parse(input).is_ok()
161 }
162 peek_impl(cursor, peek)
David Tolnay776f8e02018-08-24 22:32:10 -0400163 }
164
David Tolnay2d032802018-09-01 10:51:59 -0700165 fn display() -> &'static str {
166 $display
David Tolnay776f8e02018-08-24 22:32:10 -0400167 }
168 }
169
170 #[cfg(feature = "parsing")]
171 impl private::Sealed for $name {}
172 };
173}
174
David Tolnaya465b2d2018-08-27 08:21:09 -0700175#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400176impl_token!(Lifetime "lifetime");
David Tolnaya465b2d2018-08-27 08:21:09 -0700177#[cfg(any(feature = "full", feature = "derive"))]
David Tolnay4fb71232018-08-25 23:14:50 -0400178impl_token!(Lit "literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700179#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400180impl_token!(LitStr "string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700181#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400182impl_token!(LitByteStr "byte string literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700183#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400184impl_token!(LitByte "byte literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700185#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400186impl_token!(LitChar "character literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700187#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400188impl_token!(LitInt "integer literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700189#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400190impl_token!(LitFloat "floating point literal");
David Tolnaya465b2d2018-08-27 08:21:09 -0700191#[cfg(any(feature = "full", feature = "derive"))]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400192impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400193
David Tolnay7fb11e72018-09-06 01:02:27 -0700194// Not public API.
195#[cfg(feature = "parsing")]
196#[doc(hidden)]
197pub trait CustomKeyword {
198 fn ident() -> &'static str;
199 fn display() -> &'static str;
200}
201
202#[cfg(feature = "parsing")]
203impl<K: CustomKeyword> private::Sealed for K {}
204
205#[cfg(feature = "parsing")]
206impl<K: CustomKeyword> Token for K {
207 fn peek(cursor: Cursor) -> bool {
208 parsing::peek_keyword(cursor, K::ident())
209 }
210
211 fn display() -> &'static str {
212 K::display()
213 }
214}
215
David Tolnay776f8e02018-08-24 22:32:10 -0400216macro_rules! define_keywords {
217 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
218 $(
219 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
220 #[$doc]
221 ///
222 /// Don't try to remember the name of this type -- use the [`Token!`]
223 /// macro instead.
224 ///
225 /// [`Token!`]: index.html
226 pub struct $name {
227 pub span: Span,
228 }
229
230 #[doc(hidden)]
231 #[allow(non_snake_case)]
232 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
233 $name {
234 span: span.into_spans()[0],
235 }
236 }
237
David Tolnay776f8e02018-08-24 22:32:10 -0400238 impl std::default::Default for $name {
239 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700240 $name {
241 span: Span::call_site(),
242 }
David Tolnay776f8e02018-08-24 22:32:10 -0400243 }
244 }
245
246 #[cfg(feature = "extra-traits")]
247 impl Debug for $name {
248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
249 f.write_str(stringify!($name))
250 }
251 }
252
253 #[cfg(feature = "extra-traits")]
254 impl cmp::Eq for $name {}
255
256 #[cfg(feature = "extra-traits")]
257 impl PartialEq for $name {
258 fn eq(&self, _other: &$name) -> bool {
259 true
260 }
261 }
262
263 #[cfg(feature = "extra-traits")]
264 impl Hash for $name {
265 fn hash<H: Hasher>(&self, _state: &mut H) {}
266 }
267
268 #[cfg(feature = "printing")]
269 impl ToTokens for $name {
270 fn to_tokens(&self, tokens: &mut TokenStream) {
271 printing::keyword($token, &self.span, tokens);
272 }
273 }
274
275 #[cfg(feature = "parsing")]
276 impl Parse for $name {
277 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700278 Ok($name {
279 span: parsing::keyword(input, $token)?,
280 })
David Tolnay776f8e02018-08-24 22:32:10 -0400281 }
282 }
David Tolnay68274de2018-09-02 17:15:01 -0700283
284 #[cfg(feature = "parsing")]
285 impl Token for $name {
286 fn peek(cursor: Cursor) -> bool {
287 parsing::peek_keyword(cursor, $token)
288 }
289
290 fn display() -> &'static str {
291 concat!("`", $token, "`")
292 }
293 }
294
295 #[cfg(feature = "parsing")]
296 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400297 )*
298 };
299}
300
301macro_rules! define_punctuation_structs {
302 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
303 $(
304 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
305 #[$doc]
306 ///
307 /// Don't try to remember the name of this type -- use the [`Token!`]
308 /// macro instead.
309 ///
310 /// [`Token!`]: index.html
311 pub struct $name {
312 pub spans: [Span; $len],
313 }
314
315 #[doc(hidden)]
316 #[allow(non_snake_case)]
317 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
318 $name {
319 spans: spans.into_spans(),
320 }
321 }
322
David Tolnay776f8e02018-08-24 22:32:10 -0400323 impl std::default::Default for $name {
324 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700325 $name {
326 spans: [Span::call_site(); $len],
327 }
David Tolnay776f8e02018-08-24 22:32:10 -0400328 }
329 }
330
331 #[cfg(feature = "extra-traits")]
332 impl Debug for $name {
333 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
334 f.write_str(stringify!($name))
335 }
336 }
337
338 #[cfg(feature = "extra-traits")]
339 impl cmp::Eq for $name {}
340
341 #[cfg(feature = "extra-traits")]
342 impl PartialEq for $name {
343 fn eq(&self, _other: &$name) -> bool {
344 true
345 }
346 }
347
348 #[cfg(feature = "extra-traits")]
349 impl Hash for $name {
350 fn hash<H: Hasher>(&self, _state: &mut H) {}
351 }
352 )*
353 };
354}
355
356macro_rules! define_punctuation {
357 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
358 $(
359 define_punctuation_structs! {
360 $token pub struct $name/$len #[$doc]
361 }
362
363 #[cfg(feature = "printing")]
364 impl ToTokens for $name {
365 fn to_tokens(&self, tokens: &mut TokenStream) {
366 printing::punct($token, &self.spans, tokens);
367 }
368 }
369
370 #[cfg(feature = "parsing")]
371 impl Parse for $name {
372 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4398c922018-09-01 11:23:10 -0700373 Ok($name {
374 spans: parsing::punct(input, $token)?,
375 })
David Tolnay776f8e02018-08-24 22:32:10 -0400376 }
377 }
David Tolnay68274de2018-09-02 17:15:01 -0700378
379 #[cfg(feature = "parsing")]
380 impl Token for $name {
381 fn peek(cursor: Cursor) -> bool {
382 parsing::peek_punct(cursor, $token)
383 }
384
385 fn display() -> &'static str {
386 concat!("`", $token, "`")
387 }
388 }
389
390 #[cfg(feature = "parsing")]
391 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400392 )*
393 };
394}
395
396macro_rules! define_delimiters {
397 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
398 $(
399 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
400 #[$doc]
401 pub struct $name {
402 pub span: Span,
403 }
404
405 #[doc(hidden)]
406 #[allow(non_snake_case)]
407 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
408 $name {
409 span: span.into_spans()[0],
410 }
411 }
412
413 impl std::default::Default for $name {
414 fn default() -> Self {
David Tolnay4398c922018-09-01 11:23:10 -0700415 $name {
416 span: Span::call_site(),
417 }
David Tolnay776f8e02018-08-24 22:32:10 -0400418 }
419 }
420
421 #[cfg(feature = "extra-traits")]
422 impl Debug for $name {
423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
424 f.write_str(stringify!($name))
425 }
426 }
427
428 #[cfg(feature = "extra-traits")]
429 impl cmp::Eq for $name {}
430
431 #[cfg(feature = "extra-traits")]
432 impl PartialEq for $name {
433 fn eq(&self, _other: &$name) -> bool {
434 true
435 }
436 }
437
438 #[cfg(feature = "extra-traits")]
439 impl Hash for $name {
440 fn hash<H: Hasher>(&self, _state: &mut H) {}
441 }
442
443 impl $name {
444 #[cfg(feature = "printing")]
445 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
446 where
447 F: FnOnce(&mut TokenStream),
448 {
449 printing::delim($token, &self.span, tokens, f);
450 }
David Tolnay776f8e02018-08-24 22:32:10 -0400451 }
David Tolnay2d84a082018-08-25 16:31:38 -0400452
453 #[cfg(feature = "parsing")]
454 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400455 )*
456 };
457}
458
459define_punctuation_structs! {
David Tolnay776f8e02018-08-24 22:32:10 -0400460 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700461}
462
David Tolnay776f8e02018-08-24 22:32:10 -0400463#[cfg(feature = "printing")]
464impl ToTokens for Underscore {
465 fn to_tokens(&self, tokens: &mut TokenStream) {
466 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700467 }
David Tolnay776f8e02018-08-24 22:32:10 -0400468}
469
470#[cfg(feature = "parsing")]
471impl Parse for Underscore {
472 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700473 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400474 if let Some((ident, rest)) = cursor.ident() {
475 if ident == "_" {
476 return Ok((Underscore(ident.span()), rest));
477 }
478 }
479 if let Some((punct, rest)) = cursor.punct() {
480 if punct.as_char() == '_' {
481 return Ok((Underscore(punct.span()), rest));
482 }
483 }
484 Err(cursor.error("expected `_`"))
485 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700486 }
David Tolnay776f8e02018-08-24 22:32:10 -0400487}
488
David Tolnay2d84a082018-08-25 16:31:38 -0400489#[cfg(feature = "parsing")]
David Tolnay68274de2018-09-02 17:15:01 -0700490impl Token for Underscore {
491 fn peek(cursor: Cursor) -> bool {
492 if let Some((ident, _rest)) = cursor.ident() {
493 return ident == "_";
494 }
495 if let Some((punct, _rest)) = cursor.punct() {
496 return punct.as_char() == '_'
497 }
498 false
499 }
500
501 fn display() -> &'static str {
502 "`_`"
503 }
504}
505
506#[cfg(feature = "parsing")]
507impl private::Sealed for Underscore {}
508
509#[cfg(feature = "parsing")]
David Tolnay2d84a082018-08-25 16:31:38 -0400510impl Token for Paren {
David Tolnay00f81fd2018-09-01 10:50:12 -0700511 fn peek(cursor: Cursor) -> bool {
512 lookahead::is_delimiter(cursor, Delimiter::Parenthesis)
David Tolnay2d84a082018-08-25 16:31:38 -0400513 }
514
David Tolnay2d032802018-09-01 10:51:59 -0700515 fn display() -> &'static str {
516 "parentheses"
David Tolnay2d84a082018-08-25 16:31:38 -0400517 }
518}
519
520#[cfg(feature = "parsing")]
521impl Token for Brace {
David Tolnay00f81fd2018-09-01 10:50:12 -0700522 fn peek(cursor: Cursor) -> bool {
523 lookahead::is_delimiter(cursor, Delimiter::Brace)
David Tolnay2d84a082018-08-25 16:31:38 -0400524 }
525
David Tolnay2d032802018-09-01 10:51:59 -0700526 fn display() -> &'static str {
527 "curly braces"
David Tolnay2d84a082018-08-25 16:31:38 -0400528 }
529}
530
531#[cfg(feature = "parsing")]
532impl Token for Bracket {
David Tolnay00f81fd2018-09-01 10:50:12 -0700533 fn peek(cursor: Cursor) -> bool {
534 lookahead::is_delimiter(cursor, Delimiter::Bracket)
David Tolnay2d84a082018-08-25 16:31:38 -0400535 }
536
David Tolnay2d032802018-09-01 10:51:59 -0700537 fn display() -> &'static str {
538 "square brackets"
David Tolnay2d84a082018-08-25 16:31:38 -0400539 }
540}
541
David Tolnaya7d69fc2018-08-26 13:30:24 -0400542#[cfg(feature = "parsing")]
543impl Token for Group {
David Tolnay00f81fd2018-09-01 10:50:12 -0700544 fn peek(cursor: Cursor) -> bool {
545 lookahead::is_delimiter(cursor, Delimiter::None)
David Tolnaya7d69fc2018-08-26 13:30:24 -0400546 }
547
David Tolnay2d032802018-09-01 10:51:59 -0700548 fn display() -> &'static str {
549 "invisible group"
David Tolnaya7d69fc2018-08-26 13:30:24 -0400550 }
551}
552
David Tolnay776f8e02018-08-24 22:32:10 -0400553define_keywords! {
554 "as" pub struct As /// `as`
555 "async" pub struct Async /// `async`
556 "auto" pub struct Auto /// `auto`
557 "box" pub struct Box /// `box`
558 "break" pub struct Break /// `break`
559 "Self" pub struct CapSelf /// `Self`
560 "const" pub struct Const /// `const`
561 "continue" pub struct Continue /// `continue`
562 "crate" pub struct Crate /// `crate`
563 "default" pub struct Default /// `default`
564 "dyn" pub struct Dyn /// `dyn`
565 "else" pub struct Else /// `else`
566 "enum" pub struct Enum /// `enum`
567 "existential" pub struct Existential /// `existential`
568 "extern" pub struct Extern /// `extern`
569 "fn" pub struct Fn /// `fn`
570 "for" pub struct For /// `for`
571 "if" pub struct If /// `if`
572 "impl" pub struct Impl /// `impl`
573 "in" pub struct In /// `in`
574 "let" pub struct Let /// `let`
575 "loop" pub struct Loop /// `loop`
576 "macro" pub struct Macro /// `macro`
577 "match" pub struct Match /// `match`
578 "mod" pub struct Mod /// `mod`
579 "move" pub struct Move /// `move`
580 "mut" pub struct Mut /// `mut`
581 "pub" pub struct Pub /// `pub`
582 "ref" pub struct Ref /// `ref`
583 "return" pub struct Return /// `return`
584 "self" pub struct Self_ /// `self`
585 "static" pub struct Static /// `static`
586 "struct" pub struct Struct /// `struct`
587 "super" pub struct Super /// `super`
588 "trait" pub struct Trait /// `trait`
589 "try" pub struct Try /// `try`
590 "type" pub struct Type /// `type`
591 "union" pub struct Union /// `union`
592 "unsafe" pub struct Unsafe /// `unsafe`
593 "use" pub struct Use /// `use`
594 "where" pub struct Where /// `where`
595 "while" pub struct While /// `while`
596 "yield" pub struct Yield /// `yield`
597}
598
599define_punctuation! {
600 "+" pub struct Add/1 /// `+`
601 "+=" pub struct AddEq/2 /// `+=`
602 "&" pub struct And/1 /// `&`
603 "&&" pub struct AndAnd/2 /// `&&`
604 "&=" pub struct AndEq/2 /// `&=`
605 "@" pub struct At/1 /// `@`
606 "!" pub struct Bang/1 /// `!`
607 "^" pub struct Caret/1 /// `^`
608 "^=" pub struct CaretEq/2 /// `^=`
609 ":" pub struct Colon/1 /// `:`
610 "::" pub struct Colon2/2 /// `::`
611 "," pub struct Comma/1 /// `,`
612 "/" pub struct Div/1 /// `/`
613 "/=" pub struct DivEq/2 /// `/=`
614 "$" pub struct Dollar/1 /// `$`
615 "." pub struct Dot/1 /// `.`
616 ".." pub struct Dot2/2 /// `..`
617 "..." pub struct Dot3/3 /// `...`
618 "..=" pub struct DotDotEq/3 /// `..=`
619 "=" pub struct Eq/1 /// `=`
620 "==" pub struct EqEq/2 /// `==`
621 ">=" pub struct Ge/2 /// `>=`
622 ">" pub struct Gt/1 /// `>`
623 "<=" pub struct Le/2 /// `<=`
624 "<" pub struct Lt/1 /// `<`
625 "*=" pub struct MulEq/2 /// `*=`
626 "!=" pub struct Ne/2 /// `!=`
627 "|" pub struct Or/1 /// `|`
628 "|=" pub struct OrEq/2 /// `|=`
629 "||" pub struct OrOr/2 /// `||`
630 "#" pub struct Pound/1 /// `#`
631 "?" pub struct Question/1 /// `?`
632 "->" pub struct RArrow/2 /// `->`
633 "<-" pub struct LArrow/2 /// `<-`
634 "%" pub struct Rem/1 /// `%`
635 "%=" pub struct RemEq/2 /// `%=`
636 "=>" pub struct FatArrow/2 /// `=>`
637 ";" pub struct Semi/1 /// `;`
638 "<<" pub struct Shl/2 /// `<<`
639 "<<=" pub struct ShlEq/3 /// `<<=`
640 ">>" pub struct Shr/2 /// `>>`
641 ">>=" pub struct ShrEq/3 /// `>>=`
642 "*" pub struct Star/1 /// `*`
643 "-" pub struct Sub/1 /// `-`
644 "-=" pub struct SubEq/2 /// `-=`
645}
646
647define_delimiters! {
648 "{" pub struct Brace /// `{...}`
649 "[" pub struct Bracket /// `[...]`
650 "(" pub struct Paren /// `(...)`
651 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700652}
653
David Tolnayf005f962018-01-06 21:19:41 -0800654/// A type-macro that expands to the name of the Rust type representation of a
655/// given token.
656///
657/// See the [token module] documentation for details and examples.
658///
659/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800660// Unfortunate duplication due to a rustdoc bug.
661// https://github.com/rust-lang/rust/issues/45939
662#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700663#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800664macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400665 (as) => { $crate::token::As };
666 (async) => { $crate::token::Async };
667 (auto) => { $crate::token::Auto };
668 (box) => { $crate::token::Box };
669 (break) => { $crate::token::Break };
670 (Self) => { $crate::token::CapSelf };
671 (const) => { $crate::token::Const };
672 (continue) => { $crate::token::Continue };
673 (crate) => { $crate::token::Crate };
674 (default) => { $crate::token::Default };
675 (dyn) => { $crate::token::Dyn };
676 (else) => { $crate::token::Else };
677 (enum) => { $crate::token::Enum };
678 (existential) => { $crate::token::Existential };
679 (extern) => { $crate::token::Extern };
680 (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 };
692 (pub) => { $crate::token::Pub };
693 (ref) => { $crate::token::Ref };
694 (return) => { $crate::token::Return };
695 (self) => { $crate::token::Self_ };
696 (static) => { $crate::token::Static };
697 (struct) => { $crate::token::Struct };
698 (super) => { $crate::token::Super };
699 (trait) => { $crate::token::Trait };
700 (try) => { $crate::token::Try };
701 (type) => { $crate::token::Type };
702 (union) => { $crate::token::Union };
703 (unsafe) => { $crate::token::Unsafe };
704 (use) => { $crate::token::Use };
705 (where) => { $crate::token::Where };
706 (while) => { $crate::token::While };
707 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400708 (+) => { $crate::token::Add };
709 (+=) => { $crate::token::AddEq };
710 (&) => { $crate::token::And };
711 (&&) => { $crate::token::AndAnd };
712 (&=) => { $crate::token::AndEq };
713 (@) => { $crate::token::At };
714 (!) => { $crate::token::Bang };
715 (^) => { $crate::token::Caret };
716 (^=) => { $crate::token::CaretEq };
717 (:) => { $crate::token::Colon };
718 (::) => { $crate::token::Colon2 };
719 (,) => { $crate::token::Comma };
720 (/) => { $crate::token::Div };
721 (/=) => { $crate::token::DivEq };
722 (.) => { $crate::token::Dot };
723 (..) => { $crate::token::Dot2 };
724 (...) => { $crate::token::Dot3 };
725 (..=) => { $crate::token::DotDotEq };
726 (=) => { $crate::token::Eq };
727 (==) => { $crate::token::EqEq };
728 (>=) => { $crate::token::Ge };
729 (>) => { $crate::token::Gt };
730 (<=) => { $crate::token::Le };
731 (<) => { $crate::token::Lt };
732 (*=) => { $crate::token::MulEq };
733 (!=) => { $crate::token::Ne };
734 (|) => { $crate::token::Or };
735 (|=) => { $crate::token::OrEq };
736 (||) => { $crate::token::OrOr };
737 (#) => { $crate::token::Pound };
738 (?) => { $crate::token::Question };
739 (->) => { $crate::token::RArrow };
740 (<-) => { $crate::token::LArrow };
741 (%) => { $crate::token::Rem };
742 (%=) => { $crate::token::RemEq };
743 (=>) => { $crate::token::FatArrow };
744 (;) => { $crate::token::Semi };
745 (<<) => { $crate::token::Shl };
746 (<<=) => { $crate::token::ShlEq };
747 (>>) => { $crate::token::Shr };
748 (>>=) => { $crate::token::ShrEq };
749 (*) => { $crate::token::Star };
750 (-) => { $crate::token::Sub };
751 (-=) => { $crate::token::SubEq };
752 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800753}
754
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700755#[cfg(feature = "parsing")]
756mod parsing {
David Tolnaya8205d92018-08-30 18:44:59 -0700757 use proc_macro2::{Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700758
David Tolnay68274de2018-09-02 17:15:01 -0700759 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400760 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400761 use parse::ParseStream;
David Tolnay776f8e02018-08-24 22:32:10 -0400762 use span::FromSpans;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700763
David Tolnay776f8e02018-08-24 22:32:10 -0400764 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700765 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400766 if let Some((ident, rest)) = cursor.ident() {
767 if ident == token {
768 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700769 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700770 }
David Tolnay776f8e02018-08-24 22:32:10 -0400771 Err(cursor.error(format!("expected `{}`", token)))
772 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700773 }
774
David Tolnay68274de2018-09-02 17:15:01 -0700775 pub fn peek_keyword(cursor: Cursor, token: &str) -> bool {
776 if let Some((ident, _rest)) = cursor.ident() {
777 ident == token
778 } else {
779 false
780 }
781 }
782
David Tolnay776f8e02018-08-24 22:32:10 -0400783 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
David Tolnay4398c922018-09-01 11:23:10 -0700784 let mut spans = [input.cursor().span(); 3];
785 punct_helper(input, token, &mut spans)?;
786 Ok(S::from_spans(&spans))
787 }
788
789 fn punct_helper(input: ParseStream, token: &str, spans: &mut [Span; 3]) -> Result<()> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700790 input.step(|cursor| {
David Tolnay776f8e02018-08-24 22:32:10 -0400791 let mut cursor = *cursor;
David Tolnay776f8e02018-08-24 22:32:10 -0400792 assert!(token.len() <= spans.len());
793
794 for (i, ch) in token.chars().enumerate() {
795 match cursor.punct() {
796 Some((punct, rest)) => {
797 spans[i] = punct.span();
798 if punct.as_char() != ch {
799 break;
800 } else if i == token.len() - 1 {
David Tolnay4398c922018-09-01 11:23:10 -0700801 return Ok(((), rest));
David Tolnay776f8e02018-08-24 22:32:10 -0400802 } else if punct.spacing() != Spacing::Joint {
803 break;
804 }
805 cursor = rest;
806 }
807 None => break,
808 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400809 }
David Tolnay776f8e02018-08-24 22:32:10 -0400810
811 Err(Error::new(spans[0], format!("expected `{}`", token)))
812 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700813 }
David Tolnay68274de2018-09-02 17:15:01 -0700814
815 pub fn peek_punct(mut cursor: Cursor, token: &str) -> bool {
816 for (i, ch) in token.chars().enumerate() {
817 match cursor.punct() {
818 Some((punct, rest)) => {
819 if punct.as_char() != ch {
820 break;
821 } else if i == token.len() - 1 {
822 return true;
823 } else if punct.spacing() != Spacing::Joint {
824 break;
825 }
826 cursor = rest;
827 }
828 None => break,
829 }
830 }
831 false
832 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700833}
834
835#[cfg(feature = "printing")]
836mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700837 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700838 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700839
Alex Crichtona74a1c82018-05-16 10:20:44 -0700840 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700841 assert_eq!(s.len(), spans.len());
842
843 let mut chars = s.chars();
844 let mut spans = spans.iter();
845 let ch = chars.next_back().unwrap();
846 let span = spans.next_back().unwrap();
847 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700848 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700849 op.set_span(*span);
850 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700851 }
852
Alex Crichtona74a1c82018-05-16 10:20:44 -0700853 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700854 op.set_span(*span);
855 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700856 }
857
Alex Crichtona74a1c82018-05-16 10:20:44 -0700858 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
859 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700860 }
861
Alex Crichtona74a1c82018-05-16 10:20:44 -0700862 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500863 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700864 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700865 {
David Tolnay00ab6982017-12-31 18:15:06 -0500866 let delim = match s {
867 "(" => Delimiter::Parenthesis,
868 "[" => Delimiter::Bracket,
869 "{" => Delimiter::Brace,
870 " " => Delimiter::None,
871 _ => panic!("unknown delimiter: {}", s),
872 };
hcplaa511792018-05-29 07:13:01 +0300873 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500874 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700875 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700876 g.set_span(*span);
877 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700878 }
879}