blob: da54c240f76daf4ee7cbb1fedb7fd482a2262188 [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 Tolnay18c754c2018-08-21 23:26:58 -0400178#[derive(Copy, Clone)]
179pub struct StepCursor<'c, 'a> {
180 scope: Span,
181 cursor: Cursor<'c>,
182 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
183}
184
185impl<'c, 'a> Deref for StepCursor<'c, 'a> {
186 type Target = Cursor<'c>;
187
188 fn deref(&self) -> &Self::Target {
189 &self.cursor
190 }
191}
192
193impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay642832f2018-09-01 13:08:10 -0700194 /// Produces a cursor suitable for returning within the `R` return value of
195 /// a `ParseStream::step` invocation.
196 ///
197 /// # Performance
198 ///
199 /// This method performs a very small fixed amount of work independent of
200 /// the distance between `to` and the prior position of the stream.
201 pub fn advance(self, to: Cursor<'c>) -> Cursor<'a> {
202 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) }
David Tolnay18c754c2018-08-21 23:26:58 -0400203 }
204
David Tolnay642832f2018-09-01 13:08:10 -0700205 /// Triggers an error at the current position of the parse stream.
206 ///
207 /// The `ParseStream::step` invocation will return this same error without
208 /// advancing the stream state.
David Tolnay18c754c2018-08-21 23:26:58 -0400209 pub fn error<T: Display>(self, message: T) -> Error {
210 error::new_at(self.scope, self.cursor, message)
211 }
212}
213
David Tolnay66cb0c42018-08-31 09:01:30 -0700214fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700215 input
216 .step(|cursor| {
217 if let Some((_lifetime, rest)) = cursor.lifetime() {
218 Ok((true, rest))
219 } else if let Some((_token, rest)) = cursor.token_tree() {
220 Ok((true, rest))
221 } else {
222 Ok((false, *cursor))
223 }
224 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700225}
226
David Tolnay10951d52018-08-31 10:27:39 -0700227impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700228 pub fn new_parse_buffer(
229 scope: Span,
230 cursor: Cursor,
231 unexpected: Rc<Cell<Option<Span>>>,
232 ) -> ParseBuffer {
David Tolnay94f06632018-08-31 10:17:17 -0700233 let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) };
David Tolnay18c754c2018-08-21 23:26:58 -0400234 ParseBuffer {
235 scope: scope,
236 cell: Cell::new(extend),
237 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400238 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400239 }
240 }
241
David Tolnay94f06632018-08-31 10:17:17 -0700242 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
243 buffer.unexpected.clone()
244 }
245}
246
247impl<'a> ParseBuffer<'a> {
David Tolnay725e1c62018-09-01 12:07:25 -0700248 /// Parses a syntax tree node of type `T`, advancing the position of our
249 /// parse stream past it.
David Tolnay18c754c2018-08-21 23:26:58 -0400250 pub fn parse<T: Parse>(&self) -> Result<T> {
251 T::parse(self)
252 }
253
David Tolnay725e1c62018-09-01 12:07:25 -0700254 /// Calls the given parser function to parse a syntax tree node of type `T`
255 /// from this stream.
David Tolnay3a515a02018-08-25 21:08:27 -0400256 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
257 function(self)
258 }
259
David Tolnay725e1c62018-09-01 12:07:25 -0700260 /// Looks at the next token in the parse stream to determine whether it
261 /// matches the requested type of token.
262 ///
263 /// Does not advance the position of the parse stream.
David Tolnayb77c8b62018-08-25 16:39:41 -0400264 pub fn peek<T: Peek>(&self, token: T) -> bool {
David Tolnay576779a2018-09-01 11:54:12 -0700265 let _ = token;
266 T::Token::peek(self.cursor())
David Tolnayb77c8b62018-08-25 16:39:41 -0400267 }
268
David Tolnay725e1c62018-09-01 12:07:25 -0700269 /// Looks at the second-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400270 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400271 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700272 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400273 }
274
David Tolnay725e1c62018-09-01 12:07:25 -0700275 /// Looks at the third-next token in the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400276 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400277 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700278 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400279 }
280
David Tolnay725e1c62018-09-01 12:07:25 -0700281 /// Parses zero or more occurrences of `T` separated by punctuation of type
282 /// `P`, with optional trailing punctuation.
283 ///
284 /// Parsing continues until the end of this parse stream. The entire content
285 /// of this parse stream must consist of `T` and `P`.
David Tolnay577d0332018-08-25 21:45:24 -0400286 pub fn parse_terminated<T, P: Parse>(
287 &self,
288 parser: fn(ParseStream) -> Result<T>,
289 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700290 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400291 }
292
David Tolnay725e1c62018-09-01 12:07:25 -0700293 /// Returns whether there are tokens remaining in this stream.
294 ///
295 /// This method returns true at the end of the content of a set of
296 /// delimiters, as well as at the very end of the complete macro input.
David Tolnayf5d30452018-09-01 02:29:04 -0700297 pub fn is_empty(&self) -> bool {
298 self.cursor().eof()
299 }
300
David Tolnay725e1c62018-09-01 12:07:25 -0700301 /// Constructs a helper for peeking at the next token in this stream and
302 /// building an error message if it is not one of a set of expected tokens.
David Tolnayf5d30452018-09-01 02:29:04 -0700303 pub fn lookahead1(&self) -> Lookahead1<'a> {
304 lookahead::new(self.scope, self.cursor())
305 }
306
David Tolnay725e1c62018-09-01 12:07:25 -0700307 /// Forks a parse stream so that parsing tokens out of either the original
308 /// or the fork does not advance the position of the other.
309 ///
310 /// # Performance
311 ///
312 /// Forking a parse stream is a cheap fixed amount of work and does not
313 /// involve copying token buffers. Where you might hit performance problems
314 /// is if your macro ends up parsing a large amount of content more than
315 /// once.
316 ///
317 /// ```
318 /// # use syn::Expr;
319 /// # use syn::parse::{ParseStream, Result};
320 /// #
321 /// # fn bad(input: ParseStream) -> Result<Expr> {
322 /// // Do not do this.
323 /// if input.fork().parse::<Expr>().is_ok() {
324 /// return input.parse::<Expr>();
325 /// }
326 /// # unimplemented!()
327 /// # }
328 /// ```
329 ///
330 /// As a rule, avoid parsing an unbounded amount of tokens out of a forked
331 /// parse stream. Only use a fork when the amount of work performed against
332 /// the fork is small and bounded.
333 ///
334 /// For a lower level but generally more performant way to perform
335 /// speculative parsing, consider using [`ParseStream::step`] instead.
336 ///
337 /// [`ParseStream::step`]: #method.step
David Tolnayb77c8b62018-08-25 16:39:41 -0400338 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400339 ParseBuffer {
340 scope: self.scope,
341 cell: self.cell.clone(),
342 marker: PhantomData,
343 // Not the parent's unexpected. Nothing cares whether the clone
344 // parses all the way.
345 unexpected: Rc::new(Cell::new(None)),
346 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400347 }
348
David Tolnay725e1c62018-09-01 12:07:25 -0700349 /// Triggers an error at the current position of the parse stream.
David Tolnay4fb71232018-08-25 23:14:50 -0400350 pub fn error<T: Display>(&self, message: T) -> Error {
351 error::new_at(self.scope, self.cursor(), message)
352 }
353
David Tolnay725e1c62018-09-01 12:07:25 -0700354 /// Speculatively parses tokens from this parse stream, advancing the
355 /// position of this stream only if parsing succeeds.
David Tolnayb50c65a2018-08-30 21:14:57 -0700356 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400357 where
358 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
359 {
David Tolnay6b65f852018-09-01 11:56:25 -0700360 let (node, rest) = function(StepCursor {
David Tolnay18c754c2018-08-21 23:26:58 -0400361 scope: self.scope,
362 cursor: self.cell.get(),
363 marker: PhantomData,
David Tolnay6b65f852018-09-01 11:56:25 -0700364 })?;
365 self.cell.set(rest);
366 Ok(node)
David Tolnay18c754c2018-08-21 23:26:58 -0400367 }
David Tolnayeafc8052018-08-25 16:33:53 -0400368
David Tolnay725e1c62018-09-01 12:07:25 -0700369 /// Provides low-level access to the token representation underlying this
370 /// parse stream.
371 ///
372 /// Cursors are immutable so no operations you perform against the cursor
373 /// will affect the state of this parse stream.
David Tolnayf5d30452018-09-01 02:29:04 -0700374 pub fn cursor(&self) -> Cursor<'a> {
375 self.cell.get()
376 }
377
David Tolnay94f06632018-08-31 10:17:17 -0700378 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400379 match self.unexpected.get() {
380 Some(span) => Err(Error::new(span, "unexpected token")),
381 None => Ok(()),
382 }
383 }
David Tolnay18c754c2018-08-21 23:26:58 -0400384}
385
David Tolnaya7d69fc2018-08-26 13:30:24 -0400386impl<T: Parse> Parse for Box<T> {
387 fn parse(input: ParseStream) -> Result<Self> {
388 input.parse().map(Box::new)
389 }
390}
391
David Tolnay4fb71232018-08-25 23:14:50 -0400392impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400393 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay00f81fd2018-09-01 10:50:12 -0700394 if T::peek(input.cursor()) {
David Tolnay4fb71232018-08-25 23:14:50 -0400395 Ok(Some(input.parse()?))
396 } else {
397 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400398 }
David Tolnay18c754c2018-08-21 23:26:58 -0400399 }
400}
David Tolnay4ac232d2018-08-31 10:18:03 -0700401
David Tolnay80a914f2018-08-30 23:49:53 -0700402impl Parse for TokenStream {
403 fn parse(input: ParseStream) -> Result<Self> {
404 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
405 }
406}
407
408impl Parse for TokenTree {
409 fn parse(input: ParseStream) -> Result<Self> {
410 input.step(|cursor| match cursor.token_tree() {
411 Some((tt, rest)) => Ok((tt, rest)),
412 None => Err(cursor.error("expected token tree")),
413 })
414 }
415}
416
417impl Parse for Group {
418 fn parse(input: ParseStream) -> Result<Self> {
419 input.step(|cursor| {
420 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
421 if let Some((inside, span, rest)) = cursor.group(*delim) {
422 let mut group = Group::new(*delim, inside.token_stream());
423 group.set_span(span);
424 return Ok((group, rest));
425 }
426 }
427 Err(cursor.error("expected group token"))
428 })
429 }
430}
431
432impl Parse for Punct {
433 fn parse(input: ParseStream) -> Result<Self> {
434 input.step(|cursor| match cursor.punct() {
435 Some((punct, rest)) => Ok((punct, rest)),
436 None => Err(cursor.error("expected punctuation token")),
437 })
438 }
439}
440
441impl Parse for Literal {
442 fn parse(input: ParseStream) -> Result<Self> {
443 input.step(|cursor| match cursor.literal() {
444 Some((literal, rest)) => Ok((literal, rest)),
445 None => Err(cursor.error("expected literal token")),
446 })
447 }
448}
449
450/// Parser that can parse Rust tokens into a particular syntax tree node.
451///
452/// Refer to the [module documentation] for details about parsing in Syn.
453///
454/// [module documentation]: index.html
455///
456/// *This trait is available if Syn is built with the `"parsing"` feature.*
457pub trait Parser: Sized {
458 type Output;
459
460 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
461 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
462
463 /// Parse tokens of source code into the chosen syntax tree node.
464 ///
465 /// *This method is available if Syn is built with both the `"parsing"` and
466 /// `"proc-macro"` features.*
467 #[cfg(all(
468 not(all(target_arch = "wasm32", target_os = "unknown")),
469 feature = "proc-macro"
470 ))]
471 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
472 self.parse2(proc_macro2::TokenStream::from(tokens))
473 }
474
475 /// Parse a string of Rust code into the chosen syntax tree node.
476 ///
477 /// # Hygiene
478 ///
479 /// Every span in the resulting syntax tree will be set to resolve at the
480 /// macro call site.
481 fn parse_str(self, s: &str) -> Result<Self::Output> {
482 self.parse2(proc_macro2::TokenStream::from_str(s)?)
483 }
484}
485
David Tolnay7b07aa12018-09-01 11:41:12 -0700486fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer {
487 let scope = Span::call_site();
488 let cursor = tokens.begin();
489 let unexpected = Rc::new(Cell::new(None));
490 private::new_parse_buffer(scope, cursor, unexpected)
491}
492
David Tolnay80a914f2018-08-30 23:49:53 -0700493impl<F, T> Parser for F
494where
495 F: FnOnce(ParseStream) -> Result<T>,
496{
497 type Output = T;
498
499 fn parse2(self, tokens: TokenStream) -> Result<T> {
500 let buf = TokenBuffer::new2(tokens);
David Tolnay7b07aa12018-09-01 11:41:12 -0700501 let state = tokens_to_parse_buffer(&buf);
David Tolnay80a914f2018-08-30 23:49:53 -0700502 let node = self(&state)?;
503 state.check_unexpected()?;
504 if state.is_empty() {
505 Ok(node)
506 } else {
507 Err(state.error("unexpected token"))
508 }
509 }
510}