blob: 97c6240aaed18e10a4e199db214ea27019e730e6 [file] [log] [blame]
David Tolnay80a914f2018-08-30 23:49:53 -07001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnay18c754c2018-08-21 23:26:58 -04009//! Parsing interface for parsing a token stream into a syntax tree node.
David Tolnay80a914f2018-08-30 23:49:53 -070010//!
David Tolnaye0c51762018-08-31 11:05:22 -070011//! Parsing in Syn is built on parser functions that take in a [`ParseStream`]
12//! and produce a [`Result<T>`] where `T` is some syntax tree node. Underlying
13//! these parser functions is a lower level mechanism built around the
14//! [`Cursor`] type. `Cursor` is a cheaply copyable cursor over a range of
15//! tokens in a token stream.
David Tolnay80a914f2018-08-30 23:49:53 -070016//!
David Tolnaye0c51762018-08-31 11:05:22 -070017//! [`ParseStream`]: type.ParseStream.html
18//! [`Result<T>`]: type.Result.html
David Tolnay80a914f2018-08-30 23:49:53 -070019//! [`Cursor`]: ../buffer/index.html
David Tolnay80a914f2018-08-30 23:49:53 -070020//!
David Tolnaye0c51762018-08-31 11:05:22 -070021//! The `ParseStream`-based interface is convenient for parser implementations,
22//! but not necessarily when you just have some tokens that you want to parse.
23//! For that we expose the following two entry points.
David Tolnay80a914f2018-08-30 23:49:53 -070024//!
25//! ## The `syn::parse*` functions
26//!
27//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve
28//! as an entry point for parsing syntax tree nodes that can be parsed in an
29//! obvious default way. These functions can return any syntax tree node that
David Tolnay8aacee12018-08-31 09:15:15 -070030//! implements the [`Parse`] trait, which includes most types in Syn.
David Tolnay80a914f2018-08-30 23:49:53 -070031//!
32//! [`syn::parse`]: ../fn.parse.html
33//! [`syn::parse2`]: ../fn.parse2.html
34//! [`syn::parse_str`]: ../fn.parse_str.html
David Tolnay8aacee12018-08-31 09:15:15 -070035//! [`Parse`]: trait.Parse.html
David Tolnay80a914f2018-08-30 23:49:53 -070036//!
37//! ```
38//! use syn::Type;
39//!
David Tolnay8aacee12018-08-31 09:15:15 -070040//! # fn run_parser() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -070041//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?;
42//! # Ok(())
43//! # }
44//! #
45//! # fn main() {
46//! # run_parser().unwrap();
47//! # }
48//! ```
49//!
50//! The [`parse_quote!`] macro also uses this approach.
51//!
52//! [`parse_quote!`]: ../macro.parse_quote.html
53//!
54//! ## The `Parser` trait
55//!
56//! Some types can be parsed in several ways depending on context. For example
57//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
58//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
59//! may or may not allow trailing punctuation, and parsing it the wrong way
60//! would either reject valid input or accept invalid input.
61//!
62//! [`Attribute`]: ../struct.Attribute.html
63//! [`Punctuated`]: ../punctuated/index.html
64//!
David Tolnaye0c51762018-08-31 11:05:22 -070065//! The `Parse` trait is not implemented in these cases because there is no good
David Tolnay80a914f2018-08-30 23:49:53 -070066//! behavior to consider the default.
67//!
68//! ```ignore
69//! // Can't parse `Punctuated` without knowing whether trailing punctuation
70//! // should be allowed in this context.
71//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
72//! ```
73//!
74//! In these cases the types provide a choice of parser functions rather than a
David Tolnaye0c51762018-08-31 11:05:22 -070075//! single `Parse` implementation, and those parser functions can be invoked
David Tolnay80a914f2018-08-30 23:49:53 -070076//! through the [`Parser`] trait.
77//!
78//! [`Parser`]: trait.Parser.html
79//!
80//! ```
81//! # #[macro_use]
82//! # extern crate syn;
83//! #
84//! # extern crate proc_macro2;
85//! # use proc_macro2::TokenStream;
86//! #
David Tolnay3e3f7752018-08-31 09:33:59 -070087//! use syn::parse::Parser;
David Tolnay80a914f2018-08-30 23:49:53 -070088//! use syn::punctuated::Punctuated;
89//! use syn::{PathSegment, Expr, Attribute};
90//!
David Tolnay3e3f7752018-08-31 09:33:59 -070091//! # fn run_parsers() -> Result<(), syn::parse::Error> {
David Tolnay80a914f2018-08-30 23:49:53 -070092//! # let tokens = TokenStream::new().into();
93//! // Parse a nonempty sequence of path segments separated by `::` punctuation
94//! // with no trailing punctuation.
95//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
96//! let path = parser.parse(tokens)?;
97//!
98//! # let tokens = TokenStream::new().into();
99//! // Parse a possibly empty sequence of expressions terminated by commas with
100//! // an optional trailing punctuation.
101//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
102//! let args = parser.parse(tokens)?;
103//!
104//! # let tokens = TokenStream::new().into();
105//! // Parse zero or more outer attributes but not inner attributes.
David Tolnay3e3f7752018-08-31 09:33:59 -0700106//! let parser = Attribute::parse_outer;
107//! let attrs = parser.parse(tokens)?;
David Tolnay80a914f2018-08-30 23:49:53 -0700108//! #
109//! # Ok(())
110//! # }
111//! #
112//! # fn main() {}
113//! ```
114//!
David Tolnaye0c51762018-08-31 11:05:22 -0700115//! ---
David Tolnay80a914f2018-08-30 23:49:53 -0700116//!
117//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnay18c754c2018-08-21 23:26:58 -0400118
119use std::cell::Cell;
120use std::fmt::Display;
121use std::marker::PhantomData;
122use std::mem;
123use std::ops::Deref;
David Tolnayeafc8052018-08-25 16:33:53 -0400124use std::rc::Rc;
David Tolnay80a914f2018-08-30 23:49:53 -0700125use std::str::FromStr;
David Tolnayeafc8052018-08-25 16:33:53 -0400126
David Tolnay80a914f2018-08-30 23:49:53 -0700127#[cfg(all(
128 not(all(target_arch = "wasm32", target_os = "unknown")),
129 feature = "proc-macro"
130))]
131use proc_macro;
132use proc_macro2::{self, Delimiter, Group, Ident, Literal, Punct, Span, TokenStream, TokenTree};
David Tolnay18c754c2018-08-21 23:26:58 -0400133
David Tolnay80a914f2018-08-30 23:49:53 -0700134use buffer::{Cursor, TokenBuffer};
David Tolnayb6254182018-08-25 08:44:54 -0400135use error;
David Tolnay94f06632018-08-31 10:17:17 -0700136use lookahead;
137use private;
David Tolnay577d0332018-08-25 21:45:24 -0400138use punctuated::Punctuated;
David Tolnay4fb71232018-08-25 23:14:50 -0400139use token::Token;
David Tolnay18c754c2018-08-21 23:26:58 -0400140
David Tolnayb6254182018-08-25 08:44:54 -0400141pub use error::{Error, Result};
142pub use lookahead::{Lookahead1, Peek};
David Tolnay18c754c2018-08-21 23:26:58 -0400143
144/// Parsing interface implemented by all types that can be parsed in a default
145/// way from a token stream.
146pub trait Parse: Sized {
147 fn parse(input: ParseStream) -> Result<Self>;
148}
149
150/// Input to a Syn parser function.
151pub type ParseStream<'a> = &'a ParseBuffer<'a>;
152
153/// Cursor position within a buffered token stream.
David Tolnay18c754c2018-08-21 23:26:58 -0400154pub struct ParseBuffer<'a> {
155 scope: Span,
156 cell: Cell<Cursor<'static>>,
157 marker: PhantomData<Cursor<'a>>,
David Tolnayeafc8052018-08-25 16:33:53 -0400158 unexpected: Rc<Cell<Option<Span>>>,
159}
160
161impl<'a> Drop for ParseBuffer<'a> {
162 fn drop(&mut self) {
163 if !self.is_empty() && self.unexpected.get().is_none() {
164 self.unexpected.set(Some(self.cursor().span()));
165 }
166 }
David Tolnay18c754c2018-08-21 23:26:58 -0400167}
168
David Tolnay18c754c2018-08-21 23:26:58 -0400169#[derive(Copy, Clone)]
170pub struct StepCursor<'c, 'a> {
171 scope: Span,
172 cursor: Cursor<'c>,
173 marker: PhantomData<fn(Cursor<'c>) -> Cursor<'a>>,
174}
175
176impl<'c, 'a> Deref for StepCursor<'c, 'a> {
177 type Target = Cursor<'c>;
178
179 fn deref(&self) -> &Self::Target {
180 &self.cursor
181 }
182}
183
184impl<'c, 'a> StepCursor<'c, 'a> {
David Tolnay18c754c2018-08-21 23:26:58 -0400185 pub fn advance(self, other: Cursor<'c>) -> Cursor<'a> {
186 unsafe { mem::transmute::<Cursor<'c>, Cursor<'a>>(other) }
187 }
188
David Tolnay18c754c2018-08-21 23:26:58 -0400189 pub fn error<T: Display>(self, message: T) -> Error {
190 error::new_at(self.scope, self.cursor, message)
191 }
192}
193
David Tolnay66cb0c42018-08-31 09:01:30 -0700194fn skip(input: ParseStream) -> bool {
David Tolnay4ac232d2018-08-31 10:18:03 -0700195 input
196 .step(|cursor| {
197 if let Some((_lifetime, rest)) = cursor.lifetime() {
198 Ok((true, rest))
199 } else if let Some((_token, rest)) = cursor.token_tree() {
200 Ok((true, rest))
201 } else {
202 Ok((false, *cursor))
203 }
204 }).unwrap()
David Tolnay66cb0c42018-08-31 09:01:30 -0700205}
206
David Tolnay10951d52018-08-31 10:27:39 -0700207impl private {
David Tolnay70f30e92018-09-01 02:04:17 -0700208 pub fn new_parse_buffer(
209 scope: Span,
210 cursor: Cursor,
211 unexpected: Rc<Cell<Option<Span>>>,
212 ) -> ParseBuffer {
David Tolnay94f06632018-08-31 10:17:17 -0700213 let extend = unsafe { mem::transmute::<Cursor, Cursor<'static>>(cursor) };
David Tolnay18c754c2018-08-21 23:26:58 -0400214 ParseBuffer {
215 scope: scope,
216 cell: Cell::new(extend),
217 marker: PhantomData,
David Tolnayeafc8052018-08-25 16:33:53 -0400218 unexpected: unexpected,
David Tolnay18c754c2018-08-21 23:26:58 -0400219 }
220 }
221
David Tolnay94f06632018-08-31 10:17:17 -0700222 pub fn get_unexpected(buffer: &ParseBuffer) -> Rc<Cell<Option<Span>>> {
223 buffer.unexpected.clone()
224 }
225}
226
227impl<'a> ParseBuffer<'a> {
David Tolnay18c754c2018-08-21 23:26:58 -0400228 pub fn cursor(&self) -> Cursor<'a> {
229 self.cell.get()
230 }
231
232 pub fn is_empty(&self) -> bool {
233 self.cursor().eof()
234 }
235
236 pub fn lookahead1(&self) -> Lookahead1<'a> {
David Tolnay94f06632018-08-31 10:17:17 -0700237 lookahead::new(self.scope, self.cursor())
David Tolnay18c754c2018-08-21 23:26:58 -0400238 }
239
240 pub fn parse<T: Parse>(&self) -> Result<T> {
David Tolnayeafc8052018-08-25 16:33:53 -0400241 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400242 T::parse(self)
243 }
244
David Tolnay3a515a02018-08-25 21:08:27 -0400245 pub fn call<T>(&self, function: fn(ParseStream) -> Result<T>) -> Result<T> {
246 function(self)
247 }
248
David Tolnayb77c8b62018-08-25 16:39:41 -0400249 pub fn peek<T: Peek>(&self, token: T) -> bool {
250 self.lookahead1().peek(token)
251 }
252
David Tolnay4fb71232018-08-25 23:14:50 -0400253 pub fn peek2<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400254 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700255 skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400256 }
257
258 pub fn peek3<T: Peek>(&self, token: T) -> bool {
David Tolnay4fb71232018-08-25 23:14:50 -0400259 let ahead = self.fork();
David Tolnay66cb0c42018-08-31 09:01:30 -0700260 skip(&ahead) && skip(&ahead) && ahead.peek(token)
David Tolnay4fb71232018-08-25 23:14:50 -0400261 }
262
David Tolnay577d0332018-08-25 21:45:24 -0400263 pub fn parse_terminated<T, P: Parse>(
264 &self,
265 parser: fn(ParseStream) -> Result<T>,
266 ) -> Result<Punctuated<T, P>> {
David Tolnayd0f80212018-08-30 18:32:14 -0700267 Punctuated::parse_terminated_with(self, parser)
David Tolnay577d0332018-08-25 21:45:24 -0400268 }
269
David Tolnayb77c8b62018-08-25 16:39:41 -0400270 pub fn fork(&self) -> Self {
David Tolnay6456a9d2018-08-26 08:11:18 -0400271 ParseBuffer {
272 scope: self.scope,
273 cell: self.cell.clone(),
274 marker: PhantomData,
275 // Not the parent's unexpected. Nothing cares whether the clone
276 // parses all the way.
277 unexpected: Rc::new(Cell::new(None)),
278 }
David Tolnayb77c8b62018-08-25 16:39:41 -0400279 }
280
David Tolnay4fb71232018-08-25 23:14:50 -0400281 pub fn error<T: Display>(&self, message: T) -> Error {
282 error::new_at(self.scope, self.cursor(), message)
283 }
284
David Tolnayb50c65a2018-08-30 21:14:57 -0700285 pub fn step<F, R>(&self, function: F) -> Result<R>
David Tolnay18c754c2018-08-21 23:26:58 -0400286 where
287 F: for<'c> FnOnce(StepCursor<'c, 'a>) -> Result<(R, Cursor<'c>)>,
288 {
David Tolnayeafc8052018-08-25 16:33:53 -0400289 self.check_unexpected()?;
David Tolnay18c754c2018-08-21 23:26:58 -0400290 match function(StepCursor {
291 scope: self.scope,
292 cursor: self.cell.get(),
293 marker: PhantomData,
294 }) {
295 Ok((ret, cursor)) => {
296 self.cell.set(cursor);
297 Ok(ret)
298 }
299 Err(err) => Err(err),
300 }
301 }
David Tolnayeafc8052018-08-25 16:33:53 -0400302
David Tolnay94f06632018-08-31 10:17:17 -0700303 fn check_unexpected(&self) -> Result<()> {
David Tolnayeafc8052018-08-25 16:33:53 -0400304 match self.unexpected.get() {
305 Some(span) => Err(Error::new(span, "unexpected token")),
306 None => Ok(()),
307 }
308 }
David Tolnay18c754c2018-08-21 23:26:58 -0400309}
310
311impl Parse for Ident {
312 fn parse(input: ParseStream) -> Result<Self> {
David Tolnayb50c65a2018-08-30 21:14:57 -0700313 input.step(|cursor| {
David Tolnay18c754c2018-08-21 23:26:58 -0400314 if let Some((ident, rest)) = cursor.ident() {
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400315 match ident.to_string().as_str() {
316 "_"
317 // Based on https://doc.rust-lang.org/grammar.html#keywords
318 // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md
319 | "abstract" | "as" | "become" | "box" | "break" | "const"
320 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
321 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
322 | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub"
323 | "ref" | "return" | "Self" | "self" | "static" | "struct"
324 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
325 | "virtual" | "where" | "while" | "yield" => {}
326 _ => return Ok((ident, rest)),
327 }
David Tolnay18c754c2018-08-21 23:26:58 -0400328 }
David Tolnayc4fdb1a2018-08-24 21:11:07 -0400329 Err(cursor.error("expected identifier"))
David Tolnay18c754c2018-08-21 23:26:58 -0400330 })
331 }
332}
333
David Tolnaya7d69fc2018-08-26 13:30:24 -0400334impl<T: Parse> Parse for Box<T> {
335 fn parse(input: ParseStream) -> Result<Self> {
336 input.parse().map(Box::new)
337 }
338}
339
David Tolnay4fb71232018-08-25 23:14:50 -0400340impl<T: Parse + Token> Parse for Option<T> {
David Tolnay18c754c2018-08-21 23:26:58 -0400341 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay4fb71232018-08-25 23:14:50 -0400342 if T::peek(&input.lookahead1()) {
343 Ok(Some(input.parse()?))
344 } else {
345 Ok(None)
David Tolnay18c754c2018-08-21 23:26:58 -0400346 }
David Tolnay18c754c2018-08-21 23:26:58 -0400347 }
348}
David Tolnay4ac232d2018-08-31 10:18:03 -0700349
David Tolnay80a914f2018-08-30 23:49:53 -0700350impl Parse for TokenStream {
351 fn parse(input: ParseStream) -> Result<Self> {
352 input.step(|cursor| Ok((cursor.token_stream(), Cursor::empty())))
353 }
354}
355
356impl Parse for TokenTree {
357 fn parse(input: ParseStream) -> Result<Self> {
358 input.step(|cursor| match cursor.token_tree() {
359 Some((tt, rest)) => Ok((tt, rest)),
360 None => Err(cursor.error("expected token tree")),
361 })
362 }
363}
364
365impl Parse for Group {
366 fn parse(input: ParseStream) -> Result<Self> {
367 input.step(|cursor| {
368 for delim in &[Delimiter::Parenthesis, Delimiter::Brace, Delimiter::Bracket] {
369 if let Some((inside, span, rest)) = cursor.group(*delim) {
370 let mut group = Group::new(*delim, inside.token_stream());
371 group.set_span(span);
372 return Ok((group, rest));
373 }
374 }
375 Err(cursor.error("expected group token"))
376 })
377 }
378}
379
380impl Parse for Punct {
381 fn parse(input: ParseStream) -> Result<Self> {
382 input.step(|cursor| match cursor.punct() {
383 Some((punct, rest)) => Ok((punct, rest)),
384 None => Err(cursor.error("expected punctuation token")),
385 })
386 }
387}
388
389impl Parse for Literal {
390 fn parse(input: ParseStream) -> Result<Self> {
391 input.step(|cursor| match cursor.literal() {
392 Some((literal, rest)) => Ok((literal, rest)),
393 None => Err(cursor.error("expected literal token")),
394 })
395 }
396}
397
398/// Parser that can parse Rust tokens into a particular syntax tree node.
399///
400/// Refer to the [module documentation] for details about parsing in Syn.
401///
402/// [module documentation]: index.html
403///
404/// *This trait is available if Syn is built with the `"parsing"` feature.*
405pub trait Parser: Sized {
406 type Output;
407
408 /// Parse a proc-macro2 token stream into the chosen syntax tree node.
409 fn parse2(self, tokens: TokenStream) -> Result<Self::Output>;
410
411 /// Parse tokens of source code into the chosen syntax tree node.
412 ///
413 /// *This method is available if Syn is built with both the `"parsing"` and
414 /// `"proc-macro"` features.*
415 #[cfg(all(
416 not(all(target_arch = "wasm32", target_os = "unknown")),
417 feature = "proc-macro"
418 ))]
419 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output> {
420 self.parse2(proc_macro2::TokenStream::from(tokens))
421 }
422
423 /// Parse a string of Rust code into the chosen syntax tree node.
424 ///
425 /// # Hygiene
426 ///
427 /// Every span in the resulting syntax tree will be set to resolve at the
428 /// macro call site.
429 fn parse_str(self, s: &str) -> Result<Self::Output> {
430 self.parse2(proc_macro2::TokenStream::from_str(s)?)
431 }
432}
433
434impl<F, T> Parser for F
435where
436 F: FnOnce(ParseStream) -> Result<T>,
437{
438 type Output = T;
439
440 fn parse2(self, tokens: TokenStream) -> Result<T> {
441 let buf = TokenBuffer::new2(tokens);
442 let unexpected = Rc::new(Cell::new(None));
David Tolnay10951d52018-08-31 10:27:39 -0700443 let state = private::new_parse_buffer(Span::call_site(), buf.begin(), unexpected);
David Tolnay80a914f2018-08-30 23:49:53 -0700444 let node = self(&state)?;
445 state.check_unexpected()?;
446 if state.is_empty() {
447 Ok(node)
448 } else {
449 Err(state.error("unexpected token"))
450 }
451 }
452}