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 | //! |
| 11 | //! Parsing in Syn is built on parser functions that take in a [`Cursor`] and |
| 12 | //! produce a [`PResult<T>`] where `T` is some syntax tree node. `Cursor` is a |
| 13 | //! cheaply copyable cursor over a range of tokens in a token stream, and |
| 14 | //! `PResult` is a result that packages together a parsed syntax tree node `T` |
| 15 | //! with a stream of remaining unparsed tokens after `T` represented as another |
| 16 | //! `Cursor`, or an [`Error`] if parsing failed. |
| 17 | //! |
| 18 | //! [`Cursor`]: ../buffer/index.html |
| 19 | //! [`PResult<T>`]: type.PResult.html |
| 20 | //! [`Error`]: struct.Error.html |
| 21 | //! |
| 22 | //! This `Cursor`- and `PResult`-based interface is convenient for parser |
| 23 | //! combinators and parser implementations, but not necessarily when you just |
| 24 | //! have some tokens that you want to parse. For that we expose the following |
| 25 | //! two entry points. |
| 26 | //! |
| 27 | //! ## The `syn::parse*` functions |
| 28 | //! |
| 29 | //! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve |
| 30 | //! as an entry point for parsing syntax tree nodes that can be parsed in an |
| 31 | //! obvious default way. These functions can return any syntax tree node that |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 32 | //! implements the [`Parse`] trait, which includes most types in Syn. |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 33 | //! |
| 34 | //! [`syn::parse`]: ../fn.parse.html |
| 35 | //! [`syn::parse2`]: ../fn.parse2.html |
| 36 | //! [`syn::parse_str`]: ../fn.parse_str.html |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 37 | //! [`Parse`]: trait.Parse.html |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 38 | //! |
| 39 | //! ``` |
| 40 | //! use syn::Type; |
| 41 | //! |
David Tolnay | 8aacee1 | 2018-08-31 09:15:15 -0700 | [diff] [blame] | 42 | //! # fn run_parser() -> Result<(), syn::parse::Error> { |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 43 | //! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?; |
| 44 | //! # Ok(()) |
| 45 | //! # } |
| 46 | //! # |
| 47 | //! # fn main() { |
| 48 | //! # run_parser().unwrap(); |
| 49 | //! # } |
| 50 | //! ``` |
| 51 | //! |
| 52 | //! The [`parse_quote!`] macro also uses this approach. |
| 53 | //! |
| 54 | //! [`parse_quote!`]: ../macro.parse_quote.html |
| 55 | //! |
| 56 | //! ## The `Parser` trait |
| 57 | //! |
| 58 | //! Some types can be parsed in several ways depending on context. For example |
| 59 | //! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like |
| 60 | //! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`] |
| 61 | //! may or may not allow trailing punctuation, and parsing it the wrong way |
| 62 | //! would either reject valid input or accept invalid input. |
| 63 | //! |
| 64 | //! [`Attribute`]: ../struct.Attribute.html |
| 65 | //! [`Punctuated`]: ../punctuated/index.html |
| 66 | //! |
| 67 | //! The `Synom` trait is not implemented in these cases because there is no good |
| 68 | //! behavior to consider the default. |
| 69 | //! |
| 70 | //! ```ignore |
| 71 | //! // Can't parse `Punctuated` without knowing whether trailing punctuation |
| 72 | //! // should be allowed in this context. |
| 73 | //! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?; |
| 74 | //! ``` |
| 75 | //! |
| 76 | //! In these cases the types provide a choice of parser functions rather than a |
| 77 | //! single `Synom` implementation, and those parser functions can be invoked |
| 78 | //! through the [`Parser`] trait. |
| 79 | //! |
| 80 | //! [`Parser`]: trait.Parser.html |
| 81 | //! |
| 82 | //! ``` |
| 83 | //! # #[macro_use] |
| 84 | //! # extern crate syn; |
| 85 | //! # |
| 86 | //! # extern crate proc_macro2; |
| 87 | //! # use proc_macro2::TokenStream; |
| 88 | //! # |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 89 | //! use syn::parse::Parser; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 90 | //! use syn::punctuated::Punctuated; |
| 91 | //! use syn::{PathSegment, Expr, Attribute}; |
| 92 | //! |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 93 | //! # fn run_parsers() -> Result<(), syn::parse::Error> { |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 94 | //! # let tokens = TokenStream::new().into(); |
| 95 | //! // Parse a nonempty sequence of path segments separated by `::` punctuation |
| 96 | //! // with no trailing punctuation. |
| 97 | //! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty; |
| 98 | //! let path = parser.parse(tokens)?; |
| 99 | //! |
| 100 | //! # let tokens = TokenStream::new().into(); |
| 101 | //! // Parse a possibly empty sequence of expressions terminated by commas with |
| 102 | //! // an optional trailing punctuation. |
| 103 | //! let parser = Punctuated::<Expr, Token![,]>::parse_terminated; |
| 104 | //! let args = parser.parse(tokens)?; |
| 105 | //! |
| 106 | //! # let tokens = TokenStream::new().into(); |
| 107 | //! // Parse zero or more outer attributes but not inner attributes. |
David Tolnay | 3e3f775 | 2018-08-31 09:33:59 -0700 | [diff] [blame] | 108 | //! let parser = Attribute::parse_outer; |
| 109 | //! let attrs = parser.parse(tokens)?; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 110 | //! # |
| 111 | //! # Ok(()) |
| 112 | //! # } |
| 113 | //! # |
| 114 | //! # fn main() {} |
| 115 | //! ``` |
| 116 | //! |
| 117 | //! # Implementing a parser function |
| 118 | //! |
| 119 | //! Parser functions are usually implemented using the [`nom`]-style parser |
| 120 | //! combinator macros provided by Syn, but may also be implemented without |
| 121 | //! macros be using the low-level [`Cursor`] API directly. |
| 122 | //! |
| 123 | //! [`nom`]: https://github.com/Geal/nom |
| 124 | //! |
| 125 | //! The following parser combinator macros are available and a `Synom` parsing |
| 126 | //! example is provided for each one. |
| 127 | //! |
| 128 | //! - [`alt!`](../macro.alt.html) |
| 129 | //! - [`braces!`](../macro.braces.html) |
| 130 | //! - [`brackets!`](../macro.brackets.html) |
| 131 | //! - [`call!`](../macro.call.html) |
| 132 | //! - [`cond!`](../macro.cond.html) |
| 133 | //! - [`cond_reduce!`](../macro.cond_reduce.html) |
| 134 | //! - [`custom_keyword!`](../macro.custom_keyword.html) |
| 135 | //! - [`do_parse!`](../macro.do_parse.html) |
| 136 | //! - [`epsilon!`](../macro.epsilon.html) |
| 137 | //! - [`input_end!`](../macro.input_end.html) |
| 138 | //! - [`keyword!`](../macro.keyword.html) |
| 139 | //! - [`many0!`](../macro.many0.html) |
| 140 | //! - [`map!`](../macro.map.html) |
| 141 | //! - [`not!`](../macro.not.html) |
| 142 | //! - [`option!`](../macro.option.html) |
| 143 | //! - [`parens!`](../macro.parens.html) |
| 144 | //! - [`punct!`](../macro.punct.html) |
| 145 | //! - [`reject!`](../macro.reject.html) |
| 146 | //! - [`switch!`](../macro.switch.html) |
| 147 | //! - [`syn!`](../macro.syn.html) |
| 148 | //! - [`tuple!`](../macro.tuple.html) |
| 149 | //! - [`value!`](../macro.value.html) |
| 150 | //! |
| 151 | //! *This module is available if Syn is built with the `"parsing"` feature.* |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 152 | |
| 153 | use std::cell::Cell; |
| 154 | use std::fmt::Display; |
| 155 | use std::marker::PhantomData; |
| 156 | use std::mem; |
| 157 | use std::ops::Deref; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 158 | use std::rc::Rc; |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 159 | use std::str::FromStr; |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 160 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 161 | #[cfg(all( |
| 162 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 163 | feature = "proc-macro" |
| 164 | ))] |
| 165 | use proc_macro; |
| 166 | use proc_macro2::{self, Delimiter, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 167 | |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 168 | use buffer::{Cursor, TokenBuffer}; |
David Tolnay | b625418 | 2018-08-25 08:44:54 -0400 | [diff] [blame] | 169 | use error; |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame^] | 170 | use lookahead; |
| 171 | use private; |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 172 | use punctuated::Punctuated; |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 173 | use token::Token; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 174 | |
David Tolnay | b625418 | 2018-08-25 08:44:54 -0400 | [diff] [blame] | 175 | pub use error::{Error, Result}; |
| 176 | pub use lookahead::{Lookahead1, Peek}; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 177 | |
| 178 | /// Parsing interface implemented by all types that can be parsed in a default |
| 179 | /// way from a token stream. |
| 180 | pub trait Parse: Sized { |
| 181 | fn parse(input: ParseStream) -> Result<Self>; |
| 182 | } |
| 183 | |
| 184 | /// Input to a Syn parser function. |
| 185 | pub type ParseStream<'a> = &'a ParseBuffer<'a>; |
| 186 | |
| 187 | /// Cursor position within a buffered token stream. |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 188 | pub struct ParseBuffer<'a> { |
| 189 | scope: Span, |
| 190 | cell: Cell<Cursor<'static>>, |
| 191 | marker: PhantomData<Cursor<'a>>, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 192 | unexpected: Rc<Cell<Option<Span>>>, |
| 193 | } |
| 194 | |
| 195 | impl<'a> Drop for ParseBuffer<'a> { |
| 196 | fn drop(&mut self) { |
| 197 | if !self.is_empty() && self.unexpected.get().is_none() { |
| 198 | self.unexpected.set(Some(self.cursor().span())); |
| 199 | } |
| 200 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 201 | } |
| 202 | |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 203 | #[derive(Copy, Clone)] |
| 204 | pub struct StepCursor<'c, 'a> { |
| 205 | scope: Span, |
| 206 | cursor: Cursor<'c>, |
| 207 | marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>, |
| 208 | } |
| 209 | |
| 210 | impl<'c, 'a> Deref for StepCursor<'c, 'a> { |
| 211 | type Target = Cursor<'c>; |
| 212 | |
| 213 | fn deref(&self) -> &Self::Target { |
| 214 | &self.cursor |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | impl<'c, 'a> StepCursor<'c, 'a> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 219 | pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> { |
| 220 | unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) } |
| 221 | } |
| 222 | |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 223 | pub fn error<T: Display>(self, message: T) -> Error { |
| 224 | error::new_at(self.scope, self.cursor, message) |
| 225 | } |
| 226 | } |
| 227 | |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 228 | fn skip(input: ParseStream) -> bool { |
| 229 | input.step(|cursor| { |
| 230 | if let Some((_lifetime, rest)) = cursor.lifetime() { |
| 231 | Ok((true, rest)) |
| 232 | } else if let Some((_token, rest)) = cursor.token_tree() { |
| 233 | Ok((true, rest)) |
| 234 | } else { |
| 235 | Ok((false, *cursor)) |
| 236 | } |
| 237 | }).unwrap() |
| 238 | } |
| 239 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame^] | 240 | impl<'a> private<ParseBuffer<'a>> { |
| 241 | pub fn new(scope: Span, cursor: Cursor, unexpected: Rc<Cell<Option<Span>>>) -> ParseBuffer { |
| 242 | let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) }; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 243 | ParseBuffer { |
| 244 | scope: scope, |
| 245 | cell: Cell::new(extend), |
| 246 | marker: PhantomData, |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 247 | unexpected: unexpected, |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 248 | } |
| 249 | } |
| 250 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame^] | 251 | pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> { |
| 252 | buffer.unexpected.clone() |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | impl<'a> ParseBuffer<'a> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 257 | pub fn cursor(&self) -> Cursor<'a> { |
| 258 | self.cell.get() |
| 259 | } |
| 260 | |
| 261 | pub fn is_empty(&self) -> bool { |
| 262 | self.cursor().eof() |
| 263 | } |
| 264 | |
| 265 | pub fn lookahead1(&self) -> Lookahead1<'a> { |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame^] | 266 | lookahead::new(self.scope, self.cursor()) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 267 | } |
| 268 | |
| 269 | pub fn parse<T: Parse>(&self) -> Result<T> { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 270 | self.check_unexpected()?; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 271 | T::parse(self) |
| 272 | } |
| 273 | |
David Tolnay | 3a515a0 | 2018-08-25 21:08:27 -0400 | [diff] [blame] | 274 | pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> { |
| 275 | function(self) |
| 276 | } |
| 277 | |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 278 | pub fn peek<T: Peek>(&self, token: T) -> bool { |
| 279 | self.lookahead1().peek(token) |
| 280 | } |
| 281 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 282 | pub fn peek2<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 283 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 284 | skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 285 | } |
| 286 | |
| 287 | pub fn peek3<T: Peek>(&self, token: T) -> bool { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 288 | let ahead = self.fork(); |
David Tolnay | 66cb0c4 | 2018-08-31 09:01:30 -0700 | [diff] [blame] | 289 | skip(&ahead) && skip(&ahead) && ahead.peek(token) |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 290 | } |
| 291 | |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 292 | pub fn parse_terminated<T, P: Parse>( |
| 293 | &self, |
| 294 | parser: fn(ParseStream) -> Result<T>, |
| 295 | ) -> Result<Punctuated<T, P>> { |
David Tolnay | d0f8021 | 2018-08-30 18:32:14 -0700 | [diff] [blame] | 296 | Punctuated::parse_terminated_with(self, parser) |
David Tolnay | 577d033 | 2018-08-25 21:45:24 -0400 | [diff] [blame] | 297 | } |
| 298 | |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 299 | pub fn fork(&self) -> Self { |
David Tolnay | 6456a9d | 2018-08-26 08:11:18 -0400 | [diff] [blame] | 300 | ParseBuffer { |
| 301 | scope: self.scope, |
| 302 | cell: self.cell.clone(), |
| 303 | marker: PhantomData, |
| 304 | // Not the parent's unexpected. Nothing cares whether the clone |
| 305 | // parses all the way. |
| 306 | unexpected: Rc::new(Cell::new(None)), |
| 307 | } |
David Tolnay | b77c8b6 | 2018-08-25 16:39:41 -0400 | [diff] [blame] | 308 | } |
| 309 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 310 | pub fn error<T: Display>(&self, message: T) -> Error { |
| 311 | error::new_at(self.scope, self.cursor(), message) |
| 312 | } |
| 313 | |
David Tolnay | b50c65a | 2018-08-30 21:14:57 -0700 | [diff] [blame] | 314 | pub fn step<F, R>(&self, function: F) -> Result<R> |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 315 | where |
| 316 | F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>, |
| 317 | { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 318 | self.check_unexpected()?; |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 319 | match function(StepCursor { |
| 320 | scope: self.scope, |
| 321 | cursor: self.cell.get(), |
| 322 | marker: PhantomData, |
| 323 | }) { |
| 324 | Ok((ret, cursor)) => { |
| 325 | self.cell.set(cursor); |
| 326 | Ok(ret) |
| 327 | } |
| 328 | Err(err) => Err(err), |
| 329 | } |
| 330 | } |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 331 | |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame^] | 332 | fn check_unexpected(&self) -> Result<()> { |
David Tolnay | eafc805 | 2018-08-25 16:33:53 -0400 | [diff] [blame] | 333 | match self.unexpected.get() { |
| 334 | Some(span) => Err(Error::new(span, "unexpected token")), |
| 335 | None => Ok(()), |
| 336 | } |
| 337 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 338 | } |
| 339 | |
| 340 | impl Parse for Ident { |
| 341 | fn parse(input: ParseStream) -> Result<Self> { |
David Tolnay | b50c65a | 2018-08-30 21:14:57 -0700 | [diff] [blame] | 342 | input.step(|cursor| { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 343 | if let Some((ident, rest)) = cursor.ident() { |
David Tolnay | c4fdb1a | 2018-08-24 21:11:07 -0400 | [diff] [blame] | 344 | match ident.to_string().as_str() { |
| 345 | "_" |
| 346 | // Based on https://doc.rust-lang.org/grammar.html#keywords |
| 347 | // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md |
| 348 | | "abstract" | "as" | "become" | "box" | "break" | "const" |
| 349 | | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" |
| 350 | | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" |
| 351 | | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub" |
| 352 | | "ref" | "return" | "Self" | "self" | "static" | "struct" |
| 353 | | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" |
| 354 | | "virtual" | "where" | "while" | "yield" => {} |
| 355 | _ => return Ok((ident, rest)), |
| 356 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 357 | } |
David Tolnay | c4fdb1a | 2018-08-24 21:11:07 -0400 | [diff] [blame] | 358 | Err(cursor.error("expected identifier")) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 359 | }) |
| 360 | } |
| 361 | } |
| 362 | |
David Tolnay | a7d69fc | 2018-08-26 13:30:24 -0400 | [diff] [blame] | 363 | impl<T: Parse> Parse for Box<T> { |
| 364 | fn parse(input: ParseStream) -> Result<Self> { |
| 365 | input.parse().map(Box::new) |
| 366 | } |
| 367 | } |
| 368 | |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 369 | impl<T: Parse + Token> Parse for Option<T> { |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 370 | fn parse(input: ParseStream) -> Result<Self> { |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 371 | if T::peek(&input.lookahead1()) { |
| 372 | Ok(Some(input.parse()?)) |
| 373 | } else { |
| 374 | Ok(None) |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 375 | } |
David Tolnay | 18c754c | 2018-08-21 23:26:58 -0400 | [diff] [blame] | 376 | } |
| 377 | } |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 378 | |
| 379 | impl Parse for TokenStream { |
| 380 | fn parse(input: ParseStream) -> Result<Self> { |
| 381 | input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty()))) |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | impl Parse for TokenTree { |
| 386 | fn parse(input: ParseStream) -> Result<Self> { |
| 387 | input.step(|cursor| match cursor.token_tree() { |
| 388 | Some((tt, rest)) => Ok((tt, rest)), |
| 389 | None => Err(cursor.error("expected token tree")), |
| 390 | }) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | impl Parse for Group { |
| 395 | fn parse(input: ParseStream) -> Result<Self> { |
| 396 | input.step(|cursor| { |
| 397 | for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] { |
| 398 | if let Some((inside, span, rest)) = cursor.group(*delim) { |
| 399 | let mut group = Group::new(*delim, inside.token_stream()); |
| 400 | group.set_span(span); |
| 401 | return Ok((group, rest)); |
| 402 | } |
| 403 | } |
| 404 | Err(cursor.error("expected group token")) |
| 405 | }) |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | impl Parse for Punct { |
| 410 | fn parse(input: ParseStream) -> Result<Self> { |
| 411 | input.step(|cursor| match cursor.punct() { |
| 412 | Some((punct, rest)) => Ok((punct, rest)), |
| 413 | None => Err(cursor.error("expected punctuation token")), |
| 414 | }) |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | impl Parse for Literal { |
| 419 | fn parse(input: ParseStream) -> Result<Self> { |
| 420 | input.step(|cursor| match cursor.literal() { |
| 421 | Some((literal, rest)) => Ok((literal, rest)), |
| 422 | None => Err(cursor.error("expected literal token")), |
| 423 | }) |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | /// Parser that can parse Rust tokens into a particular syntax tree node. |
| 428 | /// |
| 429 | /// Refer to the [module documentation] for details about parsing in Syn. |
| 430 | /// |
| 431 | /// [module documentation]: index.html |
| 432 | /// |
| 433 | /// *This trait is available if Syn is built with the `"parsing"` feature.* |
| 434 | pub trait Parser: Sized { |
| 435 | type Output; |
| 436 | |
| 437 | /// Parse a proc-macro2 token stream into the chosen syntax tree node. |
| 438 | fn parse2(self, tokens: TokenStream) -> Result<Self::Output>; |
| 439 | |
| 440 | /// Parse tokens of source code into the chosen syntax tree node. |
| 441 | /// |
| 442 | /// *This method is available if Syn is built with both the `"parsing"` and |
| 443 | /// `"proc-macro"` features.* |
| 444 | #[cfg(all( |
| 445 | not(all(target_arch = "wasm32", target_os = "unknown")), |
| 446 | feature = "proc-macro" |
| 447 | ))] |
| 448 | fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> { |
| 449 | self.parse2(proc_macro2::TokenStream::from(tokens)) |
| 450 | } |
| 451 | |
| 452 | /// Parse a string of Rust code into the chosen syntax tree node. |
| 453 | /// |
| 454 | /// # Hygiene |
| 455 | /// |
| 456 | /// Every span in the resulting syntax tree will be set to resolve at the |
| 457 | /// macro call site. |
| 458 | fn parse_str(self, s: &str) -> Result<Self::Output> { |
| 459 | self.parse2(proc_macro2::TokenStream::from_str(s)?) |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | impl<F, T> Parser for F |
| 464 | where |
| 465 | F: FnOnce(ParseStream) -> Result<T>, |
| 466 | { |
| 467 | type Output = T; |
| 468 | |
| 469 | fn parse2(self, tokens: TokenStream) -> Result<T> { |
| 470 | let buf = TokenBuffer::new2(tokens); |
| 471 | let unexpected = Rc::new(Cell::new(None)); |
David Tolnay | 94f0663 | 2018-08-31 10:17:17 -0700 | [diff] [blame^] | 472 | let state = private::<ParseBuffer>::new(Span::call_site(), buf.begin(), unexpected); |
David Tolnay | 80a914f | 2018-08-30 23:49:53 -0700 | [diff] [blame] | 473 | let node = self(&state)?; |
| 474 | state.check_unexpected()?; |
| 475 | if state.is_empty() { |
| 476 | Ok(node) |
| 477 | } else { |
| 478 | Err(state.error("unexpected token")) |
| 479 | } |
| 480 | } |
| 481 | } |