blob: 29f6e3d2020fce3748806e95c9d7e0b1baa02daf [file] [log] [blame]
David Tolnay30a36002017-02-08 14:24:12 -08001//! Adapted from [`nom`](https://github.com/Geal/nom) by removing the
Michael Layzell760fd662017-05-31 22:46:05 -04002//! `IPResult::Incomplete` variant which:
David Tolnay30a36002017-02-08 14:24:12 -08003//!
4//! - we don't need,
5//! - is an unintuitive footgun when working with non-streaming use cases, and
6//! - more than doubles compilation time.
7//!
8//! ## Whitespace handling strategy
9//!
10//! As (sy)nom is a parser combinator library, the parsers provided here and
11//! that you implement yourself are all made up of successively more primitive
12//! parsers, eventually culminating in a small number of fundamental parsers
13//! that are implemented in Rust. Among these are `punct!` and `keyword!`.
14//!
15//! All synom fundamental parsers (those not combined out of other parsers)
16//! should be written to skip over leading whitespace in their input. This way,
17//! as long as every parser eventually boils down to some combination of
18//! fundamental parsers, we get correct whitespace handling at all levels for
19//! free.
20//!
21//! For our use case, this strategy is a huge improvement in usability,
22//! correctness, and compile time over nom's `ws!` strategy.
David Tolnayb5a7b142016-09-13 22:46:39 -070023
Michael Layzell5bde96f2017-01-24 17:59:21 -050024extern crate unicode_xid;
Alex Crichton7b9e02f2017-05-30 15:54:33 -070025extern crate proc_macro2;
Michael Layzell5bde96f2017-01-24 17:59:21 -050026
Alex Crichtonccbb45d2017-05-23 10:58:24 -070027#[cfg(feature = "printing")]
28extern crate quote;
29
David Tolnay30a36002017-02-08 14:24:12 -080030#[doc(hidden)]
Alex Crichton954046c2017-05-30 21:49:42 -070031pub use proc_macro2::{TokenTree, TokenStream};
32
33use std::convert::From;
34use std::error::Error;
35use std::fmt;
36
37use proc_macro2::LexError;
Michael Layzell5bde96f2017-01-24 17:59:21 -050038
Alex Crichtonccbb45d2017-05-23 10:58:24 -070039#[cfg(feature = "parsing")]
David Tolnay5fe14fc2017-01-27 16:22:08 -080040#[doc(hidden)]
41pub mod helper;
Michael Layzell5bde96f2017-01-24 17:59:21 -050042
Alex Crichtonccbb45d2017-05-23 10:58:24 -070043pub mod delimited;
Alex Crichton7b9e02f2017-05-30 15:54:33 -070044pub mod tokens;
45pub mod span;
Michael Layzell2a60e252017-05-31 21:36:47 -040046pub mod cursor;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070047
Michael Layzell0a1a6632017-06-02 18:07:43 -040048pub use cursor::{SynomBuffer, Cursor};
David Tolnayb5a7b142016-09-13 22:46:39 -070049
Michael Layzell760fd662017-05-31 22:46:05 -040050/// The result of a parser
51pub type PResult<'a, O> = Result<(Cursor<'a>, O), ParseError>;
52
53/// An error with a default error message.
54///
55/// NOTE: We should provide better error messages in the future.
56pub fn parse_error<O>() -> PResult<'static, O> {
Michael Layzellad763b72017-06-01 00:25:31 -040057 Err(ParseError(None))
David Tolnayf2222f02017-01-27 17:09:20 -080058}
59
Alex Crichton7b9e02f2017-05-30 15:54:33 -070060pub trait Synom: Sized {
Michael Layzell760fd662017-05-31 22:46:05 -040061 fn parse(input: Cursor) -> PResult<Self>;
Alex Crichton954046c2017-05-30 21:49:42 -070062
63 fn description() -> Option<&'static str> {
64 None
65 }
66
67 fn parse_all(input: TokenStream) -> Result<Self, ParseError> {
Michael Layzell0a1a6632017-06-02 18:07:43 -040068 let buf = SynomBuffer::new(input);
Michael Layzell729a4a02017-06-04 18:59:57 -040069 let descr = Self::description().unwrap_or("unnamed parser");
70 let err = match Self::parse(buf.begin()) {
Michael Layzell760fd662017-05-31 22:46:05 -040071 Ok((rest, t)) => {
Michael Layzell0a1a6632017-06-02 18:07:43 -040072 if rest.eof() {
Alex Crichton954046c2017-05-30 21:49:42 -070073 return Ok(t)
Michael Layzell0a1a6632017-06-02 18:07:43 -040074 } else if rest == buf.begin() {
Alex Crichton954046c2017-05-30 21:49:42 -070075 // parsed nothing
Michael Layzell729a4a02017-06-04 18:59:57 -040076 format!("parsed no input while parsing {}", descr)
Alex Crichton954046c2017-05-30 21:49:42 -070077 } else {
Michael Layzell729a4a02017-06-04 18:59:57 -040078 // Partially parsed the output. Print the input which remained.
79 format!("unparsed tokens after parsing {}:\n{}",
80 descr, rest.token_stream())
Alex Crichton954046c2017-05-30 21:49:42 -070081 }
82 }
Michael Layzell729a4a02017-06-04 18:59:57 -040083 Err(ref err) => format!("{} while parsing {}", err.description(), descr),
Alex Crichton954046c2017-05-30 21:49:42 -070084 };
Michael Layzell729a4a02017-06-04 18:59:57 -040085 Err(ParseError(Some(err)))
Alex Crichton954046c2017-05-30 21:49:42 -070086 }
87
88 fn parse_str_all(input: &str) -> Result<Self, ParseError> {
89 Self::parse_all(input.parse()?)
90 }
91
92 fn parse_all_unwrap(input: TokenStream) -> Self {
93 // TODO: eventually try to provide super nice error messages here as
94 // this is what most users will hit. Hopefully the compiler will give us
95 // an interface one day to give an extra-good error message here.
96 Self::parse_all(input).unwrap()
97 }
98}
99
100#[derive(Debug)]
Michael Layzellad763b72017-06-01 00:25:31 -0400101pub struct ParseError(Option<String>);
Alex Crichton954046c2017-05-30 21:49:42 -0700102
103impl Error for ParseError {
104 fn description(&self) -> &str {
Michael Layzellad763b72017-06-01 00:25:31 -0400105 match self.0 {
106 Some(ref desc) => desc,
107 None => "failed to parse",
108 }
Alex Crichton954046c2017-05-30 21:49:42 -0700109 }
110}
111
112impl fmt::Display for ParseError {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Michael Layzellad763b72017-06-01 00:25:31 -0400114 <str as fmt::Display>::fmt(self.description(), f)
Alex Crichton954046c2017-05-30 21:49:42 -0700115 }
116}
117
118impl From<LexError> for ParseError {
119 fn from(_: LexError) -> ParseError {
Michael Layzellad763b72017-06-01 00:25:31 -0400120 ParseError(Some("error while lexing input string".to_owned()))
Alex Crichton954046c2017-05-30 21:49:42 -0700121 }
122}
123
124impl Synom for TokenStream {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400125 fn parse(input: Cursor) -> PResult<Self> {
126 Ok((Cursor::empty(), input.token_stream()))
Alex Crichton954046c2017-05-30 21:49:42 -0700127 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700128}
129
Michael Layzell24645a32017-02-04 13:19:26 -0500130/// Define a function from a parser combination.
131///
David Tolnay1f16b602017-02-07 20:06:55 -0500132/// - **Syntax:** `named!(NAME -> TYPE, PARSER)` or `named!(pub NAME -> TYPE, PARSER)`
133///
134/// ```rust
135/// # extern crate syn;
136/// # #[macro_use] extern crate synom;
137/// # use syn::Ty;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700138/// # use synom::delimited::Delimited;
Alex Crichton954046c2017-05-30 21:49:42 -0700139/// # use synom::tokens::Comma;
David Tolnay1f16b602017-02-07 20:06:55 -0500140/// // One or more Rust types separated by commas.
Alex Crichton954046c2017-05-30 21:49:42 -0700141/// named!(pub comma_separated_types -> Delimited<Ty, Comma>,
142/// call!(Delimited::parse_separated_nonempty)
David Tolnay1f16b602017-02-07 20:06:55 -0500143/// );
144/// # fn main() {}
145/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500146#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700147macro_rules! named {
148 ($name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400149 fn $name(i: $crate::Cursor) -> $crate::PResult<$o> {
David Tolnayb5a7b142016-09-13 22:46:39 -0700150 $submac!(i, $($args)*)
151 }
152 };
153
154 (pub $name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400155 pub fn $name(i: $crate::Cursor) -> $crate::PResult<$o> {
David Tolnayb5a7b142016-09-13 22:46:39 -0700156 $submac!(i, $($args)*)
157 }
158 };
159}
160
David Tolnay1f16b602017-02-07 20:06:55 -0500161/// Invoke the given parser function with the passed in arguments.
Michael Layzell24645a32017-02-04 13:19:26 -0500162///
163/// - **Syntax:** `call!(FUNCTION, ARGS...)`
David Tolnay1f16b602017-02-07 20:06:55 -0500164///
Michael Layzell760fd662017-05-31 22:46:05 -0400165/// where the signature of the function is `fn(&[U], ARGS...) -> IPResult<&[U], T>`
David Tolnay1f16b602017-02-07 20:06:55 -0500166/// - **Output:** `T`, the result of invoking the function `FUNCTION`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500167#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700168macro_rules! call {
David Tolnayaf2557e2016-10-24 11:52:21 -0700169 ($i:expr, $fun:expr $(, $args:expr)*) => {
170 $fun($i $(, $args)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700171 };
172}
173
David Tolnay1f16b602017-02-07 20:06:55 -0500174/// Transform the result of a parser by applying a function or closure.
Michael Layzell24645a32017-02-04 13:19:26 -0500175///
David Tolnay1f16b602017-02-07 20:06:55 -0500176/// - **Syntax:** `map!(THING, FN)`
177/// - **Output:** the return type of function FN applied to THING
Michael Layzell24645a32017-02-04 13:19:26 -0500178///
179/// ```rust
180/// extern crate syn;
181/// #[macro_use] extern crate synom;
182///
David Tolnayb21bb0c2017-06-03 20:39:19 -0700183/// use syn::{Expr, ExprIf};
Michael Layzell24645a32017-02-04 13:19:26 -0500184///
David Tolnayb21bb0c2017-06-03 20:39:19 -0700185/// fn get_cond(if_: ExprIf) -> Expr {
186/// *if_.cond
Michael Layzell24645a32017-02-04 13:19:26 -0500187/// }
188///
David Tolnayb21bb0c2017-06-03 20:39:19 -0700189/// // Parses an `if` statement but returns the condition part only.
190/// named!(if_condition -> Expr,
191/// map!(syn!(ExprIf), get_cond)
David Tolnay1f16b602017-02-07 20:06:55 -0500192/// );
193///
194/// // Or equivalently:
David Tolnayb21bb0c2017-06-03 20:39:19 -0700195/// named!(if_condition2 -> Expr,
David Tolnaybc7d7d92017-06-03 20:54:05 -0700196/// map!(syn!(ExprIf), |if_| *if_.cond)
David Tolnay1f16b602017-02-07 20:06:55 -0500197/// );
David Tolnayb21bb0c2017-06-03 20:39:19 -0700198/// #
Alex Crichton954046c2017-05-30 21:49:42 -0700199/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500200/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500201#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700202macro_rules! map {
203 ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700204 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400205 ::std::result::Result::Err(err) =>
206 ::std::result::Result::Err(err),
207 ::std::result::Result::Ok((i, o)) =>
David Tolnaybc7d7d92017-06-03 20:54:05 -0700208 ::std::result::Result::Ok((i, $crate::invoke($g, o))),
David Tolnayb5a7b142016-09-13 22:46:39 -0700209 }
210 };
David Tolnay1f16b602017-02-07 20:06:55 -0500211
212 ($i:expr, $f:expr, $g:expr) => {
213 map!($i, call!($f), $g)
214 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700215}
216
David Tolnaybc7d7d92017-06-03 20:54:05 -0700217// Somehow this helps with type inference in `map!`.
218//
219// Not public API.
220#[doc(hidden)]
221pub fn invoke<T, R, F: FnOnce(T) -> R>(f: F, t: T) -> R {
222 f(t)
223}
224
David Tolnay1f16b602017-02-07 20:06:55 -0500225/// Parses successfully if the given parser fails to parse. Does not consume any
226/// of the input.
Michael Layzell24645a32017-02-04 13:19:26 -0500227///
228/// - **Syntax:** `not!(THING)`
David Tolnay1f16b602017-02-07 20:06:55 -0500229/// - **Output:** `()`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500230#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700231macro_rules! not {
232 ($i:expr, $submac:ident!( $($args:tt)* )) => {
233 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400234 ::std::result::Result::Ok(_) => $crate::parse_error(),
235 ::std::result::Result::Err(_) =>
236 ::std::result::Result::Ok(($i, ())),
David Tolnayb5a7b142016-09-13 22:46:39 -0700237 }
238 };
239}
240
David Tolnay1f16b602017-02-07 20:06:55 -0500241/// Conditionally execute the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500242///
David Tolnay1f16b602017-02-07 20:06:55 -0500243/// If you are familiar with nom, this is nom's `cond_with_error` parser.
244///
245/// - **Syntax:** `cond!(CONDITION, THING)`
246/// - **Output:** `Some(THING)` if the condition is true, else `None`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500247#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700248macro_rules! cond {
249 ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => {
250 if $cond {
251 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400252 ::std::result::Result::Ok((i, o)) =>
253 ::std::result::Result::Ok((i, ::std::option::Option::Some(o))),
254 ::std::result::Result::Err(x) => ::std::result::Result::Err(x),
David Tolnayb5a7b142016-09-13 22:46:39 -0700255 }
256 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400257 ::std::result::Result::Ok(($i, ::std::option::Option::None))
David Tolnayb5a7b142016-09-13 22:46:39 -0700258 }
David Tolnaycfe55022016-10-02 22:02:27 -0700259 };
260
261 ($i:expr, $cond:expr, $f:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700262 cond!($i, $cond, call!($f))
David Tolnaycfe55022016-10-02 22:02:27 -0700263 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700264}
265
David Tolnay1f16b602017-02-07 20:06:55 -0500266/// Fail to parse if condition is false, otherwise parse the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500267///
David Tolnay1f16b602017-02-07 20:06:55 -0500268/// This is typically used inside of `option!` or `alt!`.
269///
270/// - **Syntax:** `cond_reduce!(CONDITION, THING)`
271/// - **Output:** `THING`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500272#[macro_export]
David Tolnayaf2557e2016-10-24 11:52:21 -0700273macro_rules! cond_reduce {
274 ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => {
275 if $cond {
276 $submac!($i, $($args)*)
277 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400278 $crate::parse_error()
David Tolnayaf2557e2016-10-24 11:52:21 -0700279 }
280 };
281
282 ($i:expr, $cond:expr, $f:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700283 cond_reduce!($i, $cond, call!($f))
David Tolnayaf2557e2016-10-24 11:52:21 -0700284 };
285}
286
David Tolnay1f16b602017-02-07 20:06:55 -0500287/// Parse two things, returning the value of the first.
Michael Layzell24645a32017-02-04 13:19:26 -0500288///
David Tolnay1f16b602017-02-07 20:06:55 -0500289/// - **Syntax:** `terminated!(THING, AFTER)`
Michael Layzell24645a32017-02-04 13:19:26 -0500290/// - **Output:** `THING`
291///
292/// ```rust
293/// extern crate syn;
294/// #[macro_use] extern crate synom;
295///
296/// use syn::Expr;
Alex Crichton954046c2017-05-30 21:49:42 -0700297/// use synom::tokens::Pound;
Michael Layzell24645a32017-02-04 13:19:26 -0500298///
299/// // An expression terminated by ##.
300/// named!(expr_pound_pound -> Expr,
Alex Crichton954046c2017-05-30 21:49:42 -0700301/// terminated!(syn!(Expr), tuple!(syn!(Pound), syn!(Pound)))
David Tolnay1f16b602017-02-07 20:06:55 -0500302/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500303///
Alex Crichton954046c2017-05-30 21:49:42 -0700304/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500305/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500306#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700307macro_rules! terminated {
308 ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => {
309 match tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) {
Michael Layzell760fd662017-05-31 22:46:05 -0400310 ::std::result::Result::Ok((i, (o, _))) =>
311 ::std::result::Result::Ok((i, o)),
312 ::std::result::Result::Err(err) =>
313 ::std::result::Result::Err(err),
David Tolnayb5a7b142016-09-13 22:46:39 -0700314 }
315 };
316
317 ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700318 terminated!($i, $submac!($($args)*), call!($g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700319 };
320
321 ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700322 terminated!($i, call!($f), $submac!($($args)*))
David Tolnayb5a7b142016-09-13 22:46:39 -0700323 };
324
325 ($i:expr, $f:expr, $g:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700326 terminated!($i, call!($f), call!($g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700327 };
328}
329
David Tolnay1f16b602017-02-07 20:06:55 -0500330/// Parse zero or more values using the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500331///
332/// - **Syntax:** `many0!(THING)`
333/// - **Output:** `Vec<THING>`
334///
David Tolnay1f16b602017-02-07 20:06:55 -0500335/// You may also be looking for:
336///
Alex Crichton954046c2017-05-30 21:49:42 -0700337/// - `call!(Delimited::parse_separated)` - zero or more values with separator
338/// - `call!(Delimited::parse_separated_nonempty)` - one or more values
339/// - `call!(Delimited::parse_terminated)` - zero or more, allows trailing separator
David Tolnay1f16b602017-02-07 20:06:55 -0500340///
Michael Layzell24645a32017-02-04 13:19:26 -0500341/// ```rust
342/// extern crate syn;
343/// #[macro_use] extern crate synom;
344///
345/// use syn::Item;
Michael Layzell24645a32017-02-04 13:19:26 -0500346///
Alex Crichton954046c2017-05-30 21:49:42 -0700347/// named!(items -> Vec<Item>, many0!(syn!(Item)));
Michael Layzell24645a32017-02-04 13:19:26 -0500348///
Alex Crichton954046c2017-05-30 21:49:42 -0700349/// # fn main() {}
Michael Layzell5bde96f2017-01-24 17:59:21 -0500350#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700351macro_rules! many0 {
352 ($i:expr, $submac:ident!( $($args:tt)* )) => {{
353 let ret;
354 let mut res = ::std::vec::Vec::new();
355 let mut input = $i;
356
357 loop {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400358 if input.eof() {
Michael Layzell760fd662017-05-31 22:46:05 -0400359 ret = ::std::result::Result::Ok((input, res));
David Tolnayb5a7b142016-09-13 22:46:39 -0700360 break;
361 }
362
363 match $submac!(input, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400364 ::std::result::Result::Err(_) => {
365 ret = ::std::result::Result::Ok((input, res));
David Tolnayb5a7b142016-09-13 22:46:39 -0700366 break;
367 }
Michael Layzell760fd662017-05-31 22:46:05 -0400368 ::std::result::Result::Ok((i, o)) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700369 // loop trip must always consume (otherwise infinite loops)
Michael Layzell0a1a6632017-06-02 18:07:43 -0400370 if i == input {
Michael Layzell760fd662017-05-31 22:46:05 -0400371 ret = $crate::parse_error();
David Tolnayb5a7b142016-09-13 22:46:39 -0700372 break;
373 }
374
375 res.push(o);
376 input = i;
377 }
378 }
379 }
380
381 ret
382 }};
383
384 ($i:expr, $f:expr) => {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500385 $crate::many0($i, $f)
David Tolnayb5a7b142016-09-13 22:46:39 -0700386 };
387}
388
David Tolnay1f16b602017-02-07 20:06:55 -0500389// Improve compile time by compiling this loop only once per type it is used
390// with.
391//
David Tolnay5fe14fc2017-01-27 16:22:08 -0800392// Not public API.
393#[doc(hidden)]
Michael Layzell760fd662017-05-31 22:46:05 -0400394pub fn many0<'a, T>(mut input: Cursor, f: fn(Cursor) -> PResult<T>) -> PResult<Vec<T>> {
David Tolnaybc84d5a2016-10-08 13:20:57 -0700395 let mut res = Vec::new();
396
397 loop {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400398 if input.eof() {
Michael Layzell760fd662017-05-31 22:46:05 -0400399 return Ok((input, res));
David Tolnaybc84d5a2016-10-08 13:20:57 -0700400 }
401
402 match f(input) {
Michael Layzell760fd662017-05-31 22:46:05 -0400403 Err(_) => {
404 return Ok((input, res));
David Tolnaybc84d5a2016-10-08 13:20:57 -0700405 }
Michael Layzell760fd662017-05-31 22:46:05 -0400406 Ok((i, o)) => {
David Tolnaybc84d5a2016-10-08 13:20:57 -0700407 // loop trip must always consume (otherwise infinite loops)
Michael Layzell0a1a6632017-06-02 18:07:43 -0400408 if i == input {
Michael Layzell760fd662017-05-31 22:46:05 -0400409 return parse_error();
David Tolnaybc84d5a2016-10-08 13:20:57 -0700410 }
411
412 res.push(o);
413 input = i;
414 }
415 }
416 }
417}
418
David Tolnay1f16b602017-02-07 20:06:55 -0500419/// Parse a value without consuming it from the input data.
Michael Layzell24645a32017-02-04 13:19:26 -0500420///
421/// - **Syntax:** `peek!(THING)`
David Tolnay1f16b602017-02-07 20:06:55 -0500422/// - **Output:** `THING`
Michael Layzell24645a32017-02-04 13:19:26 -0500423///
424/// ```rust
425/// extern crate syn;
426/// #[macro_use] extern crate synom;
427///
Alex Crichton954046c2017-05-30 21:49:42 -0700428/// use syn::{Expr, Ident};
Michael Layzell24645a32017-02-04 13:19:26 -0500429///
David Tolnay1f16b602017-02-07 20:06:55 -0500430/// // Parse an expression that begins with an identifier.
Alex Crichton954046c2017-05-30 21:49:42 -0700431/// named!(ident_expr -> (Ident, Expr),
432/// tuple!(peek!(syn!(Ident)), syn!(Expr))
David Tolnay1f16b602017-02-07 20:06:55 -0500433/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500434///
Alex Crichton954046c2017-05-30 21:49:42 -0700435/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500436/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500437#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700438macro_rules! peek {
439 ($i:expr, $submac:ident!( $($args:tt)* )) => {
440 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400441 ::std::result::Result::Ok((_, o)) => ::std::result::Result::Ok(($i, o)),
442 ::std::result::Result::Err(err) => ::std::result::Result::Err(err),
David Tolnayb5a7b142016-09-13 22:46:39 -0700443 }
444 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700445
David Tolnay1f16b602017-02-07 20:06:55 -0500446 ($i:expr, $f:expr) => {
447 peek!($i, call!($f))
David Tolnayb5a7b142016-09-13 22:46:39 -0700448 };
449}
450
David Tolnay1f16b602017-02-07 20:06:55 -0500451/// Pattern-match the result of a parser to select which other parser to run.
452///
453/// - **Syntax:** `switch!(TARGET, PAT1 => THEN1 | PAT2 => THEN2 | ...)`
454/// - **Output:** `T`, the return type of `THEN1` and `THEN2` and ...
455///
456/// ```rust
457/// extern crate syn;
458/// #[macro_use] extern crate synom;
459///
460/// use syn::{Ident, Ty};
Alex Crichton954046c2017-05-30 21:49:42 -0700461/// use synom::tokens::*;
David Tolnay1f16b602017-02-07 20:06:55 -0500462///
463/// #[derive(Debug)]
464/// enum UnitType {
465/// Struct {
466/// name: Ident,
467/// },
468/// Enum {
469/// name: Ident,
470/// variant: Ident,
471/// },
472/// }
473///
474/// // Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
475/// named!(unit_type -> UnitType, do_parse!(
Alex Crichton954046c2017-05-30 21:49:42 -0700476/// which: alt!(
477/// syn!(Struct) => { |_| 0 }
478/// |
479/// syn!(Enum) => { |_| 1 }
480/// ) >>
481/// id: syn!(Ident) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500482/// item: switch!(value!(which),
Alex Crichton954046c2017-05-30 21:49:42 -0700483/// 0 => map!(
484/// syn!(Semi),
David Tolnay1f16b602017-02-07 20:06:55 -0500485/// move |_| UnitType::Struct {
486/// name: id,
487/// }
488/// )
489/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700490/// 1 => map!(
491/// braces!(syn!(Ident)),
492/// move |(variant, _)| UnitType::Enum {
David Tolnay1f16b602017-02-07 20:06:55 -0500493/// name: id,
494/// variant: variant,
495/// }
496/// )
497/// ) >>
498/// (item)
499/// ));
500///
Alex Crichton954046c2017-05-30 21:49:42 -0700501/// # fn main() {}
David Tolnay1f16b602017-02-07 20:06:55 -0500502/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500503#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700504macro_rules! switch {
505 ($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => {
506 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400507 ::std::result::Result::Err(err) => ::std::result::Result::Err(err),
508 ::std::result::Result::Ok((i, o)) => match o {
David Tolnayb5a7b142016-09-13 22:46:39 -0700509 $(
510 $p => $subrule!(i, $($args2)*),
511 )*
Michael Layzell760fd662017-05-31 22:46:05 -0400512 _ => $crate::parse_error(),
David Tolnayb5a7b142016-09-13 22:46:39 -0700513 }
514 }
515 };
516}
517
Alex Crichton954046c2017-05-30 21:49:42 -0700518
David Tolnay1f16b602017-02-07 20:06:55 -0500519/// Produce the given value without parsing anything. Useful as an argument to
520/// `switch!`.
521///
522/// - **Syntax:** `value!(VALUE)`
523/// - **Output:** `VALUE`
524///
525/// ```rust
526/// extern crate syn;
527/// #[macro_use] extern crate synom;
528///
529/// use syn::{Ident, Ty};
Alex Crichton954046c2017-05-30 21:49:42 -0700530/// use synom::tokens::*;
David Tolnay1f16b602017-02-07 20:06:55 -0500531///
532/// #[derive(Debug)]
533/// enum UnitType {
534/// Struct {
535/// name: Ident,
536/// },
537/// Enum {
538/// name: Ident,
539/// variant: Ident,
540/// },
541/// }
542///
543/// // Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
544/// named!(unit_type -> UnitType, do_parse!(
Alex Crichton954046c2017-05-30 21:49:42 -0700545/// which: alt!(
546/// syn!(Struct) => { |_| 0 }
547/// |
548/// syn!(Enum) => { |_| 1 }
549/// ) >>
550/// id: syn!(Ident) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500551/// item: switch!(value!(which),
Alex Crichton954046c2017-05-30 21:49:42 -0700552/// 0 => map!(
553/// syn!(Semi),
David Tolnay1f16b602017-02-07 20:06:55 -0500554/// move |_| UnitType::Struct {
555/// name: id,
556/// }
557/// )
558/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700559/// 1 => map!(
560/// braces!(syn!(Ident)),
561/// move |(variant, _)| UnitType::Enum {
David Tolnay1f16b602017-02-07 20:06:55 -0500562/// name: id,
563/// variant: variant,
564/// }
565/// )
566/// ) >>
567/// (item)
568/// ));
569///
Alex Crichton954046c2017-05-30 21:49:42 -0700570/// # fn main() {}
David Tolnay1f16b602017-02-07 20:06:55 -0500571/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500572#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700573macro_rules! value {
574 ($i:expr, $res:expr) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400575 ::std::result::Result::Ok(($i, $res))
David Tolnayb5a7b142016-09-13 22:46:39 -0700576 };
577}
578
David Tolnay1f16b602017-02-07 20:06:55 -0500579/// Run a series of parsers and produce all of the results in a tuple.
Michael Layzell24645a32017-02-04 13:19:26 -0500580///
David Tolnay1f16b602017-02-07 20:06:55 -0500581/// - **Syntax:** `tuple!(A, B, C, ...)`
582/// - **Output:** `(A, B, C, ...)`
Michael Layzell24645a32017-02-04 13:19:26 -0500583///
584/// ```rust
585/// extern crate syn;
586/// #[macro_use] extern crate synom;
587///
588/// use syn::Ty;
Michael Layzell24645a32017-02-04 13:19:26 -0500589///
Alex Crichton954046c2017-05-30 21:49:42 -0700590/// named!(two_types -> (Ty, Ty), tuple!(syn!(Ty), syn!(Ty)));
Michael Layzell24645a32017-02-04 13:19:26 -0500591///
Alex Crichton954046c2017-05-30 21:49:42 -0700592/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500593/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500594#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700595macro_rules! tuple {
596 ($i:expr, $($rest:tt)*) => {
597 tuple_parser!($i, (), $($rest)*)
598 };
599}
600
David Tolnay1f16b602017-02-07 20:06:55 -0500601/// Internal parser, do not use directly.
Michael Layzell5bde96f2017-01-24 17:59:21 -0500602#[doc(hidden)]
603#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700604macro_rules! tuple_parser {
605 ($i:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700606 tuple_parser!($i, ($($parsed),*), call!($e), $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700607 };
608
609 ($i:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => {
610 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400611 ::std::result::Result::Err(err) =>
612 ::std::result::Result::Err(err),
613 ::std::result::Result::Ok((i, o)) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700614 tuple_parser!(i, (o), $($rest)*),
615 }
616 };
617
618 ($i:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => {
619 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400620 ::std::result::Result::Err(err) =>
621 ::std::result::Result::Err(err),
622 ::std::result::Result::Ok((i, o)) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700623 tuple_parser!(i, ($($parsed)* , o), $($rest)*),
624 }
625 };
626
627 ($i:expr, ($($parsed:tt),*), $e:ident) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700628 tuple_parser!($i, ($($parsed),*), call!($e))
David Tolnayb5a7b142016-09-13 22:46:39 -0700629 };
630
631 ($i:expr, (), $submac:ident!( $($args:tt)* )) => {
632 $submac!($i, $($args)*)
633 };
634
635 ($i:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => {
636 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400637 ::std::result::Result::Err(err) =>
638 ::std::result::Result::Err(err),
639 ::std::result::Result::Ok((i, o)) =>
640 ::std::result::Result::Ok((i, ($($parsed),*, o))),
David Tolnayb5a7b142016-09-13 22:46:39 -0700641 }
642 };
643
644 ($i:expr, ($($parsed:expr),*)) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400645 ::std::result::Result::Ok(($i, ($($parsed),*)))
David Tolnayb5a7b142016-09-13 22:46:39 -0700646 };
647}
648
David Tolnay1f16b602017-02-07 20:06:55 -0500649/// Run a series of parsers, returning the result of the first one which
650/// succeeds.
Michael Layzell24645a32017-02-04 13:19:26 -0500651///
652/// Optionally allows for the result to be transformed.
653///
654/// - **Syntax:** `alt!(THING1 | THING2 => { FUNC } | ...)`
David Tolnay1f16b602017-02-07 20:06:55 -0500655/// - **Output:** `T`, the return type of `THING1` and `FUNC(THING2)` and ...
Michael Layzell24645a32017-02-04 13:19:26 -0500656///
657/// ```rust
658/// extern crate syn;
659/// #[macro_use] extern crate synom;
660///
661/// use syn::Ident;
Alex Crichton954046c2017-05-30 21:49:42 -0700662/// use synom::tokens::Bang;
Michael Layzell24645a32017-02-04 13:19:26 -0500663///
664/// named!(ident_or_bang -> Ident,
David Tolnay1f16b602017-02-07 20:06:55 -0500665/// alt!(
Alex Crichton954046c2017-05-30 21:49:42 -0700666/// syn!(Ident)
David Tolnay1f16b602017-02-07 20:06:55 -0500667/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700668/// syn!(Bang) => { |_| "BANG".into() }
David Tolnay1f16b602017-02-07 20:06:55 -0500669/// )
670/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500671///
Alex Crichton954046c2017-05-30 21:49:42 -0700672/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500673/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500674#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700675macro_rules! alt {
676 ($i:expr, $e:ident | $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700677 alt!($i, call!($e) | $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700678 };
679
680 ($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => {
681 match $subrule!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400682 res @ ::std::result::Result::Ok(_) => res,
David Tolnayb5a7b142016-09-13 22:46:39 -0700683 _ => alt!($i, $($rest)*)
684 }
685 };
686
687 ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => {
688 match $subrule!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400689 ::std::result::Result::Ok((i, o)) =>
690 ::std::result::Result::Ok((i, $gen(o))),
691 ::std::result::Result::Err(_) => alt!($i, $($rest)*),
David Tolnayb5a7b142016-09-13 22:46:39 -0700692 }
693 };
694
695 ($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700696 alt!($i, call!($e) => { $gen } | $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700697 };
698
699 ($i:expr, $e:ident => { $gen:expr }) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700700 alt!($i, call!($e) => { $gen })
David Tolnayb5a7b142016-09-13 22:46:39 -0700701 };
702
703 ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => {
704 match $subrule!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400705 ::std::result::Result::Ok((i, o)) =>
706 ::std::result::Result::Ok((i, $gen(o))),
707 ::std::result::Result::Err(err) =>
708 ::std::result::Result::Err(err),
David Tolnayb5a7b142016-09-13 22:46:39 -0700709 }
710 };
711
712 ($i:expr, $e:ident) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700713 alt!($i, call!($e))
David Tolnayb5a7b142016-09-13 22:46:39 -0700714 };
715
716 ($i:expr, $subrule:ident!( $($args:tt)*)) => {
David Tolnay5377b172016-10-25 01:13:12 -0700717 $subrule!($i, $($args)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700718 };
719}
720
Michael Layzell24645a32017-02-04 13:19:26 -0500721/// Run a series of parsers, one after another, optionally assigning the results
David Tolnay1f16b602017-02-07 20:06:55 -0500722/// a name. Fail if any of the parsers fails.
Michael Layzell24645a32017-02-04 13:19:26 -0500723///
David Tolnay1f16b602017-02-07 20:06:55 -0500724/// Produces the result of evaluating the final expression in parentheses with
725/// all of the previously named results bound.
Michael Layzell24645a32017-02-04 13:19:26 -0500726///
David Tolnay1f16b602017-02-07 20:06:55 -0500727/// - **Syntax:** `do_parse!(name: THING1 >> THING2 >> (RESULT))`
Michael Layzell24645a32017-02-04 13:19:26 -0500728/// - **Output:** `RESULT`
729///
730/// ```rust
731/// extern crate syn;
732/// #[macro_use] extern crate synom;
Alex Crichton954046c2017-05-30 21:49:42 -0700733/// extern crate proc_macro2;
Michael Layzell24645a32017-02-04 13:19:26 -0500734///
735/// use syn::{Ident, TokenTree};
Alex Crichton954046c2017-05-30 21:49:42 -0700736/// use synom::tokens::{Bang, Paren};
737/// use proc_macro2::TokenStream;
Michael Layzell24645a32017-02-04 13:19:26 -0500738///
David Tolnay1f16b602017-02-07 20:06:55 -0500739/// // Parse a macro invocation like `stringify!($args)`.
Alex Crichton954046c2017-05-30 21:49:42 -0700740/// named!(simple_mac -> (Ident, (TokenStream, Paren)), do_parse!(
741/// name: syn!(Ident) >>
742/// syn!(Bang) >>
743/// body: parens!(syn!(TokenStream)) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500744/// (name, body)
745/// ));
Michael Layzell24645a32017-02-04 13:19:26 -0500746///
Alex Crichton954046c2017-05-30 21:49:42 -0700747/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500748/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500749#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700750macro_rules! do_parse {
751 ($i:expr, ( $($rest:expr),* )) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400752 ::std::result::Result::Ok(($i, ( $($rest),* )))
David Tolnayb5a7b142016-09-13 22:46:39 -0700753 };
754
755 ($i:expr, $e:ident >> $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700756 do_parse!($i, call!($e) >> $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700757 };
758
759 ($i:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
760 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400761 ::std::result::Result::Err(err) =>
762 ::std::result::Result::Err(err),
763 ::std::result::Result::Ok((i, _)) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700764 do_parse!(i, $($rest)*),
765 }
766 };
767
768 ($i:expr, $field:ident : $e:ident >> $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700769 do_parse!($i, $field: call!($e) >> $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700770 };
771
772 ($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
773 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400774 ::std::result::Result::Err(err) =>
775 ::std::result::Result::Err(err),
776 ::std::result::Result::Ok((i, o)) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700777 let $field = o;
778 do_parse!(i, $($rest)*)
779 },
780 }
781 };
782
David Tolnayfa0edf22016-09-23 22:58:24 -0700783 ($i:expr, mut $field:ident : $e:ident >> $($rest:tt)*) => {
David Tolnay7184b132016-10-30 10:06:37 -0700784 do_parse!($i, mut $field: call!($e) >> $($rest)*)
David Tolnayfa0edf22016-09-23 22:58:24 -0700785 };
786
787 ($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
788 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400789 ::std::result::Result::Err(err) =>
790 ::std::result::Result::Err(err),
791 ::std::result::Result::Ok((i, o)) => {
David Tolnayfa0edf22016-09-23 22:58:24 -0700792 let mut $field = o;
793 do_parse!(i, $($rest)*)
794 },
795 }
796 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700797}
Michael Layzell416724e2017-05-24 21:12:34 -0400798
799#[macro_export]
800macro_rules! input_end {
801 ($i:expr,) => {
802 $crate::input_end($i)
803 };
804}
805
806// Not a public API
807#[doc(hidden)]
Michael Layzell760fd662017-05-31 22:46:05 -0400808pub fn input_end(input: Cursor) -> PResult<'static, &'static str> {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400809 if input.eof() {
810 Ok((Cursor::empty(), ""))
Michael Layzell416724e2017-05-24 21:12:34 -0400811 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400812 parse_error()
Michael Layzell416724e2017-05-24 21:12:34 -0400813 }
814}