blob: c5e364b6f37f929fda703540f3a1df145f1c83a3 [file] [log] [blame]
David Tolnay30a36002017-02-08 14:24:12 -08001//! Adapted from [`nom`](https://github.com/Geal/nom) by removing the
2//! `IResult::Incomplete` variant which:
3//!
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;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070046
Michael Layzell24645a32017-02-04 13:19:26 -050047/// The result of a parser.
David Tolnayb5a7b142016-09-13 22:46:39 -070048#[derive(Debug, PartialEq, Eq, Clone)]
49pub enum IResult<I, O> {
David Tolnayf2222f02017-01-27 17:09:20 -080050 /// Parsing succeeded. The first field contains the rest of the unparsed
51 /// data and the second field contains the parse result.
David Tolnayb5a7b142016-09-13 22:46:39 -070052 Done(I, O),
David Tolnayf2222f02017-01-27 17:09:20 -080053 /// Parsing failed.
David Tolnayb5a7b142016-09-13 22:46:39 -070054 Error,
55}
56
Michael Layzell416724e2017-05-24 21:12:34 -040057impl<'a, O> IResult<&'a [TokenTree], O> {
Michael Layzell24645a32017-02-04 13:19:26 -050058 /// Unwraps the result, asserting the the parse is complete. Panics with a
59 /// message based on the given string if the parse failed or is incomplete.
David Tolnayf2222f02017-01-27 17:09:20 -080060 pub fn expect(self, name: &str) -> O {
61 match self {
Michael Layzell416724e2017-05-24 21:12:34 -040062 IResult::Done(rest, o) => {
David Tolnayf2222f02017-01-27 17:09:20 -080063 if rest.is_empty() {
64 o
65 } else {
Michael Layzell416724e2017-05-24 21:12:34 -040066 panic!("unparsed tokens after {}: {:?}", name, /* rest */ ())
David Tolnayf2222f02017-01-27 17:09:20 -080067 }
68 }
69 IResult::Error => panic!("failed to parse {}", name),
70 }
71 }
72}
73
Alex Crichton7b9e02f2017-05-30 15:54:33 -070074pub trait Synom: Sized {
75 fn parse(input: &[TokenTree]) -> IResult<&[TokenTree], Self>;
Alex Crichton954046c2017-05-30 21:49:42 -070076
77 fn description() -> Option<&'static str> {
78 None
79 }
80
81 fn parse_all(input: TokenStream) -> Result<Self, ParseError> {
82 let tokens = input.into_iter().collect::<Vec<_>>();
83 let err = match Self::parse(&tokens) {
84 IResult::Done(rest, t) => {
85 if rest.is_empty() {
86 return Ok(t)
87 } else if rest.len() == tokens.len() {
88 // parsed nothing
89 "failed to parse"
90 } else {
91 "unparsed tokens after"
92 }
93 }
94 IResult::Error => "failed to parse"
95 };
96 match Self::description() {
97 Some(s) => Err(ParseError(format!("{} {}", err, s))),
98 None => Err(ParseError(err.to_string())),
99 }
100 }
101
102 fn parse_str_all(input: &str) -> Result<Self, ParseError> {
103 Self::parse_all(input.parse()?)
104 }
105
106 fn parse_all_unwrap(input: TokenStream) -> Self {
107 // TODO: eventually try to provide super nice error messages here as
108 // this is what most users will hit. Hopefully the compiler will give us
109 // an interface one day to give an extra-good error message here.
110 Self::parse_all(input).unwrap()
111 }
112}
113
114#[derive(Debug)]
115pub struct ParseError(String);
116
117impl Error for ParseError {
118 fn description(&self) -> &str {
119 &self.0
120 }
121}
122
123impl fmt::Display for ParseError {
124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125 <String as fmt::Display>::fmt(&self.0, f)
126 }
127}
128
129impl From<LexError> for ParseError {
130 fn from(_: LexError) -> ParseError {
131 ParseError("error while lexing input string".to_owned())
132 }
133}
134
135impl Synom for TokenStream {
136 fn parse(input: &[TokenTree]) -> IResult<&[TokenTree], Self> {
137 IResult::Done(&[], input.iter().cloned().collect())
138 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700139}
140
Michael Layzell24645a32017-02-04 13:19:26 -0500141/// Define a function from a parser combination.
142///
David Tolnay1f16b602017-02-07 20:06:55 -0500143/// - **Syntax:** `named!(NAME -> TYPE, PARSER)` or `named!(pub NAME -> TYPE, PARSER)`
144///
145/// ```rust
146/// # extern crate syn;
147/// # #[macro_use] extern crate synom;
148/// # use syn::Ty;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700149/// # use synom::delimited::Delimited;
Alex Crichton954046c2017-05-30 21:49:42 -0700150/// # use synom::tokens::Comma;
David Tolnay1f16b602017-02-07 20:06:55 -0500151/// // One or more Rust types separated by commas.
Alex Crichton954046c2017-05-30 21:49:42 -0700152/// named!(pub comma_separated_types -> Delimited<Ty, Comma>,
153/// call!(Delimited::parse_separated_nonempty)
David Tolnay1f16b602017-02-07 20:06:55 -0500154/// );
155/// # fn main() {}
156/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500157#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700158macro_rules! named {
159 ($name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => {
Michael Layzell416724e2017-05-24 21:12:34 -0400160 fn $name(i: &[$crate::TokenTree]) -> $crate::IResult<&[$crate::TokenTree], $o> {
David Tolnayb5a7b142016-09-13 22:46:39 -0700161 $submac!(i, $($args)*)
162 }
163 };
164
165 (pub $name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => {
Michael Layzell416724e2017-05-24 21:12:34 -0400166 pub fn $name(i: &[$crate::TokenTree]) -> $crate::IResult<&[$crate::TokenTree], $o> {
David Tolnayb5a7b142016-09-13 22:46:39 -0700167 $submac!(i, $($args)*)
168 }
169 };
170}
171
David Tolnay1f16b602017-02-07 20:06:55 -0500172/// Invoke the given parser function with the passed in arguments.
Michael Layzell24645a32017-02-04 13:19:26 -0500173///
174/// - **Syntax:** `call!(FUNCTION, ARGS...)`
David Tolnay1f16b602017-02-07 20:06:55 -0500175///
Alex Crichton954046c2017-05-30 21:49:42 -0700176/// where the signature of the function is `fn(&[U], ARGS...) -> IResult<&[U], T>`
David Tolnay1f16b602017-02-07 20:06:55 -0500177/// - **Output:** `T`, the result of invoking the function `FUNCTION`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500178#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700179macro_rules! call {
David Tolnayaf2557e2016-10-24 11:52:21 -0700180 ($i:expr, $fun:expr $(, $args:expr)*) => {
181 $fun($i $(, $args)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700182 };
183}
184
David Tolnay1f16b602017-02-07 20:06:55 -0500185/// Transform the result of a parser by applying a function or closure.
Michael Layzell24645a32017-02-04 13:19:26 -0500186///
David Tolnay1f16b602017-02-07 20:06:55 -0500187/// - **Syntax:** `map!(THING, FN)`
188/// - **Output:** the return type of function FN applied to THING
Michael Layzell24645a32017-02-04 13:19:26 -0500189///
190/// ```rust
191/// extern crate syn;
192/// #[macro_use] extern crate synom;
193///
194/// use syn::{Item, Ident};
Michael Layzell24645a32017-02-04 13:19:26 -0500195///
196/// fn get_item_ident(item: Item) -> Ident {
197/// item.ident
198/// }
199///
David Tolnay1f16b602017-02-07 20:06:55 -0500200/// // Parses an item and returns the name (identifier) of the item only.
201/// named!(item_ident -> Ident,
Alex Crichton954046c2017-05-30 21:49:42 -0700202/// map!(syn!(Item), get_item_ident)
David Tolnay1f16b602017-02-07 20:06:55 -0500203/// );
204///
205/// // Or equivalently:
206/// named!(item_ident2 -> Ident,
Alex Crichton954046c2017-05-30 21:49:42 -0700207/// map!(syn!(Item), |i: Item| i.ident)
David Tolnay1f16b602017-02-07 20:06:55 -0500208/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500209///
Alex Crichton954046c2017-05-30 21:49:42 -0700210/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500211/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500212#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700213macro_rules! map {
214 ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700215 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500216 $crate::IResult::Error => $crate::IResult::Error,
217 $crate::IResult::Done(i, o) => {
David Tolnay1f16b602017-02-07 20:06:55 -0500218 $crate::IResult::Done(i, call!(o, $g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700219 }
220 }
221 };
David Tolnay1f16b602017-02-07 20:06:55 -0500222
223 ($i:expr, $f:expr, $g:expr) => {
224 map!($i, call!($f), $g)
225 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700226}
227
David Tolnay1f16b602017-02-07 20:06:55 -0500228/// Parses successfully if the given parser fails to parse. Does not consume any
229/// of the input.
Michael Layzell24645a32017-02-04 13:19:26 -0500230///
231/// - **Syntax:** `not!(THING)`
David Tolnay1f16b602017-02-07 20:06:55 -0500232/// - **Output:** `()`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500233#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700234macro_rules! not {
235 ($i:expr, $submac:ident!( $($args:tt)* )) => {
236 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500237 $crate::IResult::Done(_, _) => $crate::IResult::Error,
David Tolnay1f16b602017-02-07 20:06:55 -0500238 $crate::IResult::Error => $crate::IResult::Done($i, ()),
David Tolnayb5a7b142016-09-13 22:46:39 -0700239 }
240 };
241}
242
David Tolnay1f16b602017-02-07 20:06:55 -0500243/// Conditionally execute the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500244///
David Tolnay1f16b602017-02-07 20:06:55 -0500245/// If you are familiar with nom, this is nom's `cond_with_error` parser.
246///
247/// - **Syntax:** `cond!(CONDITION, THING)`
248/// - **Output:** `Some(THING)` if the condition is true, else `None`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500249#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700250macro_rules! cond {
251 ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => {
252 if $cond {
253 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500254 $crate::IResult::Done(i, o) => $crate::IResult::Done(i, ::std::option::Option::Some(o)),
255 $crate::IResult::Error => $crate::IResult::Error,
David Tolnayb5a7b142016-09-13 22:46:39 -0700256 }
257 } else {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500258 $crate::IResult::Done($i, ::std::option::Option::None)
David Tolnayb5a7b142016-09-13 22:46:39 -0700259 }
David Tolnaycfe55022016-10-02 22:02:27 -0700260 };
261
262 ($i:expr, $cond:expr, $f:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700263 cond!($i, $cond, call!($f))
David Tolnaycfe55022016-10-02 22:02:27 -0700264 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700265}
266
David Tolnay1f16b602017-02-07 20:06:55 -0500267/// Fail to parse if condition is false, otherwise parse the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500268///
David Tolnay1f16b602017-02-07 20:06:55 -0500269/// This is typically used inside of `option!` or `alt!`.
270///
271/// - **Syntax:** `cond_reduce!(CONDITION, THING)`
272/// - **Output:** `THING`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500273#[macro_export]
David Tolnayaf2557e2016-10-24 11:52:21 -0700274macro_rules! cond_reduce {
275 ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => {
276 if $cond {
277 $submac!($i, $($args)*)
278 } else {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500279 $crate::IResult::Error
David Tolnayaf2557e2016-10-24 11:52:21 -0700280 }
281 };
282
283 ($i:expr, $cond:expr, $f:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700284 cond_reduce!($i, $cond, call!($f))
David Tolnayaf2557e2016-10-24 11:52:21 -0700285 };
286}
287
David Tolnay1f16b602017-02-07 20:06:55 -0500288/// Parse two things, returning the value of the first.
Michael Layzell24645a32017-02-04 13:19:26 -0500289///
David Tolnay1f16b602017-02-07 20:06:55 -0500290/// - **Syntax:** `terminated!(THING, AFTER)`
Michael Layzell24645a32017-02-04 13:19:26 -0500291/// - **Output:** `THING`
292///
293/// ```rust
294/// extern crate syn;
295/// #[macro_use] extern crate synom;
296///
297/// use syn::Expr;
Alex Crichton954046c2017-05-30 21:49:42 -0700298/// use synom::tokens::Pound;
Michael Layzell24645a32017-02-04 13:19:26 -0500299///
300/// // An expression terminated by ##.
301/// named!(expr_pound_pound -> Expr,
Alex Crichton954046c2017-05-30 21:49:42 -0700302/// terminated!(syn!(Expr), tuple!(syn!(Pound), syn!(Pound)))
David Tolnay1f16b602017-02-07 20:06:55 -0500303/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500304///
Alex Crichton954046c2017-05-30 21:49:42 -0700305/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500306/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500307#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700308macro_rules! terminated {
309 ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => {
310 match tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500311 $crate::IResult::Done(remaining, (o, _)) => $crate::IResult::Done(remaining, o),
312 $crate::IResult::Error => $crate::IResult::Error,
David Tolnayb5a7b142016-09-13 22:46:39 -0700313 }
314 };
315
316 ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700317 terminated!($i, $submac!($($args)*), call!($g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700318 };
319
320 ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700321 terminated!($i, call!($f), $submac!($($args)*))
David Tolnayb5a7b142016-09-13 22:46:39 -0700322 };
323
324 ($i:expr, $f:expr, $g:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700325 terminated!($i, call!($f), call!($g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700326 };
327}
328
David Tolnay1f16b602017-02-07 20:06:55 -0500329/// Parse zero or more values using the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500330///
331/// - **Syntax:** `many0!(THING)`
332/// - **Output:** `Vec<THING>`
333///
David Tolnay1f16b602017-02-07 20:06:55 -0500334/// You may also be looking for:
335///
Alex Crichton954046c2017-05-30 21:49:42 -0700336/// - `call!(Delimited::parse_separated)` - zero or more values with separator
337/// - `call!(Delimited::parse_separated_nonempty)` - one or more values
338/// - `call!(Delimited::parse_terminated)` - zero or more, allows trailing separator
David Tolnay1f16b602017-02-07 20:06:55 -0500339///
Michael Layzell24645a32017-02-04 13:19:26 -0500340/// ```rust
341/// extern crate syn;
342/// #[macro_use] extern crate synom;
343///
344/// use syn::Item;
Michael Layzell24645a32017-02-04 13:19:26 -0500345///
Alex Crichton954046c2017-05-30 21:49:42 -0700346/// named!(items -> Vec<Item>, many0!(syn!(Item)));
Michael Layzell24645a32017-02-04 13:19:26 -0500347///
Alex Crichton954046c2017-05-30 21:49:42 -0700348/// # fn main() {}
Michael Layzell5bde96f2017-01-24 17:59:21 -0500349#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700350macro_rules! many0 {
351 ($i:expr, $submac:ident!( $($args:tt)* )) => {{
352 let ret;
353 let mut res = ::std::vec::Vec::new();
354 let mut input = $i;
355
356 loop {
357 if input.is_empty() {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500358 ret = $crate::IResult::Done(input, res);
David Tolnayb5a7b142016-09-13 22:46:39 -0700359 break;
360 }
361
362 match $submac!(input, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500363 $crate::IResult::Error => {
364 ret = $crate::IResult::Done(input, res);
David Tolnayb5a7b142016-09-13 22:46:39 -0700365 break;
366 }
Michael Layzell5bde96f2017-01-24 17:59:21 -0500367 $crate::IResult::Done(i, o) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700368 // loop trip must always consume (otherwise infinite loops)
David Tolnaybc84d5a2016-10-08 13:20:57 -0700369 if i.len() == input.len() {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500370 ret = $crate::IResult::Error;
David Tolnayb5a7b142016-09-13 22:46:39 -0700371 break;
372 }
373
374 res.push(o);
375 input = i;
376 }
377 }
378 }
379
380 ret
381 }};
382
383 ($i:expr, $f:expr) => {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500384 $crate::many0($i, $f)
David Tolnayb5a7b142016-09-13 22:46:39 -0700385 };
386}
387
David Tolnay1f16b602017-02-07 20:06:55 -0500388// Improve compile time by compiling this loop only once per type it is used
389// with.
390//
David Tolnay5fe14fc2017-01-27 16:22:08 -0800391// Not public API.
392#[doc(hidden)]
Michael Layzell416724e2017-05-24 21:12:34 -0400393pub fn many0<'a, T>(mut input: &'a [TokenTree],
394 f: fn(&'a [TokenTree]) -> IResult<&'a [TokenTree], T>)
395 -> IResult<&'a [TokenTree], Vec<T>> {
David Tolnaybc84d5a2016-10-08 13:20:57 -0700396 let mut res = Vec::new();
397
398 loop {
399 if input.is_empty() {
400 return IResult::Done(input, res);
401 }
402
403 match f(input) {
404 IResult::Error => {
405 return IResult::Done(input, res);
406 }
407 IResult::Done(i, o) => {
408 // loop trip must always consume (otherwise infinite loops)
409 if i.len() == input.len() {
410 return IResult::Error;
411 }
412
413 res.push(o);
414 input = i;
415 }
416 }
417 }
418}
419
David Tolnay1f16b602017-02-07 20:06:55 -0500420/// Parse a value without consuming it from the input data.
Michael Layzell24645a32017-02-04 13:19:26 -0500421///
422/// - **Syntax:** `peek!(THING)`
David Tolnay1f16b602017-02-07 20:06:55 -0500423/// - **Output:** `THING`
Michael Layzell24645a32017-02-04 13:19:26 -0500424///
425/// ```rust
426/// extern crate syn;
427/// #[macro_use] extern crate synom;
428///
Alex Crichton954046c2017-05-30 21:49:42 -0700429/// use syn::{Expr, Ident};
David Tolnay1f16b602017-02-07 20:06:55 -0500430/// use synom::IResult;
Michael Layzell24645a32017-02-04 13:19:26 -0500431///
David Tolnay1f16b602017-02-07 20:06:55 -0500432/// // Parse an expression that begins with an identifier.
Alex Crichton954046c2017-05-30 21:49:42 -0700433/// named!(ident_expr -> (Ident, Expr),
434/// tuple!(peek!(syn!(Ident)), syn!(Expr))
David Tolnay1f16b602017-02-07 20:06:55 -0500435/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500436///
Alex Crichton954046c2017-05-30 21:49:42 -0700437/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500438/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500439#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700440macro_rules! peek {
441 ($i:expr, $submac:ident!( $($args:tt)* )) => {
442 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500443 $crate::IResult::Done(_, o) => $crate::IResult::Done($i, o),
444 $crate::IResult::Error => $crate::IResult::Error,
David Tolnayb5a7b142016-09-13 22:46:39 -0700445 }
446 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700447
David Tolnay1f16b602017-02-07 20:06:55 -0500448 ($i:expr, $f:expr) => {
449 peek!($i, call!($f))
David Tolnayb5a7b142016-09-13 22:46:39 -0700450 };
451}
452
David Tolnay1f16b602017-02-07 20:06:55 -0500453/// Pattern-match the result of a parser to select which other parser to run.
454///
455/// - **Syntax:** `switch!(TARGET, PAT1 => THEN1 | PAT2 => THEN2 | ...)`
456/// - **Output:** `T`, the return type of `THEN1` and `THEN2` and ...
457///
458/// ```rust
459/// extern crate syn;
460/// #[macro_use] extern crate synom;
461///
462/// use syn::{Ident, Ty};
Alex Crichton954046c2017-05-30 21:49:42 -0700463/// use synom::tokens::*;
David Tolnay1f16b602017-02-07 20:06:55 -0500464///
465/// #[derive(Debug)]
466/// enum UnitType {
467/// Struct {
468/// name: Ident,
469/// },
470/// Enum {
471/// name: Ident,
472/// variant: Ident,
473/// },
474/// }
475///
476/// // Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
477/// named!(unit_type -> UnitType, do_parse!(
Alex Crichton954046c2017-05-30 21:49:42 -0700478/// which: alt!(
479/// syn!(Struct) => { |_| 0 }
480/// |
481/// syn!(Enum) => { |_| 1 }
482/// ) >>
483/// id: syn!(Ident) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500484/// item: switch!(value!(which),
Alex Crichton954046c2017-05-30 21:49:42 -0700485/// 0 => map!(
486/// syn!(Semi),
David Tolnay1f16b602017-02-07 20:06:55 -0500487/// move |_| UnitType::Struct {
488/// name: id,
489/// }
490/// )
491/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700492/// 1 => map!(
493/// braces!(syn!(Ident)),
494/// move |(variant, _)| UnitType::Enum {
David Tolnay1f16b602017-02-07 20:06:55 -0500495/// name: id,
496/// variant: variant,
497/// }
498/// )
499/// ) >>
500/// (item)
501/// ));
502///
Alex Crichton954046c2017-05-30 21:49:42 -0700503/// # fn main() {}
David Tolnay1f16b602017-02-07 20:06:55 -0500504/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500505#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700506macro_rules! switch {
507 ($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => {
508 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500509 $crate::IResult::Error => $crate::IResult::Error,
510 $crate::IResult::Done(i, o) => match o {
David Tolnayb5a7b142016-09-13 22:46:39 -0700511 $(
512 $p => $subrule!(i, $($args2)*),
513 )*
Michael Layzell5bde96f2017-01-24 17:59:21 -0500514 _ => $crate::IResult::Error,
David Tolnayb5a7b142016-09-13 22:46:39 -0700515 }
516 }
517 };
518}
519
Alex Crichton954046c2017-05-30 21:49:42 -0700520
David Tolnay1f16b602017-02-07 20:06:55 -0500521/// Produce the given value without parsing anything. Useful as an argument to
522/// `switch!`.
523///
524/// - **Syntax:** `value!(VALUE)`
525/// - **Output:** `VALUE`
526///
527/// ```rust
528/// extern crate syn;
529/// #[macro_use] extern crate synom;
530///
531/// use syn::{Ident, Ty};
Alex Crichton954046c2017-05-30 21:49:42 -0700532/// use synom::tokens::*;
David Tolnay1f16b602017-02-07 20:06:55 -0500533///
534/// #[derive(Debug)]
535/// enum UnitType {
536/// Struct {
537/// name: Ident,
538/// },
539/// Enum {
540/// name: Ident,
541/// variant: Ident,
542/// },
543/// }
544///
545/// // Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
546/// named!(unit_type -> UnitType, do_parse!(
Alex Crichton954046c2017-05-30 21:49:42 -0700547/// which: alt!(
548/// syn!(Struct) => { |_| 0 }
549/// |
550/// syn!(Enum) => { |_| 1 }
551/// ) >>
552/// id: syn!(Ident) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500553/// item: switch!(value!(which),
Alex Crichton954046c2017-05-30 21:49:42 -0700554/// 0 => map!(
555/// syn!(Semi),
David Tolnay1f16b602017-02-07 20:06:55 -0500556/// move |_| UnitType::Struct {
557/// name: id,
558/// }
559/// )
560/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700561/// 1 => map!(
562/// braces!(syn!(Ident)),
563/// move |(variant, _)| UnitType::Enum {
David Tolnay1f16b602017-02-07 20:06:55 -0500564/// name: id,
565/// variant: variant,
566/// }
567/// )
568/// ) >>
569/// (item)
570/// ));
571///
Alex Crichton954046c2017-05-30 21:49:42 -0700572/// # fn main() {}
David Tolnay1f16b602017-02-07 20:06:55 -0500573/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500574#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700575macro_rules! value {
576 ($i:expr, $res:expr) => {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500577 $crate::IResult::Done($i, $res)
David Tolnayb5a7b142016-09-13 22:46:39 -0700578 };
579}
580
David Tolnay1f16b602017-02-07 20:06:55 -0500581/// Run a series of parsers and produce all of the results in a tuple.
Michael Layzell24645a32017-02-04 13:19:26 -0500582///
David Tolnay1f16b602017-02-07 20:06:55 -0500583/// - **Syntax:** `tuple!(A, B, C, ...)`
584/// - **Output:** `(A, B, C, ...)`
Michael Layzell24645a32017-02-04 13:19:26 -0500585///
586/// ```rust
587/// extern crate syn;
588/// #[macro_use] extern crate synom;
589///
590/// use syn::Ty;
Michael Layzell24645a32017-02-04 13:19:26 -0500591///
Alex Crichton954046c2017-05-30 21:49:42 -0700592/// named!(two_types -> (Ty, Ty), tuple!(syn!(Ty), syn!(Ty)));
Michael Layzell24645a32017-02-04 13:19:26 -0500593///
Alex Crichton954046c2017-05-30 21:49:42 -0700594/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500595/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500596#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700597macro_rules! tuple {
598 ($i:expr, $($rest:tt)*) => {
599 tuple_parser!($i, (), $($rest)*)
600 };
601}
602
David Tolnay1f16b602017-02-07 20:06:55 -0500603/// Internal parser, do not use directly.
Michael Layzell5bde96f2017-01-24 17:59:21 -0500604#[doc(hidden)]
605#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700606macro_rules! tuple_parser {
607 ($i:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700608 tuple_parser!($i, ($($parsed),*), call!($e), $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700609 };
610
611 ($i:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => {
612 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500613 $crate::IResult::Error => $crate::IResult::Error,
614 $crate::IResult::Done(i, o) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700615 tuple_parser!(i, (o), $($rest)*),
616 }
617 };
618
619 ($i:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => {
620 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500621 $crate::IResult::Error => $crate::IResult::Error,
622 $crate::IResult::Done(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 Layzell5bde96f2017-01-24 17:59:21 -0500637 $crate::IResult::Error => $crate::IResult::Error,
638 $crate::IResult::Done(i, o) => $crate::IResult::Done(i, ($($parsed),*, o))
David Tolnayb5a7b142016-09-13 22:46:39 -0700639 }
640 };
641
642 ($i:expr, ($($parsed:expr),*)) => {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500643 $crate::IResult::Done($i, ($($parsed),*))
David Tolnayb5a7b142016-09-13 22:46:39 -0700644 };
645}
646
David Tolnay1f16b602017-02-07 20:06:55 -0500647/// Run a series of parsers, returning the result of the first one which
648/// succeeds.
Michael Layzell24645a32017-02-04 13:19:26 -0500649///
650/// Optionally allows for the result to be transformed.
651///
652/// - **Syntax:** `alt!(THING1 | THING2 => { FUNC } | ...)`
David Tolnay1f16b602017-02-07 20:06:55 -0500653/// - **Output:** `T`, the return type of `THING1` and `FUNC(THING2)` and ...
Michael Layzell24645a32017-02-04 13:19:26 -0500654///
655/// ```rust
656/// extern crate syn;
657/// #[macro_use] extern crate synom;
658///
659/// use syn::Ident;
Alex Crichton954046c2017-05-30 21:49:42 -0700660/// use synom::tokens::Bang;
Michael Layzell24645a32017-02-04 13:19:26 -0500661///
662/// named!(ident_or_bang -> Ident,
David Tolnay1f16b602017-02-07 20:06:55 -0500663/// alt!(
Alex Crichton954046c2017-05-30 21:49:42 -0700664/// syn!(Ident)
David Tolnay1f16b602017-02-07 20:06:55 -0500665/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700666/// syn!(Bang) => { |_| "BANG".into() }
David Tolnay1f16b602017-02-07 20:06:55 -0500667/// )
668/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500669///
Alex Crichton954046c2017-05-30 21:49:42 -0700670/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500671/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500672#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700673macro_rules! alt {
674 ($i:expr, $e:ident | $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700675 alt!($i, call!($e) | $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700676 };
677
678 ($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => {
679 match $subrule!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500680 res @ $crate::IResult::Done(_, _) => res,
David Tolnayb5a7b142016-09-13 22:46:39 -0700681 _ => alt!($i, $($rest)*)
682 }
683 };
684
685 ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => {
686 match $subrule!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500687 $crate::IResult::Done(i, o) => $crate::IResult::Done(i, $gen(o)),
688 $crate::IResult::Error => alt!($i, $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700689 }
690 };
691
692 ($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700693 alt!($i, call!($e) => { $gen } | $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700694 };
695
696 ($i:expr, $e:ident => { $gen:expr }) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700697 alt!($i, call!($e) => { $gen })
David Tolnayb5a7b142016-09-13 22:46:39 -0700698 };
699
700 ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => {
701 match $subrule!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500702 $crate::IResult::Done(i, o) => $crate::IResult::Done(i, $gen(o)),
703 $crate::IResult::Error => $crate::IResult::Error,
David Tolnayb5a7b142016-09-13 22:46:39 -0700704 }
705 };
706
707 ($i:expr, $e:ident) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700708 alt!($i, call!($e))
David Tolnayb5a7b142016-09-13 22:46:39 -0700709 };
710
711 ($i:expr, $subrule:ident!( $($args:tt)*)) => {
David Tolnay5377b172016-10-25 01:13:12 -0700712 $subrule!($i, $($args)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700713 };
714}
715
Michael Layzell24645a32017-02-04 13:19:26 -0500716/// Run a series of parsers, one after another, optionally assigning the results
David Tolnay1f16b602017-02-07 20:06:55 -0500717/// a name. Fail if any of the parsers fails.
Michael Layzell24645a32017-02-04 13:19:26 -0500718///
David Tolnay1f16b602017-02-07 20:06:55 -0500719/// Produces the result of evaluating the final expression in parentheses with
720/// all of the previously named results bound.
Michael Layzell24645a32017-02-04 13:19:26 -0500721///
David Tolnay1f16b602017-02-07 20:06:55 -0500722/// - **Syntax:** `do_parse!(name: THING1 >> THING2 >> (RESULT))`
Michael Layzell24645a32017-02-04 13:19:26 -0500723/// - **Output:** `RESULT`
724///
725/// ```rust
726/// extern crate syn;
727/// #[macro_use] extern crate synom;
Alex Crichton954046c2017-05-30 21:49:42 -0700728/// extern crate proc_macro2;
Michael Layzell24645a32017-02-04 13:19:26 -0500729///
730/// use syn::{Ident, TokenTree};
Alex Crichton954046c2017-05-30 21:49:42 -0700731/// use synom::tokens::{Bang, Paren};
732/// use proc_macro2::TokenStream;
Michael Layzell24645a32017-02-04 13:19:26 -0500733///
David Tolnay1f16b602017-02-07 20:06:55 -0500734/// // Parse a macro invocation like `stringify!($args)`.
Alex Crichton954046c2017-05-30 21:49:42 -0700735/// named!(simple_mac -> (Ident, (TokenStream, Paren)), do_parse!(
736/// name: syn!(Ident) >>
737/// syn!(Bang) >>
738/// body: parens!(syn!(TokenStream)) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500739/// (name, body)
740/// ));
Michael Layzell24645a32017-02-04 13:19:26 -0500741///
Alex Crichton954046c2017-05-30 21:49:42 -0700742/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500743/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500744#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700745macro_rules! do_parse {
746 ($i:expr, ( $($rest:expr),* )) => {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500747 $crate::IResult::Done($i, ( $($rest),* ))
David Tolnayb5a7b142016-09-13 22:46:39 -0700748 };
749
750 ($i:expr, $e:ident >> $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700751 do_parse!($i, call!($e) >> $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700752 };
753
754 ($i:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
755 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500756 $crate::IResult::Error => $crate::IResult::Error,
757 $crate::IResult::Done(i, _) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700758 do_parse!(i, $($rest)*),
759 }
760 };
761
762 ($i:expr, $field:ident : $e:ident >> $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700763 do_parse!($i, $field: call!($e) >> $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700764 };
765
766 ($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
767 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500768 $crate::IResult::Error => $crate::IResult::Error,
769 $crate::IResult::Done(i, o) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700770 let $field = o;
771 do_parse!(i, $($rest)*)
772 },
773 }
774 };
775
David Tolnayfa0edf22016-09-23 22:58:24 -0700776 ($i:expr, mut $field:ident : $e:ident >> $($rest:tt)*) => {
David Tolnay7184b132016-10-30 10:06:37 -0700777 do_parse!($i, mut $field: call!($e) >> $($rest)*)
David Tolnayfa0edf22016-09-23 22:58:24 -0700778 };
779
780 ($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
781 match $submac!($i, $($args)*) {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500782 $crate::IResult::Error => $crate::IResult::Error,
783 $crate::IResult::Done(i, o) => {
David Tolnayfa0edf22016-09-23 22:58:24 -0700784 let mut $field = o;
785 do_parse!(i, $($rest)*)
786 },
787 }
788 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700789}
Michael Layzell416724e2017-05-24 21:12:34 -0400790
791#[macro_export]
792macro_rules! input_end {
793 ($i:expr,) => {
794 $crate::input_end($i)
795 };
796}
797
798// Not a public API
799#[doc(hidden)]
800pub fn input_end(input: &[TokenTree]) -> IResult<&'static [TokenTree], &'static str> {
801 if input.is_empty() {
802 IResult::Done(&[], "")
803 } else {
804 IResult::Error
805 }
806}