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