blob: 9f9b90443c9926b5b04a70c7381dd5374666cd72 [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//! ```
24//! # #[macro_use]
25//! # extern crate syn;
26//! #
David Tolnaye303b7c2018-05-20 16:46:35 -070027//! # use syn::{Attribute, Visibility, Ident, Type, Expr};
David Tolnaye79ae182018-01-06 19:23:37 -080028//! #
29//! pub struct ItemStatic {
30//! pub attrs: Vec<Attribute>,
31//! pub vis: Visibility,
32//! pub static_token: Token![static],
33//! pub mutability: Option<Token![mut]>,
34//! pub ident: Ident,
35//! pub colon_token: Token![:],
36//! pub ty: Box<Type>,
37//! pub eq_token: Token![=],
38//! pub expr: Box<Expr>,
39//! pub semi_token: Token![;],
40//! }
41//! #
42//! # fn main() {}
43//! ```
44//!
45//! # Parsing
46//!
47//! These tokens can be parsed using the [`Synom`] trait and the parser
48//! combinator macros [`punct!`], [`keyword!`], [`parens!`], [`braces!`], and
49//! [`brackets!`].
50//!
51//! [`Synom`]: ../synom/trait.Synom.html
52//! [`punct!`]: ../macro.punct.html
53//! [`keyword!`]: ../macro.keyword.html
54//! [`parens!`]: ../macro.parens.html
55//! [`braces!`]: ../macro.braces.html
56//! [`brackets!`]: ../macro.brackets.html
57//!
58//! ```
59//! #[macro_use]
60//! extern crate syn;
61//!
62//! use syn::synom::Synom;
David Tolnaye303b7c2018-05-20 16:46:35 -070063//! use syn::{Attribute, Visibility, Ident, Type, Expr};
David Tolnaye79ae182018-01-06 19:23:37 -080064//! #
65//! # struct ItemStatic;
66//! # use syn::ItemStatic as SynItemStatic;
67//!
68//! // Parse the ItemStatic struct shown above.
69//! impl Synom for ItemStatic {
70//! named!(parse -> Self, do_parse!(
71//! # (ItemStatic)
72//! # ));
73//! # }
74//! #
75//! # mod example {
76//! # use super::*;
77//! # use super::SynItemStatic as ItemStatic;
78//! #
79//! # named!(parse -> ItemStatic, do_parse!(
David Tolnayf8106f82018-08-25 21:17:45 -040080//! attrs: many0!(Attribute::old_parse_outer) >>
David Tolnaye79ae182018-01-06 19:23:37 -080081//! vis: syn!(Visibility) >>
82//! static_token: keyword!(static) >>
83//! mutability: option!(keyword!(mut)) >>
84//! ident: syn!(Ident) >>
85//! colon_token: punct!(:) >>
86//! ty: syn!(Type) >>
87//! eq_token: punct!(=) >>
88//! expr: syn!(Expr) >>
89//! semi_token: punct!(;) >>
90//! (ItemStatic {
91//! attrs, vis, static_token, mutability, ident, colon_token,
92//! ty: Box::new(ty), eq_token, expr: Box::new(expr), semi_token,
93//! })
94//! ));
95//! }
96//! #
97//! # fn main() {}
98//! ```
Alex Crichton954046c2017-05-30 21:49:42 -070099
David Tolnay776f8e02018-08-24 22:32:10 -0400100use std;
David Tolnayd9836922018-08-25 18:05:36 -0400101#[cfg(feature = "parsing")]
102use std::cell::Cell;
David Tolnay776f8e02018-08-24 22:32:10 -0400103#[cfg(feature = "extra-traits")]
104use std::cmp;
105#[cfg(feature = "extra-traits")]
106use std::fmt::{self, Debug};
107#[cfg(feature = "extra-traits")]
108use std::hash::{Hash, Hasher};
David Tolnayd9836922018-08-25 18:05:36 -0400109#[cfg(feature = "parsing")]
110use std::rc::Rc;
David Tolnay776f8e02018-08-24 22:32:10 -0400111
David Tolnay2d84a082018-08-25 16:31:38 -0400112#[cfg(feature = "parsing")]
113use proc_macro2::Delimiter;
David Tolnay8c39ac52018-08-25 08:46:21 -0400114#[cfg(any(feature = "printing", feature = "parsing"))]
115use proc_macro2::Spacing;
David Tolnay65fb5662018-05-20 20:02:28 -0700116use proc_macro2::{Ident, Span};
Sergio Benitezd14d5362018-04-28 15:38:25 -0700117#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400118use proc_macro2::{Punct, TokenStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400119#[cfg(feature = "printing")]
120use quote::{ToTokens, TokenStreamExt};
121
122#[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400123use error::Result;
124#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400125use lifetime::Lifetime;
126#[cfg(feature = "parsing")]
David Tolnaya7d69fc2018-08-26 13:30:24 -0400127use lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr};
David Tolnay4fb71232018-08-25 23:14:50 -0400128#[cfg(feature = "parsing")]
David Tolnayb6254182018-08-25 08:44:54 -0400129use lookahead;
David Tolnay776f8e02018-08-24 22:32:10 -0400130#[cfg(feature = "parsing")]
David Tolnayd9836922018-08-25 18:05:36 -0400131use parse::{Lookahead1, Parse, ParseBuffer, ParseStream};
David Tolnay776f8e02018-08-24 22:32:10 -0400132use span::IntoSpans;
133
134/// Marker trait for types that represent single tokens.
135///
136/// This trait is sealed and cannot be implemented for types outside of Syn.
137#[cfg(feature = "parsing")]
138pub trait Token: private::Sealed {
139 // Not public API.
140 #[doc(hidden)]
141 fn peek(lookahead: &Lookahead1) -> bool;
142
143 // Not public API.
144 #[doc(hidden)]
145 fn display() -> String;
Sergio Benitezd14d5362018-04-28 15:38:25 -0700146}
147
148#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400149mod private {
150 pub trait Sealed {}
Sergio Benitezd14d5362018-04-28 15:38:25 -0700151}
152
David Tolnay776f8e02018-08-24 22:32:10 -0400153macro_rules! impl_token {
David Tolnay4fb71232018-08-25 23:14:50 -0400154 ($name:ident $display:expr) => {
David Tolnay776f8e02018-08-24 22:32:10 -0400155 #[cfg(feature = "parsing")]
156 impl Token for $name {
157 fn peek(lookahead: &Lookahead1) -> bool {
David Tolnayd9836922018-08-25 18:05:36 -0400158 // TODO factor out in a way that can be compiled just once
159 let scope = Span::call_site();
160 let cursor = lookahead.cursor();
161 let unexpected = Rc::new(Cell::new(None));
162 ParseBuffer::new(scope, cursor, unexpected)
163 .parse::<Self>()
164 .is_ok()
David Tolnay776f8e02018-08-24 22:32:10 -0400165 }
166
167 fn display() -> String {
David Tolnay4fb71232018-08-25 23:14:50 -0400168 $display.to_owned()
David Tolnay776f8e02018-08-24 22:32:10 -0400169 }
170 }
171
172 #[cfg(feature = "parsing")]
173 impl private::Sealed for $name {}
174 };
175}
176
David Tolnay4fb71232018-08-25 23:14:50 -0400177impl_token!(Ident "identifier");
178impl_token!(Lifetime "lifetime");
179impl_token!(Lit "literal");
David Tolnaya7d69fc2018-08-26 13:30:24 -0400180impl_token!(LitStr "string literal");
181impl_token!(LitByteStr "byte string literal");
182impl_token!(LitByte "byte literal");
183impl_token!(LitChar "character literal");
184impl_token!(LitInt "integer literal");
185impl_token!(LitFloat "floating point literal");
186impl_token!(LitBool "boolean literal");
David Tolnay4fb71232018-08-25 23:14:50 -0400187
David Tolnay776f8e02018-08-24 22:32:10 -0400188macro_rules! define_keywords {
189 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
190 $(
191 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
192 #[$doc]
193 ///
194 /// Don't try to remember the name of this type -- use the [`Token!`]
195 /// macro instead.
196 ///
197 /// [`Token!`]: index.html
198 pub struct $name {
199 pub span: Span,
200 }
201
202 #[doc(hidden)]
203 #[allow(non_snake_case)]
204 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
205 $name {
206 span: span.into_spans()[0],
207 }
208 }
209
David Tolnay4fb71232018-08-25 23:14:50 -0400210 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400211
212 impl std::default::Default for $name {
213 fn default() -> Self {
214 $name(Span::call_site())
215 }
216 }
217
218 #[cfg(feature = "extra-traits")]
219 impl Debug for $name {
220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
221 f.write_str(stringify!($name))
222 }
223 }
224
225 #[cfg(feature = "extra-traits")]
226 impl cmp::Eq for $name {}
227
228 #[cfg(feature = "extra-traits")]
229 impl PartialEq for $name {
230 fn eq(&self, _other: &$name) -> bool {
231 true
232 }
233 }
234
235 #[cfg(feature = "extra-traits")]
236 impl Hash for $name {
237 fn hash<H: Hasher>(&self, _state: &mut H) {}
238 }
239
240 #[cfg(feature = "printing")]
241 impl ToTokens for $name {
242 fn to_tokens(&self, tokens: &mut TokenStream) {
243 printing::keyword($token, &self.span, tokens);
244 }
245 }
246
247 #[cfg(feature = "parsing")]
248 impl Parse for $name {
249 fn parse(input: ParseStream) -> Result<Self> {
250 parsing::keyword(input, $token).map($name)
251 }
252 }
253 )*
254 };
255}
256
257macro_rules! define_punctuation_structs {
258 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
259 $(
260 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
261 #[$doc]
262 ///
263 /// Don't try to remember the name of this type -- use the [`Token!`]
264 /// macro instead.
265 ///
266 /// [`Token!`]: index.html
267 pub struct $name {
268 pub spans: [Span; $len],
269 }
270
271 #[doc(hidden)]
272 #[allow(non_snake_case)]
273 pub fn $name<S: IntoSpans<[Span; $len]>>(spans: S) -> $name {
274 $name {
275 spans: spans.into_spans(),
276 }
277 }
278
David Tolnay4fb71232018-08-25 23:14:50 -0400279 impl_token!($name concat!("`", $token, "`"));
David Tolnay776f8e02018-08-24 22:32:10 -0400280
281 impl std::default::Default for $name {
282 fn default() -> Self {
283 $name([Span::call_site(); $len])
284 }
285 }
286
287 #[cfg(feature = "extra-traits")]
288 impl Debug for $name {
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 f.write_str(stringify!($name))
291 }
292 }
293
294 #[cfg(feature = "extra-traits")]
295 impl cmp::Eq for $name {}
296
297 #[cfg(feature = "extra-traits")]
298 impl PartialEq for $name {
299 fn eq(&self, _other: &$name) -> bool {
300 true
301 }
302 }
303
304 #[cfg(feature = "extra-traits")]
305 impl Hash for $name {
306 fn hash<H: Hasher>(&self, _state: &mut H) {}
307 }
308 )*
309 };
310}
311
312macro_rules! define_punctuation {
313 ($($token:tt pub struct $name:ident/$len:tt #[$doc:meta])*) => {
314 $(
315 define_punctuation_structs! {
316 $token pub struct $name/$len #[$doc]
317 }
318
319 #[cfg(feature = "printing")]
320 impl ToTokens for $name {
321 fn to_tokens(&self, tokens: &mut TokenStream) {
322 printing::punct($token, &self.spans, tokens);
323 }
324 }
325
326 #[cfg(feature = "parsing")]
327 impl Parse for $name {
328 fn parse(input: ParseStream) -> Result<Self> {
329 parsing::punct(input, $token).map($name::<[Span; $len]>)
330 }
331 }
332 )*
333 };
334}
335
336macro_rules! define_delimiters {
337 ($($token:tt pub struct $name:ident #[$doc:meta])*) => {
338 $(
339 #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))]
340 #[$doc]
341 pub struct $name {
342 pub span: Span,
343 }
344
345 #[doc(hidden)]
346 #[allow(non_snake_case)]
347 pub fn $name<S: IntoSpans<[Span; 1]>>(span: S) -> $name {
348 $name {
349 span: span.into_spans()[0],
350 }
351 }
352
353 impl std::default::Default for $name {
354 fn default() -> Self {
355 $name(Span::call_site())
356 }
357 }
358
359 #[cfg(feature = "extra-traits")]
360 impl Debug for $name {
361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362 f.write_str(stringify!($name))
363 }
364 }
365
366 #[cfg(feature = "extra-traits")]
367 impl cmp::Eq for $name {}
368
369 #[cfg(feature = "extra-traits")]
370 impl PartialEq for $name {
371 fn eq(&self, _other: &$name) -> bool {
372 true
373 }
374 }
375
376 #[cfg(feature = "extra-traits")]
377 impl Hash for $name {
378 fn hash<H: Hasher>(&self, _state: &mut H) {}
379 }
380
381 impl $name {
382 #[cfg(feature = "printing")]
383 pub fn surround<F>(&self, tokens: &mut TokenStream, f: F)
384 where
385 F: FnOnce(&mut TokenStream),
386 {
387 printing::delim($token, &self.span, tokens, f);
388 }
389
390 #[cfg(feature = "parsing")]
391 pub fn parse<F, R>(
392 tokens: $crate::buffer::Cursor,
393 f: F,
394 ) -> $crate::synom::PResult<($name, R)>
395 where
396 F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R>,
397 {
398 parsing::delim($token, tokens, $name, f)
399 }
400 }
David Tolnay2d84a082018-08-25 16:31:38 -0400401
402 #[cfg(feature = "parsing")]
403 impl private::Sealed for $name {}
David Tolnay776f8e02018-08-24 22:32:10 -0400404 )*
405 };
406}
407
408define_punctuation_structs! {
409 "'" pub struct Apostrophe/1 /// `'`
410 "_" pub struct Underscore/1 /// `_`
Alex Crichton131308c2018-05-18 14:00:24 -0700411}
412
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700413// Implement Clone anyway because it is required for cloning Lifetime.
414#[cfg(not(feature = "clone-impls"))]
415impl Clone for Apostrophe {
416 fn clone(&self) -> Self {
David Tolnay7ac699c2018-08-24 14:00:58 -0400417 Apostrophe(self.spans)
David Tolnayb2fc7ef2018-05-20 19:54:14 -0700418 }
419}
420
Alex Crichton131308c2018-05-18 14:00:24 -0700421#[cfg(feature = "printing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400422impl ToTokens for Apostrophe {
423 fn to_tokens(&self, tokens: &mut TokenStream) {
424 let mut token = Punct::new('\'', Spacing::Joint);
David Tolnay7ac699c2018-08-24 14:00:58 -0400425 token.set_span(self.spans[0]);
Alex Crichton131308c2018-05-18 14:00:24 -0700426 tokens.append(token);
427 }
428}
429
430#[cfg(feature = "parsing")]
David Tolnay776f8e02018-08-24 22:32:10 -0400431impl Parse for Apostrophe {
432 fn parse(input: ParseStream) -> Result<Self> {
433 input.step_cursor(|cursor| {
434 if let Some((punct, rest)) = cursor.punct() {
435 if punct.as_char() == '\'' && punct.spacing() == Spacing::Joint {
436 return Ok((Apostrophe(punct.span()), rest));
Alex Crichton131308c2018-05-18 14:00:24 -0700437 }
438 }
David Tolnay776f8e02018-08-24 22:32:10 -0400439 Err(cursor.error("expected `'`"))
440 })
Alex Crichton131308c2018-05-18 14:00:24 -0700441 }
442}
443
David Tolnay776f8e02018-08-24 22:32:10 -0400444#[cfg(feature = "printing")]
445impl ToTokens for Underscore {
446 fn to_tokens(&self, tokens: &mut TokenStream) {
447 tokens.append(Ident::new("_", self.spans[0]));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700448 }
David Tolnay776f8e02018-08-24 22:32:10 -0400449}
450
451#[cfg(feature = "parsing")]
452impl Parse for Underscore {
453 fn parse(input: ParseStream) -> Result<Self> {
454 input.step_cursor(|cursor| {
455 if let Some((ident, rest)) = cursor.ident() {
456 if ident == "_" {
457 return Ok((Underscore(ident.span()), rest));
458 }
459 }
460 if let Some((punct, rest)) = cursor.punct() {
461 if punct.as_char() == '_' {
462 return Ok((Underscore(punct.span()), rest));
463 }
464 }
465 Err(cursor.error("expected `_`"))
466 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700467 }
David Tolnay776f8e02018-08-24 22:32:10 -0400468}
469
David Tolnay2d84a082018-08-25 16:31:38 -0400470#[cfg(feature = "parsing")]
471impl Token for Paren {
472 fn peek(lookahead: &Lookahead1) -> bool {
473 lookahead::is_delimiter(lookahead, Delimiter::Parenthesis)
474 }
475
476 fn display() -> String {
477 "parentheses".to_owned()
478 }
479}
480
481#[cfg(feature = "parsing")]
482impl Token for Brace {
483 fn peek(lookahead: &Lookahead1) -> bool {
484 lookahead::is_delimiter(lookahead, Delimiter::Brace)
485 }
486
487 fn display() -> String {
488 "curly braces".to_owned()
489 }
490}
491
492#[cfg(feature = "parsing")]
493impl Token for Bracket {
494 fn peek(lookahead: &Lookahead1) -> bool {
495 lookahead::is_delimiter(lookahead, Delimiter::Bracket)
496 }
497
498 fn display() -> String {
499 "square brackets".to_owned()
500 }
501}
502
David Tolnaya7d69fc2018-08-26 13:30:24 -0400503#[cfg(feature = "parsing")]
504impl Token for Group {
505 fn peek(lookahead: &Lookahead1) -> bool {
506 lookahead::is_delimiter(lookahead, Delimiter::None)
507 }
508
509 fn display() -> String {
510 "invisible group".to_owned()
511 }
512}
513
David Tolnay776f8e02018-08-24 22:32:10 -0400514define_keywords! {
515 "as" pub struct As /// `as`
516 "async" pub struct Async /// `async`
517 "auto" pub struct Auto /// `auto`
518 "box" pub struct Box /// `box`
519 "break" pub struct Break /// `break`
520 "Self" pub struct CapSelf /// `Self`
521 "const" pub struct Const /// `const`
522 "continue" pub struct Continue /// `continue`
523 "crate" pub struct Crate /// `crate`
524 "default" pub struct Default /// `default`
525 "dyn" pub struct Dyn /// `dyn`
526 "else" pub struct Else /// `else`
527 "enum" pub struct Enum /// `enum`
528 "existential" pub struct Existential /// `existential`
529 "extern" pub struct Extern /// `extern`
530 "fn" pub struct Fn /// `fn`
531 "for" pub struct For /// `for`
532 "if" pub struct If /// `if`
533 "impl" pub struct Impl /// `impl`
534 "in" pub struct In /// `in`
535 "let" pub struct Let /// `let`
536 "loop" pub struct Loop /// `loop`
537 "macro" pub struct Macro /// `macro`
538 "match" pub struct Match /// `match`
539 "mod" pub struct Mod /// `mod`
540 "move" pub struct Move /// `move`
541 "mut" pub struct Mut /// `mut`
542 "pub" pub struct Pub /// `pub`
543 "ref" pub struct Ref /// `ref`
544 "return" pub struct Return /// `return`
545 "self" pub struct Self_ /// `self`
546 "static" pub struct Static /// `static`
547 "struct" pub struct Struct /// `struct`
548 "super" pub struct Super /// `super`
549 "trait" pub struct Trait /// `trait`
550 "try" pub struct Try /// `try`
551 "type" pub struct Type /// `type`
552 "union" pub struct Union /// `union`
553 "unsafe" pub struct Unsafe /// `unsafe`
554 "use" pub struct Use /// `use`
555 "where" pub struct Where /// `where`
556 "while" pub struct While /// `while`
557 "yield" pub struct Yield /// `yield`
558}
559
560define_punctuation! {
561 "+" pub struct Add/1 /// `+`
562 "+=" pub struct AddEq/2 /// `+=`
563 "&" pub struct And/1 /// `&`
564 "&&" pub struct AndAnd/2 /// `&&`
565 "&=" pub struct AndEq/2 /// `&=`
566 "@" pub struct At/1 /// `@`
567 "!" pub struct Bang/1 /// `!`
568 "^" pub struct Caret/1 /// `^`
569 "^=" pub struct CaretEq/2 /// `^=`
570 ":" pub struct Colon/1 /// `:`
571 "::" pub struct Colon2/2 /// `::`
572 "," pub struct Comma/1 /// `,`
573 "/" pub struct Div/1 /// `/`
574 "/=" pub struct DivEq/2 /// `/=`
575 "$" pub struct Dollar/1 /// `$`
576 "." pub struct Dot/1 /// `.`
577 ".." pub struct Dot2/2 /// `..`
578 "..." pub struct Dot3/3 /// `...`
579 "..=" pub struct DotDotEq/3 /// `..=`
580 "=" pub struct Eq/1 /// `=`
581 "==" pub struct EqEq/2 /// `==`
582 ">=" pub struct Ge/2 /// `>=`
583 ">" pub struct Gt/1 /// `>`
584 "<=" pub struct Le/2 /// `<=`
585 "<" pub struct Lt/1 /// `<`
586 "*=" pub struct MulEq/2 /// `*=`
587 "!=" pub struct Ne/2 /// `!=`
588 "|" pub struct Or/1 /// `|`
589 "|=" pub struct OrEq/2 /// `|=`
590 "||" pub struct OrOr/2 /// `||`
591 "#" pub struct Pound/1 /// `#`
592 "?" pub struct Question/1 /// `?`
593 "->" pub struct RArrow/2 /// `->`
594 "<-" pub struct LArrow/2 /// `<-`
595 "%" pub struct Rem/1 /// `%`
596 "%=" pub struct RemEq/2 /// `%=`
597 "=>" pub struct FatArrow/2 /// `=>`
598 ";" pub struct Semi/1 /// `;`
599 "<<" pub struct Shl/2 /// `<<`
600 "<<=" pub struct ShlEq/3 /// `<<=`
601 ">>" pub struct Shr/2 /// `>>`
602 ">>=" pub struct ShrEq/3 /// `>>=`
603 "*" pub struct Star/1 /// `*`
604 "-" pub struct Sub/1 /// `-`
605 "-=" pub struct SubEq/2 /// `-=`
606}
607
608define_delimiters! {
609 "{" pub struct Brace /// `{...}`
610 "[" pub struct Bracket /// `[...]`
611 "(" pub struct Paren /// `(...)`
612 " " pub struct Group /// None-delimited group
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700613}
614
David Tolnayf005f962018-01-06 21:19:41 -0800615/// A type-macro that expands to the name of the Rust type representation of a
616/// given token.
617///
618/// See the [token module] documentation for details and examples.
619///
620/// [token module]: token/index.html
David Tolnayf8db7ba2017-11-11 22:52:16 -0800621// Unfortunate duplication due to a rustdoc bug.
622// https://github.com/rust-lang/rust/issues/45939
623#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700624#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800625macro_rules! Token {
David Tolnay776f8e02018-08-24 22:32:10 -0400626 (as) => { $crate::token::As };
627 (async) => { $crate::token::Async };
628 (auto) => { $crate::token::Auto };
629 (box) => { $crate::token::Box };
630 (break) => { $crate::token::Break };
631 (Self) => { $crate::token::CapSelf };
632 (const) => { $crate::token::Const };
633 (continue) => { $crate::token::Continue };
634 (crate) => { $crate::token::Crate };
635 (default) => { $crate::token::Default };
636 (dyn) => { $crate::token::Dyn };
637 (else) => { $crate::token::Else };
638 (enum) => { $crate::token::Enum };
639 (existential) => { $crate::token::Existential };
640 (extern) => { $crate::token::Extern };
641 (fn) => { $crate::token::Fn };
642 (for) => { $crate::token::For };
643 (if) => { $crate::token::If };
644 (impl) => { $crate::token::Impl };
645 (in) => { $crate::token::In };
646 (let) => { $crate::token::Let };
647 (loop) => { $crate::token::Loop };
648 (macro) => { $crate::token::Macro };
649 (match) => { $crate::token::Match };
650 (mod) => { $crate::token::Mod };
651 (move) => { $crate::token::Move };
652 (mut) => { $crate::token::Mut };
653 (pub) => { $crate::token::Pub };
654 (ref) => { $crate::token::Ref };
655 (return) => { $crate::token::Return };
656 (self) => { $crate::token::Self_ };
657 (static) => { $crate::token::Static };
658 (struct) => { $crate::token::Struct };
659 (super) => { $crate::token::Super };
660 (trait) => { $crate::token::Trait };
661 (try) => { $crate::token::Try };
662 (type) => { $crate::token::Type };
663 (union) => { $crate::token::Union };
664 (unsafe) => { $crate::token::Unsafe };
665 (use) => { $crate::token::Use };
666 (where) => { $crate::token::Where };
667 (while) => { $crate::token::While };
668 (yield) => { $crate::token::Yield };
David Tolnaybb82ef02018-08-24 20:15:45 -0400669 (+) => { $crate::token::Add };
670 (+=) => { $crate::token::AddEq };
671 (&) => { $crate::token::And };
672 (&&) => { $crate::token::AndAnd };
673 (&=) => { $crate::token::AndEq };
674 (@) => { $crate::token::At };
675 (!) => { $crate::token::Bang };
676 (^) => { $crate::token::Caret };
677 (^=) => { $crate::token::CaretEq };
678 (:) => { $crate::token::Colon };
679 (::) => { $crate::token::Colon2 };
680 (,) => { $crate::token::Comma };
681 (/) => { $crate::token::Div };
682 (/=) => { $crate::token::DivEq };
683 (.) => { $crate::token::Dot };
684 (..) => { $crate::token::Dot2 };
685 (...) => { $crate::token::Dot3 };
686 (..=) => { $crate::token::DotDotEq };
687 (=) => { $crate::token::Eq };
688 (==) => { $crate::token::EqEq };
689 (>=) => { $crate::token::Ge };
690 (>) => { $crate::token::Gt };
691 (<=) => { $crate::token::Le };
692 (<) => { $crate::token::Lt };
693 (*=) => { $crate::token::MulEq };
694 (!=) => { $crate::token::Ne };
695 (|) => { $crate::token::Or };
696 (|=) => { $crate::token::OrEq };
697 (||) => { $crate::token::OrOr };
698 (#) => { $crate::token::Pound };
699 (?) => { $crate::token::Question };
700 (->) => { $crate::token::RArrow };
701 (<-) => { $crate::token::LArrow };
702 (%) => { $crate::token::Rem };
703 (%=) => { $crate::token::RemEq };
704 (=>) => { $crate::token::FatArrow };
705 (;) => { $crate::token::Semi };
706 (<<) => { $crate::token::Shl };
707 (<<=) => { $crate::token::ShlEq };
708 (>>) => { $crate::token::Shr };
709 (>>=) => { $crate::token::ShrEq };
710 (*) => { $crate::token::Star };
711 (-) => { $crate::token::Sub };
712 (-=) => { $crate::token::SubEq };
713 (_) => { $crate::token::Underscore };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800714}
715
David Tolnayf005f962018-01-06 21:19:41 -0800716/// Parse a single Rust punctuation token.
717///
718/// See the [token module] documentation for details and examples.
719///
720/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800721///
722/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500723#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800724#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700725#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800726macro_rules! punct {
David Tolnay32954ef2017-12-26 22:43:16 -0500727 ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) };
728 ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) };
729 ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) };
730 ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) };
731 ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) };
732 ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) };
733 ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) };
734 ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) };
735 ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) };
736 ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) };
737 ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) };
738 ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) };
739 ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) };
740 ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) };
741 ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) };
742 ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) };
743 ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) };
744 ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) };
745 ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) };
746 ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) };
747 ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) };
748 ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) };
749 ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) };
750 ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) };
751 ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) };
752 ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) };
753 ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) };
754 ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) };
755 ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) };
756 ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) };
757 ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) };
758 ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) };
759 ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) };
760 ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) };
761 ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) };
David Tolnay17624152018-03-31 18:11:40 +0200762 ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) };
David Tolnay32954ef2017-12-26 22:43:16 -0500763 ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) };
764 ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) };
765 ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) };
766 ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) };
767 ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) };
768 ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) };
769 ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) };
770 ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) };
771 ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800772}
773
David Tolnayf005f962018-01-06 21:19:41 -0800774/// Parse a single Rust keyword token.
775///
776/// See the [token module] documentation for details and examples.
777///
778/// [token module]: token/index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800779///
780/// *This macro is available if Syn is built with the `"parsing"` feature.*
David Tolnay0fbe3282017-12-26 21:46:16 -0500781#[cfg(feature = "parsing")]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800782#[macro_export]
David Tolnaya5ed2fe2018-04-29 12:23:34 -0700783#[cfg_attr(rustfmt, rustfmt_skip)]
David Tolnayf8db7ba2017-11-11 22:52:16 -0800784macro_rules! keyword {
David Tolnaybb82ef02018-08-24 20:15:45 -0400785 ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) };
786 ($i:expr, async) => { call!($i, <$crate::token::Async as $crate::synom::Synom>::parse) };
787 ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) };
788 ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) };
789 ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) };
790 ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) };
791 ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) };
792 ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) };
793 ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) };
794 ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) };
795 ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) };
796 ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) };
797 ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) };
798 ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) };
799 ($i:expr, existential) => { call!($i, <$crate::token::Existential as $crate::synom::Synom>::parse) };
800 ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) };
801 ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) };
802 ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) };
803 ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) };
804 ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) };
805 ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) };
806 ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) };
807 ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) };
808 ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) };
809 ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) };
810 ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) };
811 ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) };
812 ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) };
813 ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) };
814 ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) };
815 ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) };
816 ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) };
817 ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) };
818 ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) };
819 ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) };
820 ($i:expr, try) => { call!($i, <$crate::token::Try as $crate::synom::Synom>::parse) };
821 ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) };
822 ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) };
823 ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) };
824 ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) };
825 ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) };
826 ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) };
827 ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) };
David Tolnayf8db7ba2017-11-11 22:52:16 -0800828}
829
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700830macro_rules! ident_from_token {
831 ($token:ident) => {
832 impl From<Token![$token]> for Ident {
833 fn from(token: Token![$token]) -> Ident {
David Tolnay7ac699c2018-08-24 14:00:58 -0400834 Ident::new(stringify!($token), token.span)
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700835 }
836 }
837 };
838}
839
840ident_from_token!(self);
841ident_from_token!(Self);
842ident_from_token!(super);
843ident_from_token!(crate);
David Tolnay0a4d4e92018-07-21 15:31:45 -0700844ident_from_token!(extern);
David Tolnaybd0bc3e2018-05-20 17:15:35 -0700845
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700846#[cfg(feature = "parsing")]
847mod parsing {
David Tolnay51382052017-12-27 13:46:21 -0500848 use proc_macro2::{Delimiter, Spacing, Span};
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700849
David Tolnaydfc886b2018-01-06 08:03:09 -0800850 use buffer::Cursor;
David Tolnayad4b2472018-08-25 08:25:24 -0400851 use error::{Error, Result};
David Tolnayb6254182018-08-25 08:44:54 -0400852 use parse::ParseStream;
David Tolnay203557a2017-12-27 23:59:33 -0500853 use parse_error;
David Tolnay776f8e02018-08-24 22:32:10 -0400854 use span::FromSpans;
David Tolnay203557a2017-12-27 23:59:33 -0500855 use synom::PResult;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700856
David Tolnay776f8e02018-08-24 22:32:10 -0400857 pub fn keyword(input: ParseStream, token: &str) -> Result<Span> {
858 input.step_cursor(|cursor| {
859 if let Some((ident, rest)) = cursor.ident() {
860 if ident == token {
861 return Ok((ident.span(), rest));
Alex Crichton954046c2017-05-30 21:49:42 -0700862 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700863 }
David Tolnay776f8e02018-08-24 22:32:10 -0400864 Err(cursor.error(format!("expected `{}`", token)))
865 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700866 }
867
David Tolnay776f8e02018-08-24 22:32:10 -0400868 pub fn punct<S: FromSpans>(input: ParseStream, token: &str) -> Result<S> {
869 input.step_cursor(|cursor| {
870 let mut cursor = *cursor;
871 let mut spans = [cursor.span(); 3];
872 assert!(token.len() <= spans.len());
873
874 for (i, ch) in token.chars().enumerate() {
875 match cursor.punct() {
876 Some((punct, rest)) => {
877 spans[i] = punct.span();
878 if punct.as_char() != ch {
879 break;
880 } else if i == token.len() - 1 {
881 return Ok((S::from_spans(&spans), rest));
882 } else if punct.spacing() != Spacing::Joint {
883 break;
884 }
885 cursor = rest;
886 }
887 None => break,
888 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400889 }
David Tolnay776f8e02018-08-24 22:32:10 -0400890
891 Err(Error::new(spans[0], format!("expected `{}`", token)))
892 })
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700893 }
894
David Tolnay51382052017-12-27 13:46:21 -0500895 pub fn delim<'a, F, R, T>(
896 delim: &str,
897 tokens: Cursor<'a>,
David Tolnay2b069542018-05-09 12:59:36 -0700898 new: fn(Span) -> T,
David Tolnay51382052017-12-27 13:46:21 -0500899 f: F,
David Tolnay8875fca2017-12-31 13:52:37 -0500900 ) -> PResult<'a, (T, R)>
David Tolnay51382052017-12-27 13:46:21 -0500901 where
902 F: FnOnce(Cursor) -> PResult<R>,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700903 {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400904 // NOTE: We should support none-delimited sequences here.
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700905 let delim = match delim {
906 "(" => Delimiter::Parenthesis,
907 "{" => Delimiter::Brace,
908 "[" => Delimiter::Bracket,
Michael Layzell93c36282017-06-04 20:43:14 -0400909 " " => Delimiter::None,
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700910 _ => panic!("unknown delimiter: {}", delim),
911 };
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700912
David Tolnay65729482017-12-31 16:14:50 -0500913 if let Some((inside, span, rest)) = tokens.group(delim) {
914 match f(inside) {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500915 Ok((ret, remaining)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400916 if remaining.eof() {
David Tolnay2b069542018-05-09 12:59:36 -0700917 return Ok(((new(span), ret), rest));
Michael Layzell0a1a6632017-06-02 18:07:43 -0400918 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700919 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400920 Err(err) => return Err(err),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700921 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700922 }
Michael Layzell0a1a6632017-06-02 18:07:43 -0400923 parse_error()
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700924 }
925}
926
927#[cfg(feature = "printing")]
928mod printing {
David Tolnay65fb5662018-05-20 20:02:28 -0700929 use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700930 use quote::TokenStreamExt;
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700931
Alex Crichtona74a1c82018-05-16 10:20:44 -0700932 pub fn punct(s: &str, spans: &[Span], tokens: &mut TokenStream) {
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700933 assert_eq!(s.len(), spans.len());
934
935 let mut chars = s.chars();
936 let mut spans = spans.iter();
937 let ch = chars.next_back().unwrap();
938 let span = spans.next_back().unwrap();
939 for (ch, span) in chars.zip(spans) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700940 let mut op = Punct::new(ch, Spacing::Joint);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700941 op.set_span(*span);
942 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700943 }
944
Alex Crichtona74a1c82018-05-16 10:20:44 -0700945 let mut op = Punct::new(ch, Spacing::Alone);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700946 op.set_span(*span);
947 tokens.append(op);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700948 }
949
Alex Crichtona74a1c82018-05-16 10:20:44 -0700950 pub fn keyword(s: &str, span: &Span, tokens: &mut TokenStream) {
951 tokens.append(Ident::new(s, *span));
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700952 }
953
Alex Crichtona74a1c82018-05-16 10:20:44 -0700954 pub fn delim<F>(s: &str, span: &Span, tokens: &mut TokenStream, f: F)
David Tolnay51382052017-12-27 13:46:21 -0500955 where
Alex Crichtona74a1c82018-05-16 10:20:44 -0700956 F: FnOnce(&mut TokenStream),
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700957 {
David Tolnay00ab6982017-12-31 18:15:06 -0500958 let delim = match s {
959 "(" => Delimiter::Parenthesis,
960 "[" => Delimiter::Bracket,
961 "{" => Delimiter::Brace,
962 " " => Delimiter::None,
963 _ => panic!("unknown delimiter: {}", s),
964 };
hcplaa511792018-05-29 07:13:01 +0300965 let mut inner = TokenStream::new();
David Tolnay00ab6982017-12-31 18:15:06 -0500966 f(&mut inner);
David Tolnay106db5e2018-05-20 19:56:38 -0700967 let mut g = Group::new(delim, inner);
Alex Crichton9a4dca22018-03-28 06:32:19 -0700968 g.set_span(*span);
969 tokens.append(g);
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700970 }
971}