standalone_syn/
synom.rs

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
9//! Parsing interface for parsing a token stream into a syntax tree node.
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 a [`ParseError`] if parsing failed.
17//!
18//! [`Cursor`]: ../buffer/index.html
19//! [`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 [`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//! #
89//! use syn::synom::Parser;
90//! use syn::punctuated::Punctuated;
91//! use syn::{PathSegment, Expr, Attribute};
92//!
93//! # fn run_parsers() -> Result<(), syn::synom::ParseError> {
94//! #     let tokens = TokenStream::empty().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::empty().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::empty().into();
107//! // Parse zero or more outer attributes but not inner attributes.
108//! named!(outer_attrs -> Vec<Attribute>, many0!(Attribute::parse_outer));
109//! let attrs = outer_attrs.parse(tokens)?;
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//! - [`do_parse!`](../macro.do_parse.html)
135//! - [`epsilon!`](../macro.epsilon.html)
136//! - [`input_end!`](../macro.input_end.html)
137//! - [`keyword!`](../macro.keyword.html)
138//! - [`many0!`](../macro.many0.html)
139//! - [`map!`](../macro.map.html)
140//! - [`not!`](../macro.not.html)
141//! - [`option!`](../macro.option.html)
142//! - [`parens!`](../macro.parens.html)
143//! - [`punct!`](../macro.punct.html)
144//! - [`reject!`](../macro.reject.html)
145//! - [`switch!`](../macro.switch.html)
146//! - [`syn!`](../macro.syn.html)
147//! - [`tuple!`](../macro.tuple.html)
148//! - [`value!`](../macro.value.html)
149//!
150//! *This module is available if Syn is built with the `"parsing"` feature.*
151
152#[cfg(feature = "proc-macro")]
153use proc_macro;
154use proc_macro2;
155
156pub use error::{PResult, ParseError};
157
158use buffer::{Cursor, TokenBuffer};
159
160/// Parsing interface implemented by all types that can be parsed in a default
161/// way from a token stream.
162///
163/// Refer to the [module documentation] for details about parsing in Syn.
164///
165/// [module documentation]: index.html
166///
167/// *This trait is available if Syn is built with the `"parsing"` feature.*
168pub trait Synom: Sized {
169    fn parse(input: Cursor) -> PResult<Self>;
170
171    fn description() -> Option<&'static str> {
172        None
173    }
174}
175
176impl Synom for proc_macro2::TokenStream {
177    fn parse(input: Cursor) -> PResult<Self> {
178        Ok((input.token_stream(), Cursor::empty()))
179    }
180
181    fn description() -> Option<&'static str> {
182        Some("arbitrary token stream")
183    }
184}
185
186/// Parser that can parse Rust tokens into a particular syntax tree node.
187///
188/// Refer to the [module documentation] for details about parsing in Syn.
189///
190/// [module documentation]: index.html
191///
192/// *This trait is available if Syn is built with the `"parsing"` feature.*
193pub trait Parser: Sized {
194    type Output;
195
196    /// Parse a proc-macro2 token stream into the chosen syntax tree node.
197    fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<Self::Output, ParseError>;
198
199    /// Parse tokens of source code into the chosen syntax tree node.
200    #[cfg(feature = "proc-macro")]
201    fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output, ParseError> {
202        self.parse2(tokens.into())
203    }
204
205    /// Parse a string of Rust code into the chosen syntax tree node.
206    ///
207    /// # Hygiene
208    ///
209    /// Every span in the resulting syntax tree will be set to resolve at the
210    /// macro call site.
211    fn parse_str(self, s: &str) -> Result<Self::Output, ParseError> {
212        match s.parse() {
213            Ok(tts) => self.parse2(tts),
214            Err(_) => Err(ParseError::new("error while lexing input string")),
215        }
216    }
217}
218
219impl<F, T> Parser for F where F: FnOnce(Cursor) -> PResult<T> {
220    type Output = T;
221
222    fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<T, ParseError> {
223        let buf = TokenBuffer::new2(tokens);
224        let (t, rest) = self(buf.begin())?;
225        if rest.eof() {
226            Ok(t)
227        } else if rest == buf.begin() {
228            // parsed nothing
229            Err(ParseError::new("failed to parse anything"))
230        } else {
231            Err(ParseError::new("failed to parse all tokens"))
232        }
233    }
234}