blob: 891469695d2962ed6fa0de3f10c67db745986cc8 [file] [log] [blame]
David Tolnay80a914f2018-08-30 23:49:53 -07001// 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 Tolnay18c754c2018-08-21 23:26:58 -04009//! Parsing interface for parsing a token stream into a syntax tree node.
David Tolnay80a914f2018-08-30 23:49:53 -070010//!
David Tolnaye0c51762018-08-31 11:05:22 -070011//! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
12//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
13//! these parser functions is a lower level mechanism built around the
14//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
15//! tokens in a token stream.
David Tolnay80a914f2018-08-30 23:49:53 -070016//!
David Tolnaye0c51762018-08-31 11:05:22 -070017//! [`ParseStream`]: type.ParseStream.html
18//! [`Result<T>`]: type.Result.html
David Tolnay80a914f2018-08-30 23:49:53 -070019//! [`Cursor`]: ../buffer/index.html
David Tolnay80a914f2018-08-30 23:49:53 -070020//!
David Tolnaye0c51762018-08-31 11:05:22 -070021//! The `ParseStream`-based interface is convenient for parser implementations,
22//! but not necessarily when you just have some tokens that you want to parse.
23//! For that we expose the following two entry points.
David Tolnay80a914f2018-08-30 23:49:53 -070024//!
25//! ## The `syn::parse*` functions
26//!
27//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
28//! as an entry point for parsing syntax tree nodes that can be parsed in an
29//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -070030//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -070031//!
32//! [`syn::parse`]: ../fn.parse.html
33//! [`syn::parse2`]: ../fn.parse2.html
34//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -070035//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -070036//!
37//! ```
38//! use syn::Type;
39//!
David Tolnay8aacee12018-08-31 09:15:15 -070040//! # fn run_parser() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -070041//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
42//! # Ok(())
43//! # }
44//! #
45//! # fn main() {
46//! # run_parser().unwrap();
47//! # }
48//! ```
49//!
50//! The [`parse_quote!`] macro also uses this approach.
51//!
52//! [`parse_quote!`]: ../macro.parse_quote.html
53//!
54//! ## The `Parser` trait
55//!
56//! Some types can be parsed in several ways depending on context. For example
57//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
58//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
59//! may or may not allow trailing punctuation, and parsing it the wrong way
60//! would either reject valid input or accept invalid input.
61//!
62//! [`Attribute`]: ../struct.Attribute.html
63//! [`Punctuated`]: ../punctuated/index.html
64//!
David Tolnaye0c51762018-08-31 11:05:22 -070065//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -070066//! behavior to consider the default.
67//!
68//! ```ignore
69//! // Can't parse `Punctuated` without knowing whether trailing punctuation
70//! // should be allowed in this context.
71//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
72//! ```
73//!
74//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -070075//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -070076//! through the [`Parser`] trait.
77//!
78//! [`Parser`]: trait.Parser.html
79//!
80//! ```
David Tolnay80a914f2018-08-30 23:49:53 -070081//! # extern crate syn;
82//! #
83//! # extern crate proc_macro2;
84//! # use proc_macro2::TokenStream;
85//! #
David Tolnay3e3f7752018-08-31 09:33:59 -070086//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -070087//! use syn::punctuated::Punctuated;
David Tolnay9b00f652018-09-01 10:31:02 -070088//! use syn::{Attribute, Expr, PathSegment, Token};
David Tolnay80a914f2018-08-30 23:49:53 -070089//!
David Tolnay3e3f7752018-08-31 09:33:59 -070090//! # fn run_parsers() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -070091//! # let tokens = TokenStream::new().into();
92//! // Parse a nonempty sequence of path segments separated by `::` punctuation
93//! // with no trailing punctuation.
94//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
95//! let path = parser.parse(tokens)?;
96//!
97//! # let tokens = TokenStream::new().into();
98//! // Parse a possibly empty sequence of expressions terminated by commas with
99//! // an optional trailing punctuation.
100//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
101//! let args = parser.parse(tokens)?;
102//!
103//! # let tokens = TokenStream::new().into();
104//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700105//! let parser = Attribute::parse_outer;
106//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700107//! #
108//! # Ok(())
109//! # }
110//! #
111//! # fn main() {}
112//! ```
113//!
David Tolnaye0c51762018-08-31 11:05:22 -0700114//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700115//!
116//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400117
118use std::cell::Cell;
119use std::fmt::Display;
120use std::marker::PhantomData;
121use std::mem;
122use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400123use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700124use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400125
David Tolnay80a914f2018-08-30 23:49:53 -0700126#[cfg(all(
127 not(all(target_arch = "wasm32", target_os = "unknown")),
128 feature = "proc-macro"
129))]
130use proc_macro;
David Tolnayf07b3342018-09-01 11:58:11 -0700131use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400132
David Tolnay80a914f2018-08-30 23:49:53 -0700133use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400134use error;
David Tolnay94f06632018-08-31 10:17:17 -0700135use lookahead;
136use private;
David Tolnay577d0332018-08-25 21:45:24 -0400137use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400138use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400139
David Tolnayb6254182018-08-25 08:44:54 -0400140pub use error::{Error, Result};
141pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400142
143/// Parsing interface implemented by all types that can be parsed in a default
144/// way from a token stream.
145pub trait Parse: Sized {
146 fn parse(input: ParseStream) -> Result<Self>;
147}
148
149/// Input to a Syn parser function.
David Tolnaya0daa482018-09-01 02:09:40 -0700150///
151/// See the methods of this type under the documentation of [`ParseBuffer`]. For
152/// an overview of parsing in Syn, refer to the [module documentation].
153///
154/// [module documentation]: index.html
David Tolnay18c754c2018-08-21 23:26:58 -0400155pub type ParseStream<'a> = &'a ParseBuffer<'a>;
156
157/// Cursor position within a buffered token stream.
David Tolnay18c754c2018-08-21 23:26:58 -0400158pub struct ParseBuffer<'a> {
159 scope: Span,
160 cell: Cell<Cursor<'static>>,
161 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400162 unexpected: Rc<Cell<Option<Span>>>,
163}
164
165impl<'a> Drop for ParseBuffer<'a> {
166 fn drop(&mut self) {
167 if !self.is_empty() && self.unexpected.get().is_none() {
168 self.unexpected.set(Some(self.cursor().span()));
169 }
170 }
David Tolnay18c754c2018-08-21 23:26:58 -0400171}
172
David Tolnay642832f2018-09-01 13:08:10 -0700173/// Cursor state associated with speculative parsing.
174///
175/// This type is the input of the closure provided to [`ParseStream::step`].
176///
177/// [`ParseStream::step`]: struct.ParseBuffer.html#method.step
David Tolnay9bd34392018-09-01 13:19:53 -0700178///
179/// # Example
180///
181/// ```
182/// # extern crate proc_macro2;
183/// # extern crate syn;
184/// #
185/// use proc_macro2::TokenTree;
186/// use syn::parse::{ParseStream, Result};
187///
188/// // This function advances the stream past the next occurrence of `@`. If
189/// // no `@` is present in the stream, the stream position is unchanged and
190/// // an error is returned.
191/// fn skip_past_next_at(input: ParseStream) -> Result<()> {
192/// input.step(|cursor| {
193/// let mut rest = *cursor;
194/// while let Some((tt, next)) = cursor.token_tree() {
195/// match tt {
196/// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
197/// return Ok(((), next));
198/// }
199/// _ => rest = next,
200/// }
201/// }
202/// Err(cursor.error("no `@` was found after this point"))
203/// })
204/// }
205/// #
206/// # fn main() {}
207/// ```
David Tolnay18c754c2018-08-21 23:26:58 -0400208#[derive(Copy, Clone)]
209pub struct StepCursor<'c, 'a> {
210 scope: Span,
211 cursor: Cursor<'c>,
212 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
213}
214
215impl<'c, 'a> Deref for StepCursor<'c, 'a> {
216 type Target = Cursor<'c>;
217
218 fn deref(&self) -> &Self::Target {
219 &self.cursor
220 }
221}
222
223impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700224 /// Triggers an error at the current position of the parse stream.
225 ///
226 /// The `ParseStream::step` invocation will return this same error without
227 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400228 pub fn error<T: Display>(self, message: T) -> Error {
229 error::new_at(self.scope, self.cursor, message)
230 }
231}
232
David Tolnay6ea3fdc2018-09-01 13:30:53 -0700233impl private {
234 pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> {
235 let _ = proof;
236 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
237 }
238}
239
David Tolnay66cb0c42018-08-31 09:01:30 -0700240fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700241 input
242 .step(|cursor| {
243 if let Some((_lifetime, rest)) = cursor.lifetime() {
244 Ok((true, rest))
245 } else if let Some((_token, rest)) = cursor.token_tree() {
246 Ok((true, rest))
247 } else {
248 Ok((false, *cursor))
249 }
250 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700251}
252
David Tolnay10951d52018-08-31 10:27:39 -0700253impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700254 pub fn new_parse_buffer(
255 scope: Span,
256 cursor: Cursor,
257 unexpected: Rc<Cell<Option<Span>>>,
258 ) -> ParseBuffer {
David Tolnay94f06632018-08-31 10:17:17 -0700259 let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) };
David Tolnay18c754c2018-08-21 23:26:58 -0400260 ParseBuffer {
261 scope: scope,
262 cell: Cell::new(extend),
263 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400264 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400265 }
266 }
267
David Tolnay94f06632018-08-31 10:17:17 -0700268 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
269 buffer.unexpected.clone()
270 }
271}
272
273impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700274 /// Parses a syntax tree node of type `T`, advancing the position of our
275 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400276 pub fn parse<T: Parse>(&self) -> Result<T> {
277 T::parse(self)
278 }
279
David Tolnay725e1c62018-09-01 12:07:25 -0700280 /// Calls the given parser function to parse a syntax tree node of type `T`
281 /// from this stream.
David Tolnay3a515a02018-08-25 21:08:27 -0400282 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
283 function(self)
284 }
285
David Tolnay725e1c62018-09-01 12:07:25 -0700286 /// Looks at the next token in the parse stream to determine whether it
287 /// matches the requested type of token.
288 ///
289 /// Does not advance the position of the parse stream.
David Tolnayb77c8b62018-08-25 16:39:41 -0400290 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700291 let _ = token;
292 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400293 }
294
David Tolnay725e1c62018-09-01 12:07:25 -0700295 /// Looks at the second-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400296 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400297 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700298 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400299 }
300
David Tolnay725e1c62018-09-01 12:07:25 -0700301 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400302 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400303 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700304 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400305 }
306
David Tolnay725e1c62018-09-01 12:07:25 -0700307 /// Parses zero or more occurrences of `T` separated by punctuation of type
308 /// `P`, with optional trailing punctuation.
309 ///
310 /// Parsing continues until the end of this parse stream. The entire content
311 /// of this parse stream must consist of `T` and `P`.
David Tolnay0abe65b2018-09-01 14:31:43 -0700312 ///
313 /// # Example
314 ///
315 /// ```rust
316 /// # extern crate quote;
317 /// # extern crate syn;
318 /// #
319 /// # use quote::quote;
320 /// #
321 /// use syn::{parenthesized, token, Ident, Token, Type};
322 /// use syn::parse::{Parse, ParseStream, Result};
323 /// use syn::punctuated::Punctuated;
324 ///
325 /// // Parse a simplified tuple struct syntax like:
326 /// //
327 /// // struct S(A, B);
328 /// struct TupleStruct {
329 /// struct_token: Token![struct],
330 /// ident: Ident,
331 /// paren_token: token::Paren,
332 /// fields: Punctuated<Type, Token![,]>,
333 /// semi_token: Token![;],
334 /// }
335 ///
336 /// impl Parse for TupleStruct {
337 /// fn parse(input: ParseStream) -> Result<Self> {
338 /// let content;
339 /// Ok(TupleStruct {
340 /// struct_token: input.parse()?,
341 /// ident: input.parse()?,
342 /// paren_token: parenthesized!(content in input),
343 /// fields: content.parse_terminated(Type::parse)?,
344 /// semi_token: input.parse()?,
345 /// })
346 /// }
347 /// }
348 /// #
349 /// # fn main() {
350 /// # let input = quote! {
351 /// # struct S(A, B);
352 /// # };
353 /// # syn::parse2::<TupleStruct>(input).unwrap();
354 /// # }
355 /// ```
David Tolnay577d0332018-08-25 21:45:24 -0400356 pub fn parse_terminated<T, P: Parse>(
357 &self,
358 parser: fn(ParseStream) -> Result<T>,
359 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700360 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400361 }
362
David Tolnay725e1c62018-09-01 12:07:25 -0700363 /// Returns whether there are tokens remaining in this stream.
364 ///
365 /// This method returns true at the end of the content of a set of
366 /// delimiters, as well as at the very end of the complete macro input.
David Tolnaycce6b5f2018-09-01 14:24:46 -0700367 ///
368 /// # Example
369 ///
370 /// ```rust
371 /// # extern crate syn;
372 /// #
373 /// use syn::{braced, token, Ident, Item, Token};
374 /// use syn::parse::{Parse, ParseStream, Result};
375 ///
376 /// // Parses a Rust `mod m { ... }` containing zero or more items.
377 /// struct Mod {
378 /// mod_token: Token![mod],
379 /// name: Ident,
380 /// brace_token: token::Brace,
381 /// items: Vec<Item>,
382 /// }
383 ///
384 /// impl Parse for Mod {
385 /// fn parse(input: ParseStream) -> Result<Self> {
386 /// let content;
387 /// Ok(Mod {
388 /// mod_token: input.parse()?,
389 /// name: input.parse()?,
390 /// brace_token: braced!(content in input),
391 /// items: {
392 /// let mut items = Vec::new();
393 /// while !content.is_empty() {
394 /// items.push(content.parse()?);
395 /// }
396 /// items
397 /// },
398 /// })
399 /// }
400 /// }
401 /// #
402 /// # fn main() {}
David Tolnayf5d30452018-09-01 02:29:04 -0700403 pub fn is_empty(&self) -> bool {
404 self.cursor().eof()
405 }
406
David Tolnay725e1c62018-09-01 12:07:25 -0700407 /// Constructs a helper for peeking at the next token in this stream and
408 /// building an error message if it is not one of a set of expected tokens.
David Tolnay2c77e772018-09-01 14:18:46 -0700409 ///
410 /// # Example
411 ///
412 /// ```
413 /// # extern crate syn;
414 /// #
415 /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Token, TypeParam};
416 /// use syn::parse::{Parse, ParseStream, Result};
417 ///
418 /// // A generic parameter, a single one of the comma-separated elements inside
419 /// // angle brackets in:
420 /// //
421 /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... }
422 /// //
423 /// // On invalid input, lookahead gives us a reasonable error message.
424 /// //
425 /// // error: expected one of: identifier, lifetime, `const`
426 /// // |
427 /// // 5 | fn f<!Sized>() {}
428 /// // | ^
429 /// enum GenericParam {
430 /// Type(TypeParam),
431 /// Lifetime(LifetimeDef),
432 /// Const(ConstParam),
433 /// }
434 ///
435 /// impl Parse for GenericParam {
436 /// fn parse(input: ParseStream) -> Result<Self> {
437 /// let lookahead = input.lookahead1();
438 /// if lookahead.peek(Ident) {
439 /// input.parse().map(GenericParam::Type)
440 /// } else if lookahead.peek(Lifetime) {
441 /// input.parse().map(GenericParam::Lifetime)
442 /// } else if lookahead.peek(Token![const]) {
443 /// input.parse().map(GenericParam::Const)
444 /// } else {
445 /// Err(lookahead.error())
446 /// }
447 /// }
448 /// }
449 /// #
450 /// # fn main() {}
451 /// ```
David Tolnayf5d30452018-09-01 02:29:04 -0700452 pub fn lookahead1(&self) -> Lookahead1<'a> {
453 lookahead::new(self.scope, self.cursor())
454 }
455
David Tolnay725e1c62018-09-01 12:07:25 -0700456 /// Forks a parse stream so that parsing tokens out of either the original
457 /// or the fork does not advance the position of the other.
458 ///
459 /// # Performance
460 ///
461 /// Forking a parse stream is a cheap fixed amount of work and does not
462 /// involve copying token buffers. Where you might hit performance problems
463 /// is if your macro ends up parsing a large amount of content more than
464 /// once.
465 ///
466 /// ```
467 /// # use syn::Expr;
468 /// # use syn::parse::{ParseStream, Result};
469 /// #
470 /// # fn bad(input: ParseStream) -> Result<Expr> {
471 /// // Do not do this.
472 /// if input.fork().parse::<Expr>().is_ok() {
473 /// return input.parse::<Expr>();
474 /// }
475 /// # unimplemented!()
476 /// # }
477 /// ```
478 ///
479 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
480 /// parse stream. Only use a fork when the amount of work performed against
481 /// the fork is small and bounded.
482 ///
David Tolnayec149b02018-09-01 14:17:28 -0700483 /// For a lower level but occasionally more performant way to perform
David Tolnay725e1c62018-09-01 12:07:25 -0700484 /// speculative parsing, consider using [`ParseStream::step`] instead.
485 ///
486 /// [`ParseStream::step`]: #method.step
David Tolnayec149b02018-09-01 14:17:28 -0700487 ///
488 /// # Example
489 ///
490 /// The parse implementation shown here parses possibly restricted `pub`
491 /// visibilities.
492 ///
493 /// - `pub`
494 /// - `pub(crate)`
495 /// - `pub(self)`
496 /// - `pub(super)`
497 /// - `pub(in some::path)`
498 ///
499 /// To handle the case of visibilities inside of tuple structs, the parser
500 /// needs to distinguish parentheses that specify visibility restrictions
501 /// from parentheses that form part of a tuple type.
502 ///
503 /// ```
504 /// # struct A;
505 /// # struct B;
506 /// # struct C;
507 /// #
508 /// struct S(pub(crate) A, pub (B, C));
509 /// ```
510 ///
511 /// In this example input the first tuple struct element of `S` has
512 /// `pub(crate)` visibility while the second tuple struct element has `pub`
513 /// visibility; the parentheses around `(B, C)` are part of the type rather
514 /// than part of a visibility restriction.
515 ///
516 /// The parser uses a forked parse stream to check the first token inside of
517 /// parentheses after the `pub` keyword. This is a small bounded amount of
518 /// work performed against the forked parse stream.
519 ///
520 /// ```
521 /// # extern crate syn;
522 /// #
523 /// use syn::{parenthesized, token, Ident, Path, Token};
524 /// use syn::ext::IdentExt;
525 /// use syn::parse::{Parse, ParseStream, Result};
526 ///
527 /// struct PubVisibility {
528 /// pub_token: Token![pub],
529 /// restricted: Option<Restricted>,
530 /// }
531 ///
532 /// struct Restricted {
533 /// paren_token: token::Paren,
534 /// in_token: Option<Token![in]>,
535 /// path: Path,
536 /// }
537 ///
538 /// impl Parse for PubVisibility {
539 /// fn parse(input: ParseStream) -> Result<Self> {
540 /// let pub_token: Token![pub] = input.parse()?;
541 ///
542 /// if input.peek(token::Paren) {
543 /// let ahead = input.fork();
544 /// let mut content;
545 /// parenthesized!(content in ahead);
546 ///
547 /// if content.peek(Token![crate])
548 /// || content.peek(Token![self])
549 /// || content.peek(Token![super])
550 /// {
551 /// return Ok(PubVisibility {
552 /// pub_token: pub_token,
553 /// restricted: Some(Restricted {
554 /// paren_token: parenthesized!(content in input),
555 /// in_token: None,
556 /// path: Path::from(content.call(Ident::parse_any)?),
557 /// }),
558 /// });
559 /// } else if content.peek(Token![in]) {
560 /// return Ok(PubVisibility {
561 /// pub_token: pub_token,
562 /// restricted: Some(Restricted {
563 /// paren_token: parenthesized!(content in input),
564 /// in_token: Some(content.parse()?),
565 /// path: content.call(Path::parse_mod_style)?,
566 /// }),
567 /// });
568 /// }
569 /// }
570 ///
571 /// Ok(PubVisibility {
572 /// pub_token: pub_token,
573 /// restricted: None,
574 /// })
575 /// }
576 /// }
577 /// #
578 /// # fn main() {}
579 /// ```
David Tolnayb77c8b62018-08-25 16:39:41 -0400580 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400581 ParseBuffer {
582 scope: self.scope,
583 cell: self.cell.clone(),
584 marker: PhantomData,
585 // Not the parent's unexpected. Nothing cares whether the clone
586 // parses all the way.
587 unexpected: Rc::new(Cell::new(None)),
588 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400589 }
590
David Tolnay725e1c62018-09-01 12:07:25 -0700591 /// Triggers an error at the current position of the parse stream.
David Tolnay23fce0b2018-09-01 13:50:31 -0700592 ///
593 /// # Example
594 ///
595 /// ```
596 /// # extern crate syn;
597 /// #
598 /// use syn::{Expr, Token};
599 /// use syn::parse::{Parse, ParseStream, Result};
600 ///
601 /// // Some kind of loop: `while` or `for` or `loop`.
602 /// struct Loop {
603 /// expr: Expr,
604 /// }
605 ///
606 /// impl Parse for Loop {
607 /// fn parse(input: ParseStream) -> Result<Self> {
608 /// if input.peek(Token![while])
609 /// || input.peek(Token![for])
610 /// || input.peek(Token![loop])
611 /// {
612 /// Ok(Loop {
613 /// expr: input.parse()?,
614 /// })
615 /// } else {
616 /// Err(input.error("expected some kind of loop"))
617 /// }
618 /// }
619 /// }
620 /// ```
David Tolnay4fb71232018-08-25 23:14:50 -0400621 pub fn error<T: Display>(&self, message: T) -> Error {
622 error::new_at(self.scope, self.cursor(), message)
623 }
624
David Tolnay725e1c62018-09-01 12:07:25 -0700625 /// Speculatively parses tokens from this parse stream, advancing the
626 /// position of this stream only if parsing succeeds.
David Tolnay9bd34392018-09-01 13:19:53 -0700627 ///
David Tolnayad1d1d22018-09-01 13:34:43 -0700628 /// This is a powerful low-level API used for defining the `Parse` impls of
629 /// the basic built-in token types. It is not something that will be used
630 /// widely outside of the Syn codebase.
631 ///
David Tolnay9bd34392018-09-01 13:19:53 -0700632 /// # Example
633 ///
634 /// ```
635 /// # extern crate proc_macro2;
636 /// # extern crate syn;
637 /// #
638 /// use proc_macro2::TokenTree;
639 /// use syn::parse::{ParseStream, Result};
640 ///
641 /// // This function advances the stream past the next occurrence of `@`. If
642 /// // no `@` is present in the stream, the stream position is unchanged and
643 /// // an error is returned.
644 /// fn skip_past_next_at(input: ParseStream) -> Result<()> {
645 /// input.step(|cursor| {
646 /// let mut rest = *cursor;
647 /// while let Some((tt, next)) = cursor.token_tree() {
648 /// match tt {
649 /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => {
650 /// return Ok(((), next));
651 /// }
652 /// _ => rest = next,
653 /// }
654 /// }
655 /// Err(cursor.error("no `@` was found after this point"))
656 /// })
657 /// }
658 /// #
659 /// # fn main() {}
660 /// ```
David Tolnayb50c65a2018-08-30 21:14:57 -0700661 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400662 where
663 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
664 {
David Tolnay6b65f852018-09-01 11:56:25 -0700665 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400666 scope: self.scope,
667 cursor: self.cell.get(),
668 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700669 })?;
670 self.cell.set(rest);
671 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400672 }
David Tolnayeafc8052018-08-25 16:33:53 -0400673
David Tolnay725e1c62018-09-01 12:07:25 -0700674 /// Provides low-level access to the token representation underlying this
675 /// parse stream.
676 ///
677 /// Cursors are immutable so no operations you perform against the cursor
678 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700679 pub fn cursor(&self) -> Cursor<'a> {
680 self.cell.get()
681 }
682
David Tolnay94f06632018-08-31 10:17:17 -0700683 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400684 match self.unexpected.get() {
685 Some(span) => Err(Error::new(span, "unexpected token")),
686 None => Ok(()),
687 }
688 }
David Tolnay18c754c2018-08-21 23:26:58 -0400689}
690
David Tolnaya7d69fc2018-08-26 13:30:24 -0400691impl<T: Parse> Parse for Box<T> {
692 fn parse(input: ParseStream) -> Result<Self> {
693 input.parse().map(Box::new)
694 }
695}
696
David Tolnay4fb71232018-08-25 23:14:50 -0400697impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400698 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700699 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400700 Ok(Some(input.parse()?))
701 } else {
702 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400703 }
David Tolnay18c754c2018-08-21 23:26:58 -0400704 }
705}
David Tolnay4ac232d2018-08-31 10:18:03 -0700706
David Tolnay80a914f2018-08-30 23:49:53 -0700707impl Parse for TokenStream {
708 fn parse(input: ParseStream) -> Result<Self> {
709 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
710 }
711}
712
713impl Parse for TokenTree {
714 fn parse(input: ParseStream) -> Result<Self> {
715 input.step(|cursor| match cursor.token_tree() {
716 Some((tt, rest)) => Ok((tt, rest)),
717 None => Err(cursor.error("expected token tree")),
718 })
719 }
720}
721
722impl Parse for Group {
723 fn parse(input: ParseStream) -> Result<Self> {
724 input.step(|cursor| {
725 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
726 if let Some((inside, span, rest)) = cursor.group(*delim) {
727 let mut group = Group::new(*delim, inside.token_stream());
728 group.set_span(span);
729 return Ok((group, rest));
730 }
731 }
732 Err(cursor.error("expected group token"))
733 })
734 }
735}
736
737impl Parse for Punct {
738 fn parse(input: ParseStream) -> Result<Self> {
739 input.step(|cursor| match cursor.punct() {
740 Some((punct, rest)) => Ok((punct, rest)),
741 None => Err(cursor.error("expected punctuation token")),
742 })
743 }
744}
745
746impl Parse for Literal {
747 fn parse(input: ParseStream) -> Result<Self> {
748 input.step(|cursor| match cursor.literal() {
749 Some((literal, rest)) => Ok((literal, rest)),
750 None => Err(cursor.error("expected literal token")),
751 })
752 }
753}
754
755/// Parser that can parse Rust tokens into a particular syntax tree node.
756///
757/// Refer to the [module documentation] for details about parsing in Syn.
758///
759/// [module documentation]: index.html
760///
761/// *This trait is available if Syn is built with the `"parsing"` feature.*
762pub trait Parser: Sized {
763 type Output;
764
765 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
766 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
767
768 /// Parse tokens of source code into the chosen syntax tree node.
769 ///
770 /// *This method is available if Syn is built with both the `"parsing"` and
771 /// `"proc-macro"` features.*
772 #[cfg(all(
773 not(all(target_arch = "wasm32", target_os = "unknown")),
774 feature = "proc-macro"
775 ))]
776 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
777 self.parse2(proc_macro2::TokenStream::from(tokens))
778 }
779
780 /// Parse a string of Rust code into the chosen syntax tree node.
781 ///
782 /// # Hygiene
783 ///
784 /// Every span in the resulting syntax tree will be set to resolve at the
785 /// macro call site.
786 fn parse_str(self, s: &str) -> Result<Self::Output> {
787 self.parse2(proc_macro2::TokenStream::from_str(s)?)
788 }
789}
790
David Tolnay7b07aa12018-09-01 11:41:12 -0700791fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
792 let scope = Span::call_site();
793 let cursor = tokens.begin();
794 let unexpected = Rc::new(Cell::new(None));
795 private::new_parse_buffer(scope, cursor, unexpected)
796}
797
David Tolnay80a914f2018-08-30 23:49:53 -0700798impl<F, T> Parser for F
799where
800 F: FnOnce(ParseStream) -> Result<T>,
801{
802 type Output = T;
803
804 fn parse2(self, tokens: TokenStream) -> Result<T> {
805 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -0700806 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -0700807 let node = self(&state)?;
808 state.check_unexpected()?;
809 if state.is_empty() {
810 Ok(node)
811 } else {
812 Err(state.error("unexpected token"))
813 }
814 }
815}