blob: 5db92d33943741e317b89bf47dc8f4f5e0b72970 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// 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 Tolnayb34f5702018-01-06 19:39:49 -08009//! Parsing interface for parsing a token stream into a syntax tree node.
David Tolnayc5ab8c62017-12-26 16:43:39 -050010//!
David Tolnayca7cd972018-01-11 14:23:06 -080011//! 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 a [`ParseError`] if parsing failed.
David Tolnayc5ab8c62017-12-26 16:43:39 -050017//!
David Tolnayb34f5702018-01-06 19:39:49 -080018//! [`Cursor`]: ../buffer/index.html
David Tolnayca7cd972018-01-11 14:23:06 -080019//! [`PResult<T>`]: type.PResult.html
20//! [`ParseError`]: struct.ParseError.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
32//! implements the [`Synom`] trait, which includes most types in Syn.
33//!
34//! [`syn::parse`]: ../fn.parse.html
35//! [`syn::parse2`]: ../fn.parse2.html
36//! [`syn::parse_str`]: ../fn.parse_str.html
37//! [`Synom`]: trait.Synom.html
38//!
39//! ```
40//! use syn::Type;
41//!
42//! # fn run_parser() -> Result<(), syn::synom::ParseError> {
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 `Parser` trait
53//!
54//! Some types can be parsed in several ways depending on context. For example
55//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like
56//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`]
57//! may or may not allow trailing punctuation, and parsing it the wrong way
58//! would either reject valid input or accept invalid input.
59//!
60//! [`Attribute`]: ../struct.Attribute.html
61//! [`Punctuated`]: ../punctuated/index.html
62//!
63//! The `Synom` trait is not implemented in these cases because there is no good
64//! behavior to consider the default.
65//!
66//! ```ignore
67//! // Can't parse `Punctuated` without knowing whether trailing punctuation
68//! // should be allowed in this context.
69//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?;
70//! ```
71//!
72//! In these cases the types provide a choice of parser functions rather than a
73//! single `Synom` implementation, and those parser functions can be invoked
74//! through the [`Parser`] trait.
75//!
76//! [`Parser`]: trait.Parser.html
77//!
78//! ```
79//! # #[macro_use]
80//! # extern crate syn;
81//! #
82//! # extern crate proc_macro2;
83//! # use proc_macro2::TokenStream;
84//! #
85//! use syn::synom::Parser;
86//! use syn::punctuated::Punctuated;
87//! use syn::{PathSegment, Expr, Attribute};
88//!
89//! # fn run_parsers() -> Result<(), syn::synom::ParseError> {
90//! # let tokens = TokenStream::empty().into();
91//! // Parse a nonempty sequence of path segments separated by `::` punctuation
92//! // with no trailing punctuation.
93//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty;
94//! let path = parser.parse(tokens)?;
95//!
96//! # let tokens = TokenStream::empty().into();
97//! // Parse a possibly empty sequence of expressions terminated by commas with
98//! // an optional trailing punctuation.
99//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
100//! let args = parser.parse(tokens)?;
101//!
102//! # let tokens = TokenStream::empty().into();
103//! // Parse zero or more outer attributes but not inner attributes.
104//! named!(outer_attrs -> Vec<Attribute>, many0!(Attribute::parse_outer));
105//! let attrs = outer_attrs.parse(tokens)?;
106//! #
107//! # Ok(())
108//! # }
109//! #
110//! # fn main() {}
111//! ```
112//!
113//! # Implementing a parser function
114//!
115//! Parser functions are usually implemented using the [`nom`]-style parser
116//! combinator macros provided by Syn, but may also be implemented without
117//! macros be using the low-level [`Cursor`] API directly.
118//!
119//! [`nom`]: https://github.com/Geal/nom
David Tolnayc5ab8c62017-12-26 16:43:39 -0500120//!
David Tolnayb34f5702018-01-06 19:39:49 -0800121//! The following parser combinator macros are available and a `Synom` parsing
122//! example is provided for each one.
David Tolnayc5ab8c62017-12-26 16:43:39 -0500123//!
David Tolnayb34f5702018-01-06 19:39:49 -0800124//! - [`alt!`](../macro.alt.html)
125//! - [`braces!`](../macro.braces.html)
126//! - [`brackets!`](../macro.brackets.html)
127//! - [`call!`](../macro.call.html)
128//! - [`cond!`](../macro.cond.html)
129//! - [`cond_reduce!`](../macro.cond_reduce.html)
130//! - [`do_parse!`](../macro.do_parse.html)
131//! - [`epsilon!`](../macro.epsilon.html)
132//! - [`input_end!`](../macro.input_end.html)
133//! - [`keyword!`](../macro.keyword.html)
134//! - [`many0!`](../macro.many0.html)
135//! - [`map!`](../macro.map.html)
136//! - [`not!`](../macro.not.html)
137//! - [`option!`](../macro.option.html)
138//! - [`parens!`](../macro.parens.html)
139//! - [`punct!`](../macro.punct.html)
140//! - [`reject!`](../macro.reject.html)
141//! - [`switch!`](../macro.switch.html)
142//! - [`syn!`](../macro.syn.html)
143//! - [`tuple!`](../macro.tuple.html)
144//! - [`value!`](../macro.value.html)
David Tolnay461d98e2018-01-07 11:07:19 -0800145//!
146//! *This module is available if Syn is built with the `"parsing"` feature.*
David Tolnayc5ab8c62017-12-26 16:43:39 -0500147
David Tolnayca7cd972018-01-11 14:23:06 -0800148use proc_macro;
149use proc_macro2;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500150
David Tolnay203557a2017-12-27 23:59:33 -0500151pub use error::{PResult, ParseError};
David Tolnayc5ab8c62017-12-26 16:43:39 -0500152
David Tolnayca7cd972018-01-11 14:23:06 -0800153use buffer::{Cursor, TokenBuffer};
David Tolnaydfc886b2018-01-06 08:03:09 -0800154
David Tolnayca7cd972018-01-11 14:23:06 -0800155/// Parsing interface implemented by all types that can be parsed in a default
156/// way from a token stream.
David Tolnayb34f5702018-01-06 19:39:49 -0800157///
158/// Refer to the [module documentation] for details about parsing in Syn.
159///
160/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -0800161///
162/// *This trait is available if Syn is built with the `"parsing"` feature.*
David Tolnayc5ab8c62017-12-26 16:43:39 -0500163pub trait Synom: Sized {
164 fn parse(input: Cursor) -> PResult<Self>;
165
166 fn description() -> Option<&'static str> {
167 None
168 }
169}
170
David Tolnayca7cd972018-01-11 14:23:06 -0800171impl Synom for proc_macro2::TokenStream {
David Tolnayc5ab8c62017-12-26 16:43:39 -0500172 fn parse(input: Cursor) -> PResult<Self> {
David Tolnayf4aa6b42017-12-31 16:40:33 -0500173 Ok((input.token_stream(), Cursor::empty()))
David Tolnayc5ab8c62017-12-26 16:43:39 -0500174 }
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800175
176 fn description() -> Option<&'static str> {
177 Some("arbitrary token stream")
178 }
David Tolnayc5ab8c62017-12-26 16:43:39 -0500179}
David Tolnayca7cd972018-01-11 14:23:06 -0800180
181/// Parser that can parse Rust tokens into a particular syntax tree node.
182///
183/// Refer to the [module documentation] for details about parsing in Syn.
184///
185/// [module documentation]: index.html
186///
187/// *This trait is available if Syn is built with the `"parsing"` feature.*
188pub trait Parser: Sized {
189 type Output;
190
191 fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<Self::Output, ParseError>;
192
193 fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output, ParseError> {
194 self.parse2(tokens.into())
195 }
196
197 fn parse_str(self, s: &str) -> Result<Self::Output, ParseError> {
198 match s.parse() {
199 Ok(tts) => self.parse2(tts),
200 Err(_) => Err(ParseError::new("error while lexing input string")),
201 }
202 }
203}
204
205impl<F, T> Parser for F where F: FnOnce(Cursor) -> PResult<T> {
206 type Output = T;
207
208 fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<T, ParseError> {
209 let buf = TokenBuffer::new2(tokens);
210 let (t, rest) = self(buf.begin())?;
211 if rest.eof() {
212 Ok(t)
213 } else if rest == buf.begin() {
214 // parsed nothing
215 Err(ParseError::new("failed to parse anything"))
216 } else {
217 Err(ParseError::new("failed to parse all tokens"))
218 }
219 }
220}