David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1 | // 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 Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 9 | //! Parsing interface for parsing a token stream into a syntax tree node. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 10 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 11 | //! 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 Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 16 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 17 | //! [`ParseStream`]: type.ParseStream.html |
| 18 | //! [`Result<T>`]: type.Result.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 19 | //! [`Cursor`]: ../buffer/index.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 20 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 21 | //! # Example |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 22 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 23 | //! Here is a snippet of parsing code to get a feel for the style of the |
| 24 | //! library. We define data structures for a subset of Rust syntax including |
| 25 | //! enums (not shown) and structs, then provide implementations of the [`Parse`] |
| 26 | //! trait to parse these syntax tree data structures from a token stream. |
| 27 | //! |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 28 | //! Once `Parse` impls have been defined, they can be called conveniently from a |
David Tolnay | 8e6096a | 2018-09-06 02:14:47 -0700 | [diff] [blame] | 29 | //! procedural macro through [`parse_macro_input!`] as shown at the bottom of |
| 30 | //! the snippet. If the caller provides syntactically invalid input to the |
| 31 | //! procedural macro, they will receive a helpful compiler error message |
| 32 | //! pointing out the exact token that triggered the failure to parse. |
| 33 | //! |
| 34 | //! [`parse_macro_input!`]: ../macro.parse_macro_input.html |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 35 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 36 | //! ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 37 | //! #[macro_use] |
| 38 | //! extern crate syn; |
| 39 | //! |
| 40 | //! extern crate proc_macro; |
| 41 | //! |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 42 | //! use proc_macro::TokenStream; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 43 | //! use syn::{token, Field, Ident, Result}; |
| 44 | //! use syn::parse::{Parse, ParseStream}; |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 45 | //! use syn::punctuated::Punctuated; |
| 46 | //! |
| 47 | //! enum Item { |
| 48 | //! Struct(ItemStruct), |
| 49 | //! Enum(ItemEnum), |
| 50 | //! } |
| 51 | //! |
| 52 | //! struct ItemStruct { |
| 53 | //! struct_token: Token![struct], |
| 54 | //! ident: Ident, |
| 55 | //! brace_token: token::Brace, |
| 56 | //! fields: Punctuated<Field, Token![,]>, |
| 57 | //! } |
| 58 | //! # |
| 59 | //! # enum ItemEnum {} |
| 60 | //! |
| 61 | //! impl Parse for Item { |
| 62 | //! fn parse(input: ParseStream) -> Result<Self> { |
| 63 | //! let lookahead = input.lookahead1(); |
| 64 | //! if lookahead.peek(Token![struct]) { |
| 65 | //! input.parse().map(Item::Struct) |
| 66 | //! } else if lookahead.peek(Token![enum]) { |
| 67 | //! input.parse().map(Item::Enum) |
| 68 | //! } else { |
| 69 | //! Err(lookahead.error()) |
| 70 | //! } |
| 71 | //! } |
| 72 | //! } |
| 73 | //! |
| 74 | //! impl Parse for ItemStruct { |
| 75 | //! fn parse(input: ParseStream) -> Result<Self> { |
| 76 | //! let content; |
| 77 | //! Ok(ItemStruct { |
| 78 | //! struct_token: input.parse()?, |
| 79 | //! ident: input.parse()?, |
| 80 | //! brace_token: braced!(content in input), |
| 81 | //! fields: content.parse_terminated(Field::parse_named)?, |
| 82 | //! }) |
| 83 | //! } |
| 84 | //! } |
| 85 | //! # |
| 86 | //! # impl Parse for ItemEnum { |
| 87 | //! # fn parse(input: ParseStream) -> Result<Self> { |
| 88 | //! # unimplemented!() |
| 89 | //! # } |
| 90 | //! # } |
David Tolnay | 88d9f62 | 2018-09-01 17:52:33 -0700 | [diff] [blame] | 91 | //! |
| 92 | //! # const IGNORE: &str = stringify! { |
| 93 | //! #[proc_macro] |
| 94 | //! # }; |
| 95 | //! pub fn my_macro(tokens: TokenStream) -> TokenStream { |
| 96 | //! let input = parse_macro_input!(tokens as Item); |
| 97 | //! |
| 98 | //! /* ... */ |
| 99 | //! # "".parse().unwrap() |
| 100 | //! } |
| 101 | //! # |
| 102 | //! # fn main() {} |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 103 | //! ``` |
| 104 | //! |
| 105 | //! # The `syn::parse*` functions |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 106 | //! |
| 107 | //! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve |
| 108 | //! as an entry point for parsing syntax tree nodes that can be parsed in an |
| 109 | //! obvious default way. These functions can return any syntax tree node that |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 110 | //! implements the [`Parse`] trait, which includes most types in Syn. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 111 | //! |
| 112 | //! [`syn::parse`]: ../fn.parse.html |
| 113 | //! [`syn::parse2`]: ../fn.parse2.html |
| 114 | //! [`syn::parse_str`]: ../fn.parse_str.html |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 115 | //! [`Parse`]: trait.Parse.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 116 | //! |
| 117 | //! ``` |
| 118 | //! use syn::Type; |
| 119 | //! |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 120 | //! # fn run_parser() -> syn::Result<()> { |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 121 | //! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?; |
| 122 | //! # Ok(()) |
| 123 | //! # } |
| 124 | //! # |
| 125 | //! # fn main() { |
| 126 | //! # run_parser().unwrap(); |
| 127 | //! # } |
| 128 | //! ``` |
| 129 | //! |
| 130 | //! The [`parse_quote!`] macro also uses this approach. |
| 131 | //! |
| 132 | //! [`parse_quote!`]: ../macro.parse_quote.html |
| 133 | //! |
David Tolnay | 4398445 | 2018-09-01 17:43:56 -0700 | [diff] [blame] | 134 | //! # The `Parser` trait |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 135 | //! |
| 136 | //! Some types can be parsed in several ways depending on context. For example |
| 137 | //! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like |
| 138 | //! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`] |
| 139 | //! may or may not allow trailing punctuation, and parsing it the wrong way |
| 140 | //! would either reject valid input or accept invalid input. |
| 141 | //! |
| 142 | //! [`Attribute`]: ../struct.Attribute.html |
| 143 | //! [`Punctuated`]: ../punctuated/index.html |
| 144 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 145 | //! The `Parse` trait is not implemented in these cases because there is no good |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 146 | //! behavior to consider the default. |
| 147 | //! |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 148 | //! ```compile_fail |
| 149 | //! # extern crate proc_macro; |
| 150 | //! # extern crate syn; |
| 151 | //! # |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 152 | //! # use syn::punctuated::Punctuated; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 153 | //! # use syn::{PathSegment, Result, Token}; |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 154 | //! # |
| 155 | //! # fn f(tokens: proc_macro::TokenStream) -> Result<()> { |
| 156 | //! # |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 157 | //! // Can't parse `Punctuated` without knowing whether trailing punctuation |
| 158 | //! // should be allowed in this context. |
| 159 | //! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?; |
David Tolnay | 2b45fd4 | 2018-11-06 21:16:55 -0800 | [diff] [blame] | 160 | //! # |
| 161 | //! # Ok(()) |
| 162 | //! # } |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 163 | //! ``` |
| 164 | //! |
| 165 | //! In these cases the types provide a choice of parser functions rather than a |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 166 | //! single `Parse` implementation, and those parser functions can be invoked |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 167 | //! through the [`Parser`] trait. |
| 168 | //! |
| 169 | //! [`Parser`]: trait.Parser.html |
| 170 | //! |
| 171 | //! ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 172 | //! #[macro_use] |
| 173 | //! extern crate syn; |
| 174 | //! |
| 175 | //! extern crate proc_macro2; |
| 176 | //! |
| 177 | //! use proc_macro2::TokenStream; |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 178 | //! use syn::parse::Parser; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 179 | //! use syn::punctuated::Punctuated; |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 180 | //! use syn::{Attribute, Expr, PathSegment}; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 181 | //! |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 182 | //! # fn run_parsers() -> syn::Result<()> { |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 183 | //! # let tokens = TokenStream::new().into(); |
| 184 | //! // Parse a nonempty sequence of path segments separated by `::` punctuation |
| 185 | //! // with no trailing punctuation. |
| 186 | //! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty; |
| 187 | //! let path = parser.parse(tokens)?; |
| 188 | //! |
| 189 | //! # let tokens = TokenStream::new().into(); |
| 190 | //! // Parse a possibly empty sequence of expressions terminated by commas with |
| 191 | //! // an optional trailing punctuation. |
| 192 | //! let parser = Punctuated::<Expr, Token![,]>::parse_terminated; |
| 193 | //! let args = parser.parse(tokens)?; |
| 194 | //! |
| 195 | //! # let tokens = TokenStream::new().into(); |
| 196 | //! // Parse zero or more outer attributes but not inner attributes. |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 197 | //! let parser = Attribute::parse_outer; |
| 198 | //! let attrs = parser.parse(tokens)?; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 199 | //! # |
| 200 | //! # Ok(()) |
| 201 | //! # } |
| 202 | //! # |
| 203 | //! # fn main() {} |
| 204 | //! ``` |
| 205 | //! |
David Tolnay | e0c5176 | 2018-08-31 11:05:22 -0700 | [diff] [blame] | 206 | //! --- |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 207 | //! |
| 208 | //! *This module is available if Syn is built with the `"parsing"` feature.* |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 209 | |
| 210 | use std::cell::Cell; |
Diggory Hardy | 1c522e1 | 2018-11-02 10:10:02 +0000 | [diff] [blame] | 211 | use std::fmt::{self, Debug, Display}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 212 | use std::marker::PhantomData; |
| 213 | use std::mem; |
| 214 | use std::ops::Deref; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 215 | use std::rc::Rc; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 216 | use std::str::FromStr; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 217 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 218 | #[cfg(all( |
| 219 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 220 | feature = "proc-macro" |
| 221 | ))] |
| 222 | use proc_macro; |
David Tolnay | f07b334 | 2018-09-01 11:58:11 -0700 | [diff] [blame] | 223 | use proc_macro2::{self, Delimiter, Group, Literal, Punct, Span, TokenStream, TokenTree}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 224 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 225 | use buffer::{Cursor, TokenBuffer}; |
David Tolnay | b625418 | 2018-08-25 08:44:54 -0400 | [diff] [blame] | 226 | use error; |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 227 | use lookahead; |
| 228 | use private; |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 229 | use punctuated::Punctuated; |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 230 | use token::Token; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 231 | |
David Tolnay | b625418 | 2018-08-25 08:44:54 -0400 | [diff] [blame] | 232 | pub use error::{Error, Result}; |
| 233 | pub use lookahead::{Lookahead1, Peek}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 234 | |
| 235 | /// Parsing interface implemented by all types that can be parsed in a default |
| 236 | /// way from a token stream. |
| 237 | pub trait Parse: Sized { |
| 238 | fn parse(input: ParseStream) -> Result<Self>; |
| 239 | } |
| 240 | |
| 241 | /// Input to a Syn parser function. |
David Tolnay | a0daa48 | 2018-09-01 02:09:40 -0700 | [diff] [blame] | 242 | /// |
| 243 | /// See the methods of this type under the documentation of [`ParseBuffer`]. For |
| 244 | /// an overview of parsing in Syn, refer to the [module documentation]. |
| 245 | /// |
| 246 | /// [module documentation]: index.html |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 247 | pub type ParseStream<'a> = &'a ParseBuffer<'a>; |
| 248 | |
| 249 | /// Cursor position within a buffered token stream. |
David Tolnay | 20d29a1 | 2018-09-01 15:15:33 -0700 | [diff] [blame] | 250 | /// |
| 251 | /// This type is more commonly used through the type alias [`ParseStream`] which |
| 252 | /// is an alias for `&ParseBuffer`. |
| 253 | /// |
| 254 | /// `ParseStream` is the input type for all parser functions in Syn. They have |
| 255 | /// the signature `fn(ParseStream) -> Result<T>`. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 256 | pub struct ParseBuffer<'a> { |
| 257 | scope: Span, |
David Tolnay | 5d7f225 | 2018-09-02 08:21:40 -0700 | [diff] [blame] | 258 | // Instead of Cell<Cursor<'a>> so that ParseBuffer<'a> is covariant in 'a. |
| 259 | // The rest of the code in this module needs to be careful that only a |
| 260 | // cursor derived from this `cell` is ever assigned to this `cell`. |
| 261 | // |
| 262 | // Cell<Cursor<'a>> cannot be covariant in 'a because then we could take a |
| 263 | // ParseBuffer<'a>, upcast to ParseBuffer<'short> for some lifetime shorter |
| 264 | // than 'a, and then assign a Cursor<'short> into the Cell. |
| 265 | // |
| 266 | // By extension, it would not be safe to expose an API that accepts a |
| 267 | // Cursor<'a> and trusts that it lives as long as the cursor currently in |
| 268 | // the cell. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 269 | cell: Cell<Cursor<'static>>, |
| 270 | marker: PhantomData<Cursor<'a>>, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 271 | unexpected: Rc<Cell<Option<Span>>>, |
| 272 | } |
| 273 | |
| 274 | impl<'a> Drop for ParseBuffer<'a> { |
| 275 | fn drop(&mut self) { |
| 276 | if !self.is_empty() && self.unexpected.get().is_none() { |
| 277 | self.unexpected.set(Some(self.cursor().span())); |
| 278 | } |
| 279 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 280 | } |
| 281 | |
Diggory Hardy | 1c522e1 | 2018-11-02 10:10:02 +0000 | [diff] [blame] | 282 | impl<'a> Display for ParseBuffer<'a> { |
| 283 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 284 | Display::fmt(&self.cursor().token_stream(), f) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | impl<'a> Debug for ParseBuffer<'a> { |
| 289 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 290 | Debug::fmt(&self.cursor().token_stream(), f) |
| 291 | } |
| 292 | } |
| 293 | |
David Tolnay | 642832f | 2018-09-01 13:08:10 -0700 | [diff] [blame] | 294 | /// Cursor state associated with speculative parsing. |
| 295 | /// |
| 296 | /// This type is the input of the closure provided to [`ParseStream::step`]. |
| 297 | /// |
| 298 | /// [`ParseStream::step`]: struct.ParseBuffer.html#method.step |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 299 | /// |
| 300 | /// # Example |
| 301 | /// |
| 302 | /// ``` |
| 303 | /// # extern crate proc_macro2; |
| 304 | /// # extern crate syn; |
| 305 | /// # |
| 306 | /// use proc_macro2::TokenTree; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 307 | /// use syn::Result; |
| 308 | /// use syn::parse::ParseStream; |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 309 | /// |
| 310 | /// // This function advances the stream past the next occurrence of `@`. If |
| 311 | /// // no `@` is present in the stream, the stream position is unchanged and |
| 312 | /// // an error is returned. |
| 313 | /// fn skip_past_next_at(input: ParseStream) -> Result<()> { |
| 314 | /// input.step(|cursor| { |
| 315 | /// let mut rest = *cursor; |
Sharad Chand | e1df40a | 2018-09-08 15:25:52 +0545 | [diff] [blame] | 316 | /// while let Some((tt, next)) = rest.token_tree() { |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 317 | /// match tt { |
| 318 | /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => { |
| 319 | /// return Ok(((), next)); |
| 320 | /// } |
| 321 | /// _ => rest = next, |
| 322 | /// } |
| 323 | /// } |
| 324 | /// Err(cursor.error("no `@` was found after this point")) |
| 325 | /// }) |
| 326 | /// } |
| 327 | /// # |
David Tolnay | db31258 | 2018-11-06 20:42:05 -0800 | [diff] [blame] | 328 | /// # |
| 329 | /// # fn remainder_after_skipping_past_next_at( |
| 330 | /// # input: ParseStream, |
| 331 | /// # ) -> Result<proc_macro2::TokenStream> { |
| 332 | /// # skip_past_next_at(input)?; |
| 333 | /// # input.parse() |
| 334 | /// # } |
| 335 | /// # |
| 336 | /// # fn main() { |
| 337 | /// # use syn::parse::Parser; |
| 338 | /// # let remainder = remainder_after_skipping_past_next_at |
| 339 | /// # .parse_str("a @ b c") |
| 340 | /// # .unwrap(); |
| 341 | /// # assert_eq!(remainder.to_string(), "b c"); |
| 342 | /// # } |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 343 | /// ``` |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 344 | #[derive(Copy, Clone)] |
| 345 | pub struct StepCursor<'c, 'a> { |
| 346 | scope: Span, |
David Tolnay | 56924f4 | 2018-09-02 08:24:58 -0700 | [diff] [blame] | 347 | // This field is covariant in 'c. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 348 | cursor: Cursor<'c>, |
David Tolnay | 56924f4 | 2018-09-02 08:24:58 -0700 | [diff] [blame] | 349 | // This field is contravariant in 'c. Together these make StepCursor |
| 350 | // invariant in 'c. Also covariant in 'a. The user cannot cast 'c to a |
| 351 | // different lifetime but can upcast into a StepCursor with a shorter |
| 352 | // lifetime 'a. |
| 353 | // |
| 354 | // As long as we only ever construct a StepCursor for which 'c outlives 'a, |
| 355 | // this means if ever a StepCursor<'c, 'a> exists we are guaranteed that 'c |
| 356 | // outlives 'a. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 357 | marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>, |
| 358 | } |
| 359 | |
| 360 | impl<'c, 'a> Deref for StepCursor<'c, 'a> { |
| 361 | type Target = Cursor<'c>; |
| 362 | |
| 363 | fn deref(&self) -> &Self::Target { |
| 364 | &self.cursor |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | impl<'c, 'a> StepCursor<'c, 'a> { |
David Tolnay | 642832f | 2018-09-01 13:08:10 -0700 | [diff] [blame] | 369 | /// Triggers an error at the current position of the parse stream. |
| 370 | /// |
| 371 | /// The `ParseStream::step` invocation will return this same error without |
| 372 | /// advancing the stream state. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 373 | pub fn error<T: Display>(self, message: T) -> Error { |
| 374 | error::new_at(self.scope, self.cursor, message) |
| 375 | } |
| 376 | } |
| 377 | |
David Tolnay | 6ea3fdc | 2018-09-01 13:30:53 -0700 | [diff] [blame] | 378 | impl private { |
| 379 | pub fn advance_step_cursor<'c, 'a>(proof: StepCursor<'c, 'a>, to: Cursor<'c>) -> Cursor<'a> { |
David Tolnay | 56924f4 | 2018-09-02 08:24:58 -0700 | [diff] [blame] | 380 | // Refer to the comments within the StepCursor definition. We use the |
| 381 | // fact that a StepCursor<'c, 'a> exists as proof that 'c outlives 'a. |
| 382 | // Cursor is covariant in its lifetime parameter so we can cast a |
| 383 | // Cursor<'c> to one with the shorter lifetime Cursor<'a>. |
David Tolnay | 6ea3fdc | 2018-09-01 13:30:53 -0700 | [diff] [blame] | 384 | let _ = proof; |
| 385 | unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(to) } |
| 386 | } |
| 387 | } |
| 388 | |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 389 | fn skip(input: ParseStream) -> bool { |
David Tolnay | 4ac232d | 2018-08-31 10:18:03 -0700 | [diff] [blame] | 390 | input |
| 391 | .step(|cursor| { |
| 392 | if let Some((_lifetime, rest)) = cursor.lifetime() { |
| 393 | Ok((true, rest)) |
| 394 | } else if let Some((_token, rest)) = cursor.token_tree() { |
| 395 | Ok((true, rest)) |
| 396 | } else { |
| 397 | Ok((false, *cursor)) |
| 398 | } |
David Tolnay | fb84fc0 | 2018-10-02 21:01:30 -0700 | [diff] [blame] | 399 | }) |
| 400 | .unwrap() |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 401 | } |
| 402 | |
David Tolnay | 10951d5 | 2018-08-31 10:27:39 -0700 | [diff] [blame] | 403 | impl private { |
David Tolnay | 70f30e9 | 2018-09-01 02:04:17 -0700 | [diff] [blame] | 404 | pub fn new_parse_buffer( |
| 405 | scope: Span, |
| 406 | cursor: Cursor, |
| 407 | unexpected: Rc<Cell<Option<Span>>>, |
| 408 | ) -> ParseBuffer { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 409 | ParseBuffer { |
| 410 | scope: scope, |
David Tolnay | 5d7f225 | 2018-09-02 08:21:40 -0700 | [diff] [blame] | 411 | // See comment on `cell` in the struct definition. |
| 412 | cell: Cell::new(unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }), |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 413 | marker: PhantomData, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 414 | unexpected: unexpected, |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 415 | } |
| 416 | } |
| 417 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 418 | pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> { |
| 419 | buffer.unexpected.clone() |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | impl<'a> ParseBuffer<'a> { |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 424 | /// Parses a syntax tree node of type `T`, advancing the position of our |
| 425 | /// parse stream past it. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 426 | pub fn parse<T: Parse>(&self) -> Result<T> { |
| 427 | T::parse(self) |
| 428 | } |
| 429 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 430 | /// Calls the given parser function to parse a syntax tree node of type `T` |
| 431 | /// from this stream. |
David Tolnay | 21ce84c | 2018-09-01 15:37:51 -0700 | [diff] [blame] | 432 | /// |
| 433 | /// # Example |
| 434 | /// |
| 435 | /// The parser below invokes [`Attribute::parse_outer`] to parse a vector of |
| 436 | /// zero or more outer attributes. |
| 437 | /// |
| 438 | /// [`Attribute::parse_outer`]: ../struct.Attribute.html#method.parse_outer |
| 439 | /// |
| 440 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 441 | /// #[macro_use] |
| 442 | /// extern crate syn; |
| 443 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 444 | /// use syn::{Attribute, Ident, Result}; |
| 445 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 21ce84c | 2018-09-01 15:37:51 -0700 | [diff] [blame] | 446 | /// |
| 447 | /// // Parses a unit struct with attributes. |
| 448 | /// // |
| 449 | /// // #[path = "s.tmpl"] |
| 450 | /// // struct S; |
| 451 | /// struct UnitStruct { |
| 452 | /// attrs: Vec<Attribute>, |
| 453 | /// struct_token: Token![struct], |
| 454 | /// name: Ident, |
| 455 | /// semi_token: Token![;], |
| 456 | /// } |
| 457 | /// |
| 458 | /// impl Parse for UnitStruct { |
| 459 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 460 | /// Ok(UnitStruct { |
| 461 | /// attrs: input.call(Attribute::parse_outer)?, |
| 462 | /// struct_token: input.parse()?, |
| 463 | /// name: input.parse()?, |
| 464 | /// semi_token: input.parse()?, |
| 465 | /// }) |
| 466 | /// } |
| 467 | /// } |
| 468 | /// # |
| 469 | /// # fn main() {} |
| 470 | /// ``` |
David Tolnay | 3a515a0 | 2018-08-25 21:08:27 -0400 | [diff] [blame] | 471 | pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> { |
| 472 | function(self) |
| 473 | } |
| 474 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 475 | /// Looks at the next token in the parse stream to determine whether it |
| 476 | /// matches the requested type of token. |
| 477 | /// |
| 478 | /// Does not advance the position of the parse stream. |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 479 | /// |
David Tolnay | 7d229e8 | 2018-09-01 16:42:34 -0700 | [diff] [blame] | 480 | /// # Syntax |
| 481 | /// |
| 482 | /// Note that this method does not use turbofish syntax. Pass the peek type |
| 483 | /// inside of parentheses. |
| 484 | /// |
| 485 | /// - `input.peek(Token![struct])` |
| 486 | /// - `input.peek(Token![==])` |
| 487 | /// - `input.peek(Ident)` |
| 488 | /// - `input.peek(Lifetime)` |
| 489 | /// - `input.peek(token::Brace)` |
| 490 | /// |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 491 | /// # Example |
| 492 | /// |
| 493 | /// In this example we finish parsing the list of supertraits when the next |
| 494 | /// token in the input is either `where` or an opening curly brace. |
| 495 | /// |
| 496 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 497 | /// #[macro_use] |
| 498 | /// extern crate syn; |
| 499 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 500 | /// use syn::{token, Generics, Ident, Result, TypeParamBound}; |
| 501 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | ddebc3e | 2018-09-01 16:29:20 -0700 | [diff] [blame] | 502 | /// use syn::punctuated::Punctuated; |
| 503 | /// |
| 504 | /// // Parses a trait definition containing no associated items. |
| 505 | /// // |
| 506 | /// // trait Marker<'de, T>: A + B<'de> where Box<T>: Clone {} |
| 507 | /// struct MarkerTrait { |
| 508 | /// trait_token: Token![trait], |
| 509 | /// ident: Ident, |
| 510 | /// generics: Generics, |
| 511 | /// colon_token: Option<Token![:]>, |
| 512 | /// supertraits: Punctuated<TypeParamBound, Token![+]>, |
| 513 | /// brace_token: token::Brace, |
| 514 | /// } |
| 515 | /// |
| 516 | /// impl Parse for MarkerTrait { |
| 517 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 518 | /// let trait_token: Token![trait] = input.parse()?; |
| 519 | /// let ident: Ident = input.parse()?; |
| 520 | /// let mut generics: Generics = input.parse()?; |
| 521 | /// let colon_token: Option<Token![:]> = input.parse()?; |
| 522 | /// |
| 523 | /// let mut supertraits = Punctuated::new(); |
| 524 | /// if colon_token.is_some() { |
| 525 | /// loop { |
| 526 | /// supertraits.push_value(input.parse()?); |
| 527 | /// if input.peek(Token![where]) || input.peek(token::Brace) { |
| 528 | /// break; |
| 529 | /// } |
| 530 | /// supertraits.push_punct(input.parse()?); |
| 531 | /// } |
| 532 | /// } |
| 533 | /// |
| 534 | /// generics.where_clause = input.parse()?; |
| 535 | /// let content; |
| 536 | /// let empty_brace_token = braced!(content in input); |
| 537 | /// |
| 538 | /// Ok(MarkerTrait { |
| 539 | /// trait_token: trait_token, |
| 540 | /// ident: ident, |
| 541 | /// generics: generics, |
| 542 | /// colon_token: colon_token, |
| 543 | /// supertraits: supertraits, |
| 544 | /// brace_token: empty_brace_token, |
| 545 | /// }) |
| 546 | /// } |
| 547 | /// } |
| 548 | /// # |
| 549 | /// # fn main() {} |
| 550 | /// ``` |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 551 | pub fn peek<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 576779a | 2018-09-01 11:54:12 -0700 | [diff] [blame] | 552 | let _ = token; |
| 553 | T::Token::peek(self.cursor()) |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 554 | } |
| 555 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 556 | /// Looks at the second-next token in the parse stream. |
David Tolnay | e334b87 | 2018-09-01 16:38:10 -0700 | [diff] [blame] | 557 | /// |
| 558 | /// This is commonly useful as a way to implement contextual keywords. |
| 559 | /// |
| 560 | /// # Example |
| 561 | /// |
| 562 | /// This example needs to use `peek2` because the symbol `union` is not a |
| 563 | /// keyword in Rust. We can't use just `peek` and decide to parse a union if |
| 564 | /// the very next token is `union`, because someone is free to write a `mod |
| 565 | /// union` and a macro invocation that looks like `union::some_macro! { ... |
| 566 | /// }`. In other words `union` is a contextual keyword. |
| 567 | /// |
| 568 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 569 | /// #[macro_use] |
| 570 | /// extern crate syn; |
| 571 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 572 | /// use syn::{Ident, ItemUnion, Macro, Result}; |
| 573 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | e334b87 | 2018-09-01 16:38:10 -0700 | [diff] [blame] | 574 | /// |
| 575 | /// // Parses either a union or a macro invocation. |
| 576 | /// enum UnionOrMacro { |
| 577 | /// // union MaybeUninit<T> { uninit: (), value: T } |
| 578 | /// Union(ItemUnion), |
| 579 | /// // lazy_static! { ... } |
| 580 | /// Macro(Macro), |
| 581 | /// } |
| 582 | /// |
| 583 | /// impl Parse for UnionOrMacro { |
| 584 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 585 | /// if input.peek(Token![union]) && input.peek2(Ident) { |
| 586 | /// input.parse().map(UnionOrMacro::Union) |
| 587 | /// } else { |
| 588 | /// input.parse().map(UnionOrMacro::Macro) |
| 589 | /// } |
| 590 | /// } |
| 591 | /// } |
| 592 | /// # |
| 593 | /// # fn main() {} |
| 594 | /// ``` |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 595 | pub fn peek2<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 596 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 597 | skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 598 | } |
| 599 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 600 | /// Looks at the third-next token in the parse stream. |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 601 | pub fn peek3<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 602 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 603 | skip(&ahead) && skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 604 | } |
| 605 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 606 | /// Parses zero or more occurrences of `T` separated by punctuation of type |
| 607 | /// `P`, with optional trailing punctuation. |
| 608 | /// |
| 609 | /// Parsing continues until the end of this parse stream. The entire content |
| 610 | /// of this parse stream must consist of `T` and `P`. |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 611 | /// |
| 612 | /// # Example |
| 613 | /// |
| 614 | /// ```rust |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 615 | /// # #[macro_use] |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 616 | /// # extern crate quote; |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 617 | /// # |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 618 | /// #[macro_use] |
| 619 | /// extern crate syn; |
| 620 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 621 | /// use syn::{token, Ident, Result, Type}; |
| 622 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 0abe65b | 2018-09-01 14:31:43 -0700 | [diff] [blame] | 623 | /// use syn::punctuated::Punctuated; |
| 624 | /// |
| 625 | /// // Parse a simplified tuple struct syntax like: |
| 626 | /// // |
| 627 | /// // struct S(A, B); |
| 628 | /// struct TupleStruct { |
| 629 | /// struct_token: Token![struct], |
| 630 | /// ident: Ident, |
| 631 | /// paren_token: token::Paren, |
| 632 | /// fields: Punctuated<Type, Token![,]>, |
| 633 | /// semi_token: Token![;], |
| 634 | /// } |
| 635 | /// |
| 636 | /// impl Parse for TupleStruct { |
| 637 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 638 | /// let content; |
| 639 | /// Ok(TupleStruct { |
| 640 | /// struct_token: input.parse()?, |
| 641 | /// ident: input.parse()?, |
| 642 | /// paren_token: parenthesized!(content in input), |
| 643 | /// fields: content.parse_terminated(Type::parse)?, |
| 644 | /// semi_token: input.parse()?, |
| 645 | /// }) |
| 646 | /// } |
| 647 | /// } |
| 648 | /// # |
| 649 | /// # fn main() { |
| 650 | /// # let input = quote! { |
| 651 | /// # struct S(A, B); |
| 652 | /// # }; |
| 653 | /// # syn::parse2::<TupleStruct>(input).unwrap(); |
| 654 | /// # } |
| 655 | /// ``` |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 656 | pub fn parse_terminated<T, P: Parse>( |
| 657 | &self, |
| 658 | parser: fn(ParseStream) -> Result<T>, |
| 659 | ) -> Result<Punctuated<T, P>> { |
David Tolnay | d0f8021 | 2018-08-30 18:32:14 -0700 | [diff] [blame] | 660 | Punctuated::parse_terminated_with(self, parser) |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 661 | } |
| 662 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 663 | /// Returns whether there are tokens remaining in this stream. |
| 664 | /// |
| 665 | /// This method returns true at the end of the content of a set of |
| 666 | /// delimiters, as well as at the very end of the complete macro input. |
David Tolnay | cce6b5f | 2018-09-01 14:24:46 -0700 | [diff] [blame] | 667 | /// |
| 668 | /// # Example |
| 669 | /// |
| 670 | /// ```rust |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 671 | /// #[macro_use] |
| 672 | /// extern crate syn; |
| 673 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 674 | /// use syn::{token, Ident, Item, Result}; |
| 675 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | cce6b5f | 2018-09-01 14:24:46 -0700 | [diff] [blame] | 676 | /// |
| 677 | /// // Parses a Rust `mod m { ... }` containing zero or more items. |
| 678 | /// struct Mod { |
| 679 | /// mod_token: Token![mod], |
| 680 | /// name: Ident, |
| 681 | /// brace_token: token::Brace, |
| 682 | /// items: Vec<Item>, |
| 683 | /// } |
| 684 | /// |
| 685 | /// impl Parse for Mod { |
| 686 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 687 | /// let content; |
| 688 | /// Ok(Mod { |
| 689 | /// mod_token: input.parse()?, |
| 690 | /// name: input.parse()?, |
| 691 | /// brace_token: braced!(content in input), |
| 692 | /// items: { |
| 693 | /// let mut items = Vec::new(); |
| 694 | /// while !content.is_empty() { |
| 695 | /// items.push(content.parse()?); |
| 696 | /// } |
| 697 | /// items |
| 698 | /// }, |
| 699 | /// }) |
| 700 | /// } |
| 701 | /// } |
| 702 | /// # |
| 703 | /// # fn main() {} |
David Tolnay | f2b7860 | 2018-11-06 20:42:37 -0800 | [diff] [blame] | 704 | /// ``` |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 705 | pub fn is_empty(&self) -> bool { |
| 706 | self.cursor().eof() |
| 707 | } |
| 708 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 709 | /// Constructs a helper for peeking at the next token in this stream and |
| 710 | /// building an error message if it is not one of a set of expected tokens. |
David Tolnay | 2c77e77 | 2018-09-01 14:18:46 -0700 | [diff] [blame] | 711 | /// |
| 712 | /// # Example |
| 713 | /// |
| 714 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 715 | /// #[macro_use] |
| 716 | /// extern crate syn; |
| 717 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 718 | /// use syn::{ConstParam, Ident, Lifetime, LifetimeDef, Result, TypeParam}; |
| 719 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 2c77e77 | 2018-09-01 14:18:46 -0700 | [diff] [blame] | 720 | /// |
| 721 | /// // A generic parameter, a single one of the comma-separated elements inside |
| 722 | /// // angle brackets in: |
| 723 | /// // |
| 724 | /// // fn f<T: Clone, 'a, 'b: 'a, const N: usize>() { ... } |
| 725 | /// // |
| 726 | /// // On invalid input, lookahead gives us a reasonable error message. |
| 727 | /// // |
| 728 | /// // error: expected one of: identifier, lifetime, `const` |
| 729 | /// // | |
| 730 | /// // 5 | fn f<!Sized>() {} |
| 731 | /// // | ^ |
| 732 | /// enum GenericParam { |
| 733 | /// Type(TypeParam), |
| 734 | /// Lifetime(LifetimeDef), |
| 735 | /// Const(ConstParam), |
| 736 | /// } |
| 737 | /// |
| 738 | /// impl Parse for GenericParam { |
| 739 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 740 | /// let lookahead = input.lookahead1(); |
| 741 | /// if lookahead.peek(Ident) { |
| 742 | /// input.parse().map(GenericParam::Type) |
| 743 | /// } else if lookahead.peek(Lifetime) { |
| 744 | /// input.parse().map(GenericParam::Lifetime) |
| 745 | /// } else if lookahead.peek(Token![const]) { |
| 746 | /// input.parse().map(GenericParam::Const) |
| 747 | /// } else { |
| 748 | /// Err(lookahead.error()) |
| 749 | /// } |
| 750 | /// } |
| 751 | /// } |
| 752 | /// # |
| 753 | /// # fn main() {} |
| 754 | /// ``` |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 755 | pub fn lookahead1(&self) -> Lookahead1<'a> { |
| 756 | lookahead::new(self.scope, self.cursor()) |
| 757 | } |
| 758 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 759 | /// Forks a parse stream so that parsing tokens out of either the original |
| 760 | /// or the fork does not advance the position of the other. |
| 761 | /// |
| 762 | /// # Performance |
| 763 | /// |
| 764 | /// Forking a parse stream is a cheap fixed amount of work and does not |
| 765 | /// involve copying token buffers. Where you might hit performance problems |
| 766 | /// is if your macro ends up parsing a large amount of content more than |
| 767 | /// once. |
| 768 | /// |
| 769 | /// ``` |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 770 | /// # use syn::{Expr, Result}; |
| 771 | /// # use syn::parse::ParseStream; |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 772 | /// # |
| 773 | /// # fn bad(input: ParseStream) -> Result<Expr> { |
| 774 | /// // Do not do this. |
| 775 | /// if input.fork().parse::<Expr>().is_ok() { |
| 776 | /// return input.parse::<Expr>(); |
| 777 | /// } |
| 778 | /// # unimplemented!() |
| 779 | /// # } |
| 780 | /// ``` |
| 781 | /// |
| 782 | /// As a rule, avoid parsing an unbounded amount of tokens out of a forked |
| 783 | /// parse stream. Only use a fork when the amount of work performed against |
| 784 | /// the fork is small and bounded. |
| 785 | /// |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 786 | /// For a lower level but occasionally more performant way to perform |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 787 | /// speculative parsing, consider using [`ParseStream::step`] instead. |
| 788 | /// |
| 789 | /// [`ParseStream::step`]: #method.step |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 790 | /// |
| 791 | /// # Example |
| 792 | /// |
| 793 | /// The parse implementation shown here parses possibly restricted `pub` |
| 794 | /// visibilities. |
| 795 | /// |
| 796 | /// - `pub` |
| 797 | /// - `pub(crate)` |
| 798 | /// - `pub(self)` |
| 799 | /// - `pub(super)` |
| 800 | /// - `pub(in some::path)` |
| 801 | /// |
| 802 | /// To handle the case of visibilities inside of tuple structs, the parser |
| 803 | /// needs to distinguish parentheses that specify visibility restrictions |
| 804 | /// from parentheses that form part of a tuple type. |
| 805 | /// |
| 806 | /// ``` |
| 807 | /// # struct A; |
| 808 | /// # struct B; |
| 809 | /// # struct C; |
| 810 | /// # |
| 811 | /// struct S(pub(crate) A, pub (B, C)); |
| 812 | /// ``` |
| 813 | /// |
| 814 | /// In this example input the first tuple struct element of `S` has |
| 815 | /// `pub(crate)` visibility while the second tuple struct element has `pub` |
| 816 | /// visibility; the parentheses around `(B, C)` are part of the type rather |
| 817 | /// than part of a visibility restriction. |
| 818 | /// |
| 819 | /// The parser uses a forked parse stream to check the first token inside of |
| 820 | /// parentheses after the `pub` keyword. This is a small bounded amount of |
| 821 | /// work performed against the forked parse stream. |
| 822 | /// |
| 823 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 824 | /// #[macro_use] |
| 825 | /// extern crate syn; |
| 826 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 827 | /// use syn::{token, Ident, Path, Result}; |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 828 | /// use syn::ext::IdentExt; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 829 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | ec149b0 | 2018-09-01 14:17:28 -0700 | [diff] [blame] | 830 | /// |
| 831 | /// struct PubVisibility { |
| 832 | /// pub_token: Token![pub], |
| 833 | /// restricted: Option<Restricted>, |
| 834 | /// } |
| 835 | /// |
| 836 | /// struct Restricted { |
| 837 | /// paren_token: token::Paren, |
| 838 | /// in_token: Option<Token![in]>, |
| 839 | /// path: Path, |
| 840 | /// } |
| 841 | /// |
| 842 | /// impl Parse for PubVisibility { |
| 843 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 844 | /// let pub_token: Token![pub] = input.parse()?; |
| 845 | /// |
| 846 | /// if input.peek(token::Paren) { |
| 847 | /// let ahead = input.fork(); |
| 848 | /// let mut content; |
| 849 | /// parenthesized!(content in ahead); |
| 850 | /// |
| 851 | /// if content.peek(Token![crate]) |
| 852 | /// || content.peek(Token![self]) |
| 853 | /// || content.peek(Token![super]) |
| 854 | /// { |
| 855 | /// return Ok(PubVisibility { |
| 856 | /// pub_token: pub_token, |
| 857 | /// restricted: Some(Restricted { |
| 858 | /// paren_token: parenthesized!(content in input), |
| 859 | /// in_token: None, |
| 860 | /// path: Path::from(content.call(Ident::parse_any)?), |
| 861 | /// }), |
| 862 | /// }); |
| 863 | /// } else if content.peek(Token![in]) { |
| 864 | /// return Ok(PubVisibility { |
| 865 | /// pub_token: pub_token, |
| 866 | /// restricted: Some(Restricted { |
| 867 | /// paren_token: parenthesized!(content in input), |
| 868 | /// in_token: Some(content.parse()?), |
| 869 | /// path: content.call(Path::parse_mod_style)?, |
| 870 | /// }), |
| 871 | /// }); |
| 872 | /// } |
| 873 | /// } |
| 874 | /// |
| 875 | /// Ok(PubVisibility { |
| 876 | /// pub_token: pub_token, |
| 877 | /// restricted: None, |
| 878 | /// }) |
| 879 | /// } |
| 880 | /// } |
| 881 | /// # |
| 882 | /// # fn main() {} |
| 883 | /// ``` |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 884 | pub fn fork(&self) -> Self { |
David Tolnay | 6456a9d | 2018-08-26 08:11:18 -0400 | [diff] [blame] | 885 | ParseBuffer { |
| 886 | scope: self.scope, |
| 887 | cell: self.cell.clone(), |
| 888 | marker: PhantomData, |
| 889 | // Not the parent's unexpected. Nothing cares whether the clone |
| 890 | // parses all the way. |
| 891 | unexpected: Rc::new(Cell::new(None)), |
| 892 | } |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 893 | } |
| 894 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 895 | /// Triggers an error at the current position of the parse stream. |
David Tolnay | 23fce0b | 2018-09-01 13:50:31 -0700 | [diff] [blame] | 896 | /// |
| 897 | /// # Example |
| 898 | /// |
| 899 | /// ``` |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 900 | /// #[macro_use] |
| 901 | /// extern crate syn; |
| 902 | /// |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 903 | /// use syn::{Expr, Result}; |
| 904 | /// use syn::parse::{Parse, ParseStream}; |
David Tolnay | 23fce0b | 2018-09-01 13:50:31 -0700 | [diff] [blame] | 905 | /// |
| 906 | /// // Some kind of loop: `while` or `for` or `loop`. |
| 907 | /// struct Loop { |
| 908 | /// expr: Expr, |
| 909 | /// } |
| 910 | /// |
| 911 | /// impl Parse for Loop { |
| 912 | /// fn parse(input: ParseStream) -> Result<Self> { |
| 913 | /// if input.peek(Token![while]) |
| 914 | /// || input.peek(Token![for]) |
| 915 | /// || input.peek(Token![loop]) |
| 916 | /// { |
| 917 | /// Ok(Loop { |
| 918 | /// expr: input.parse()?, |
| 919 | /// }) |
| 920 | /// } else { |
| 921 | /// Err(input.error("expected some kind of loop")) |
| 922 | /// } |
| 923 | /// } |
| 924 | /// } |
David Tolnay | a1c9807 | 2018-09-06 08:58:10 -0700 | [diff] [blame] | 925 | /// # |
| 926 | /// # fn main() {} |
David Tolnay | 23fce0b | 2018-09-01 13:50:31 -0700 | [diff] [blame] | 927 | /// ``` |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 928 | pub fn error<T: Display>(&self, message: T) -> Error { |
| 929 | error::new_at(self.scope, self.cursor(), message) |
| 930 | } |
| 931 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 932 | /// Speculatively parses tokens from this parse stream, advancing the |
| 933 | /// position of this stream only if parsing succeeds. |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 934 | /// |
David Tolnay | ad1d1d2 | 2018-09-01 13:34:43 -0700 | [diff] [blame] | 935 | /// This is a powerful low-level API used for defining the `Parse` impls of |
| 936 | /// the basic built-in token types. It is not something that will be used |
| 937 | /// widely outside of the Syn codebase. |
| 938 | /// |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 939 | /// # Example |
| 940 | /// |
| 941 | /// ``` |
| 942 | /// # extern crate proc_macro2; |
| 943 | /// # extern crate syn; |
| 944 | /// # |
| 945 | /// use proc_macro2::TokenTree; |
David Tolnay | 67fea04 | 2018-11-24 14:50:20 -0800 | [diff] [blame^] | 946 | /// use syn::Result; |
| 947 | /// use syn::parse::ParseStream; |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 948 | /// |
| 949 | /// // This function advances the stream past the next occurrence of `@`. If |
| 950 | /// // no `@` is present in the stream, the stream position is unchanged and |
| 951 | /// // an error is returned. |
| 952 | /// fn skip_past_next_at(input: ParseStream) -> Result<()> { |
| 953 | /// input.step(|cursor| { |
| 954 | /// let mut rest = *cursor; |
David Tolnay | db31258 | 2018-11-06 20:42:05 -0800 | [diff] [blame] | 955 | /// while let Some((tt, next)) = rest.token_tree() { |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 956 | /// match tt { |
| 957 | /// TokenTree::Punct(ref punct) if punct.as_char() == '@' => { |
| 958 | /// return Ok(((), next)); |
| 959 | /// } |
| 960 | /// _ => rest = next, |
| 961 | /// } |
| 962 | /// } |
| 963 | /// Err(cursor.error("no `@` was found after this point")) |
| 964 | /// }) |
| 965 | /// } |
| 966 | /// # |
David Tolnay | db31258 | 2018-11-06 20:42:05 -0800 | [diff] [blame] | 967 | /// # fn remainder_after_skipping_past_next_at( |
| 968 | /// # input: ParseStream, |
| 969 | /// # ) -> Result<proc_macro2::TokenStream> { |
| 970 | /// # skip_past_next_at(input)?; |
| 971 | /// # input.parse() |
| 972 | /// # } |
| 973 | /// # |
| 974 | /// # fn main() { |
| 975 | /// # use syn::parse::Parser; |
| 976 | /// # let remainder = remainder_after_skipping_past_next_at |
| 977 | /// # .parse_str("a @ b c") |
| 978 | /// # .unwrap(); |
| 979 | /// # assert_eq!(remainder.to_string(), "b c"); |
| 980 | /// # } |
David Tolnay | 9bd3439 | 2018-09-01 13:19:53 -0700 | [diff] [blame] | 981 | /// ``` |
David Tolnay | b50c65a | 2018-08-30 21:14:57 -0700 | [diff] [blame] | 982 | pub fn step<F, R>(&self, function: F) -> Result<R> |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 983 | where |
| 984 | F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>, |
| 985 | { |
David Tolnay | c142b09 | 2018-09-02 08:52:52 -0700 | [diff] [blame] | 986 | // Since the user's function is required to work for any 'c, we know |
| 987 | // that the Cursor<'c> they return is either derived from the input |
| 988 | // StepCursor<'c, 'a> or from a Cursor<'static>. |
| 989 | // |
| 990 | // It would not be legal to write this function without the invariant |
| 991 | // lifetime 'c in StepCursor<'c, 'a>. If this function were written only |
| 992 | // in terms of 'a, the user could take our ParseBuffer<'a>, upcast it to |
| 993 | // a ParseBuffer<'short> which some shorter lifetime than 'a, invoke |
| 994 | // `step` on their ParseBuffer<'short> with a closure that returns |
| 995 | // Cursor<'short>, and we would wrongly write that Cursor<'short> into |
| 996 | // the Cell intended to hold Cursor<'a>. |
| 997 | // |
| 998 | // In some cases it may be necessary for R to contain a Cursor<'a>. |
| 999 | // Within Syn we solve this using `private::advance_step_cursor` which |
| 1000 | // uses the existence of a StepCursor<'c, 'a> as proof that it is safe |
| 1001 | // to cast from Cursor<'c> to Cursor<'a>. If needed outside of Syn, it |
| 1002 | // would be safe to expose that API as a method on StepCursor. |
David Tolnay | 6b65f85 | 2018-09-01 11:56:25 -0700 | [diff] [blame] | 1003 | let (node, rest) = function(StepCursor { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1004 | scope: self.scope, |
| 1005 | cursor: self.cell.get(), |
| 1006 | marker: PhantomData, |
David Tolnay | 6b65f85 | 2018-09-01 11:56:25 -0700 | [diff] [blame] | 1007 | })?; |
| 1008 | self.cell.set(rest); |
| 1009 | Ok(node) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1010 | } |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 1011 | |
David Tolnay | 725e1c6 | 2018-09-01 12:07:25 -0700 | [diff] [blame] | 1012 | /// Provides low-level access to the token representation underlying this |
| 1013 | /// parse stream. |
| 1014 | /// |
| 1015 | /// Cursors are immutable so no operations you perform against the cursor |
| 1016 | /// will affect the state of this parse stream. |
David Tolnay | f5d3045 | 2018-09-01 02:29:04 -0700 | [diff] [blame] | 1017 | pub fn cursor(&self) -> Cursor<'a> { |
| 1018 | self.cell.get() |
| 1019 | } |
| 1020 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame] | 1021 | fn check_unexpected(&self) -> Result<()> { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 1022 | match self.unexpected.get() { |
| 1023 | Some(span) => Err(Error::new(span, "unexpected token")), |
| 1024 | None => Ok(()), |
| 1025 | } |
| 1026 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1027 | } |
| 1028 | |
David Tolnay | a7d69fc | 2018-08-26 13:30:24 -0400 | [diff] [blame] | 1029 | impl<T: Parse> Parse for Box<T> { |
| 1030 | fn parse(input: ParseStream) -> Result<Self> { |
| 1031 | input.parse().map(Box::new) |
| 1032 | } |
| 1033 | } |
| 1034 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 1035 | impl<T: Parse + Token> Parse for Option<T> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1036 | fn parse(input: ParseStream) -> Result<Self> { |
David Tolnay | 00f81fd | 2018-09-01 10:50:12 -0700 | [diff] [blame] | 1037 | if T::peek(input.cursor()) { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 1038 | Ok(Some(input.parse()?)) |
| 1039 | } else { |
| 1040 | Ok(None) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1041 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 1042 | } |
| 1043 | } |
David Tolnay | 4ac232d | 2018-08-31 10:18:03 -0700 | [diff] [blame] | 1044 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1045 | impl Parse for TokenStream { |
| 1046 | fn parse(input: ParseStream) -> Result<Self> { |
| 1047 | input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty()))) |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | impl Parse for TokenTree { |
| 1052 | fn parse(input: ParseStream) -> Result<Self> { |
| 1053 | input.step(|cursor| match cursor.token_tree() { |
| 1054 | Some((tt, rest)) => Ok((tt, rest)), |
| 1055 | None => Err(cursor.error("expected token tree")), |
| 1056 | }) |
| 1057 | } |
| 1058 | } |
| 1059 | |
| 1060 | impl Parse for Group { |
| 1061 | fn parse(input: ParseStream) -> Result<Self> { |
| 1062 | input.step(|cursor| { |
| 1063 | for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] { |
| 1064 | if let Some((inside, span, rest)) = cursor.group(*delim) { |
| 1065 | let mut group = Group::new(*delim, inside.token_stream()); |
| 1066 | group.set_span(span); |
| 1067 | return Ok((group, rest)); |
| 1068 | } |
| 1069 | } |
| 1070 | Err(cursor.error("expected group token")) |
| 1071 | }) |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | impl Parse for Punct { |
| 1076 | fn parse(input: ParseStream) -> Result<Self> { |
| 1077 | input.step(|cursor| match cursor.punct() { |
| 1078 | Some((punct, rest)) => Ok((punct, rest)), |
| 1079 | None => Err(cursor.error("expected punctuation token")), |
| 1080 | }) |
| 1081 | } |
| 1082 | } |
| 1083 | |
| 1084 | impl Parse for Literal { |
| 1085 | fn parse(input: ParseStream) -> Result<Self> { |
| 1086 | input.step(|cursor| match cursor.literal() { |
| 1087 | Some((literal, rest)) => Ok((literal, rest)), |
| 1088 | None => Err(cursor.error("expected literal token")), |
| 1089 | }) |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | /// Parser that can parse Rust tokens into a particular syntax tree node. |
| 1094 | /// |
| 1095 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 1096 | /// |
| 1097 | /// [module documentation]: index.html |
| 1098 | /// |
| 1099 | /// *This trait is available if Syn is built with the `"parsing"` feature.* |
| 1100 | pub trait Parser: Sized { |
| 1101 | type Output; |
| 1102 | |
| 1103 | /// Parse a proc-macro2 token stream into the chosen syntax tree node. |
| 1104 | fn parse2(self, tokens: TokenStream) -> Result<Self::Output>; |
| 1105 | |
| 1106 | /// Parse tokens of source code into the chosen syntax tree node. |
| 1107 | /// |
| 1108 | /// *This method is available if Syn is built with both the `"parsing"` and |
| 1109 | /// `"proc-macro"` features.* |
| 1110 | #[cfg(all( |
| 1111 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 1112 | feature = "proc-macro" |
| 1113 | ))] |
| 1114 | fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> { |
| 1115 | self.parse2(proc_macro2::TokenStream::from(tokens)) |
| 1116 | } |
| 1117 | |
| 1118 | /// Parse a string of Rust code into the chosen syntax tree node. |
| 1119 | /// |
| 1120 | /// # Hygiene |
| 1121 | /// |
| 1122 | /// Every span in the resulting syntax tree will be set to resolve at the |
| 1123 | /// macro call site. |
| 1124 | fn parse_str(self, s: &str) -> Result<Self::Output> { |
| 1125 | self.parse2(proc_macro2::TokenStream::from_str(s)?) |
| 1126 | } |
| 1127 | } |
| 1128 | |
David Tolnay | 7b07aa1 | 2018-09-01 11:41:12 -0700 | [diff] [blame] | 1129 | fn tokens_to_parse_buffer(tokens: &TokenBuffer) -> ParseBuffer { |
| 1130 | let scope = Span::call_site(); |
| 1131 | let cursor = tokens.begin(); |
| 1132 | let unexpected = Rc::new(Cell::new(None)); |
| 1133 | private::new_parse_buffer(scope, cursor, unexpected) |
| 1134 | } |
| 1135 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1136 | impl<F, T> Parser for F |
| 1137 | where |
| 1138 | F: FnOnce(ParseStream) -> Result<T>, |
| 1139 | { |
| 1140 | type Output = T; |
| 1141 | |
| 1142 | fn parse2(self, tokens: TokenStream) -> Result<T> { |
| 1143 | let buf = TokenBuffer::new2(tokens); |
David Tolnay | 7b07aa1 | 2018-09-01 11:41:12 -0700 | [diff] [blame] | 1144 | let state = tokens_to_parse_buffer(&buf); |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 1145 | let node = self(&state)?; |
| 1146 | state.check_unexpected()?; |
| 1147 | if state.is_empty() { |
| 1148 | Ok(node) |
| 1149 | } else { |
| 1150 | Err(state.error("unexpected token")) |
| 1151 | } |
| 1152 | } |
| 1153 | } |