blob: de48e0d60520aa5c2060cca99ab2a4f3aee43204 [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);
69 let result = Self::parse(buf.begin());
Michael Layzellad763b72017-06-01 00:25:31 -040070 let err = match result {
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
76 "failed to parse"
77 } else {
78 "unparsed tokens after"
79 }
80 }
Michael Layzellad763b72017-06-01 00:25:31 -040081 Err(ref err) => err.description(),
Alex Crichton954046c2017-05-30 21:49:42 -070082 };
83 match Self::description() {
Michael Layzellad763b72017-06-01 00:25:31 -040084 Some(s) => Err(ParseError(Some(format!("{} {}", err, s)))),
85 None => Err(ParseError(Some(err.to_string()))),
Alex Crichton954046c2017-05-30 21:49:42 -070086 }
87 }
88
89 fn parse_str_all(input: &str) -> Result<Self, ParseError> {
90 Self::parse_all(input.parse()?)
91 }
92
93 fn parse_all_unwrap(input: TokenStream) -> Self {
94 // TODO: eventually try to provide super nice error messages here as
95 // this is what most users will hit. Hopefully the compiler will give us
96 // an interface one day to give an extra-good error message here.
97 Self::parse_all(input).unwrap()
98 }
99}
100
101#[derive(Debug)]
Michael Layzellad763b72017-06-01 00:25:31 -0400102pub struct ParseError(Option<String>);
Alex Crichton954046c2017-05-30 21:49:42 -0700103
104impl Error for ParseError {
105 fn description(&self) -> &str {
Michael Layzellad763b72017-06-01 00:25:31 -0400106 match self.0 {
107 Some(ref desc) => desc,
108 None => "failed to parse",
109 }
Alex Crichton954046c2017-05-30 21:49:42 -0700110 }
111}
112
113impl fmt::Display for ParseError {
114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Michael Layzellad763b72017-06-01 00:25:31 -0400115 <str as fmt::Display>::fmt(self.description(), f)
Alex Crichton954046c2017-05-30 21:49:42 -0700116 }
117}
118
119impl From<LexError> for ParseError {
120 fn from(_: LexError) -> ParseError {
Michael Layzellad763b72017-06-01 00:25:31 -0400121 ParseError(Some("error while lexing input string".to_owned()))
Alex Crichton954046c2017-05-30 21:49:42 -0700122 }
123}
124
125impl Synom for TokenStream {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400126 fn parse(input: Cursor) -> PResult<Self> {
127 Ok((Cursor::empty(), input.token_stream()))
Alex Crichton954046c2017-05-30 21:49:42 -0700128 }
Alex Crichton7b9e02f2017-05-30 15:54:33 -0700129}
130
Michael Layzell24645a32017-02-04 13:19:26 -0500131/// Define a function from a parser combination.
132///
David Tolnay1f16b602017-02-07 20:06:55 -0500133/// - **Syntax:** `named!(NAME -> TYPE, PARSER)` or `named!(pub NAME -> TYPE, PARSER)`
134///
135/// ```rust
136/// # extern crate syn;
137/// # #[macro_use] extern crate synom;
138/// # use syn::Ty;
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700139/// # use synom::delimited::Delimited;
Alex Crichton954046c2017-05-30 21:49:42 -0700140/// # use synom::tokens::Comma;
David Tolnay1f16b602017-02-07 20:06:55 -0500141/// // One or more Rust types separated by commas.
Alex Crichton954046c2017-05-30 21:49:42 -0700142/// named!(pub comma_separated_types -> Delimited<Ty, Comma>,
143/// call!(Delimited::parse_separated_nonempty)
David Tolnay1f16b602017-02-07 20:06:55 -0500144/// );
145/// # fn main() {}
146/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500147#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700148macro_rules! named {
149 ($name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400150 fn $name(i: $crate::Cursor) -> $crate::PResult<$o> {
David Tolnayb5a7b142016-09-13 22:46:39 -0700151 $submac!(i, $($args)*)
152 }
153 };
154
155 (pub $name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400156 pub fn $name(i: $crate::Cursor) -> $crate::PResult<$o> {
David Tolnayb5a7b142016-09-13 22:46:39 -0700157 $submac!(i, $($args)*)
158 }
159 };
160}
161
David Tolnay1f16b602017-02-07 20:06:55 -0500162/// Invoke the given parser function with the passed in arguments.
Michael Layzell24645a32017-02-04 13:19:26 -0500163///
164/// - **Syntax:** `call!(FUNCTION, ARGS...)`
David Tolnay1f16b602017-02-07 20:06:55 -0500165///
Michael Layzell760fd662017-05-31 22:46:05 -0400166/// where the signature of the function is `fn(&[U], ARGS...) -> IPResult<&[U], T>`
David Tolnay1f16b602017-02-07 20:06:55 -0500167/// - **Output:** `T`, the result of invoking the function `FUNCTION`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500168#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700169macro_rules! call {
David Tolnayaf2557e2016-10-24 11:52:21 -0700170 ($i:expr, $fun:expr $(, $args:expr)*) => {
171 $fun($i $(, $args)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700172 };
173}
174
David Tolnay1f16b602017-02-07 20:06:55 -0500175/// Transform the result of a parser by applying a function or closure.
Michael Layzell24645a32017-02-04 13:19:26 -0500176///
David Tolnay1f16b602017-02-07 20:06:55 -0500177/// - **Syntax:** `map!(THING, FN)`
178/// - **Output:** the return type of function FN applied to THING
Michael Layzell24645a32017-02-04 13:19:26 -0500179///
180/// ```rust
181/// extern crate syn;
182/// #[macro_use] extern crate synom;
183///
David Tolnayb21bb0c2017-06-03 20:39:19 -0700184/// use syn::{Expr, ExprIf};
Michael Layzell24645a32017-02-04 13:19:26 -0500185///
David Tolnayb21bb0c2017-06-03 20:39:19 -0700186/// fn get_cond(if_: ExprIf) -> Expr {
187/// *if_.cond
Michael Layzell24645a32017-02-04 13:19:26 -0500188/// }
189///
David Tolnayb21bb0c2017-06-03 20:39:19 -0700190/// // Parses an `if` statement but returns the condition part only.
191/// named!(if_condition -> Expr,
192/// map!(syn!(ExprIf), get_cond)
David Tolnay1f16b602017-02-07 20:06:55 -0500193/// );
194///
195/// // Or equivalently:
David Tolnayb21bb0c2017-06-03 20:39:19 -0700196/// named!(if_condition2 -> Expr,
197/// map!(syn!(ExprIf), |if_: ExprIf| *if_.cond)
David Tolnay1f16b602017-02-07 20:06:55 -0500198/// );
David Tolnayb21bb0c2017-06-03 20:39:19 -0700199/// #
Alex Crichton954046c2017-05-30 21:49:42 -0700200/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500201/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500202#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700203macro_rules! map {
204 ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700205 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400206 ::std::result::Result::Err(err) =>
207 ::std::result::Result::Err(err),
208 ::std::result::Result::Ok((i, o)) =>
209 ::std::result::Result::Ok((i, call!(o, $g))),
David Tolnayb5a7b142016-09-13 22:46:39 -0700210 }
211 };
David Tolnay1f16b602017-02-07 20:06:55 -0500212
213 ($i:expr, $f:expr, $g:expr) => {
214 map!($i, call!($f), $g)
215 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700216}
217
David Tolnay1f16b602017-02-07 20:06:55 -0500218/// Parses successfully if the given parser fails to parse. Does not consume any
219/// of the input.
Michael Layzell24645a32017-02-04 13:19:26 -0500220///
221/// - **Syntax:** `not!(THING)`
David Tolnay1f16b602017-02-07 20:06:55 -0500222/// - **Output:** `()`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500223#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700224macro_rules! not {
225 ($i:expr, $submac:ident!( $($args:tt)* )) => {
226 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400227 ::std::result::Result::Ok(_) => $crate::parse_error(),
228 ::std::result::Result::Err(_) =>
229 ::std::result::Result::Ok(($i, ())),
David Tolnayb5a7b142016-09-13 22:46:39 -0700230 }
231 };
232}
233
David Tolnay1f16b602017-02-07 20:06:55 -0500234/// Conditionally execute the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500235///
David Tolnay1f16b602017-02-07 20:06:55 -0500236/// If you are familiar with nom, this is nom's `cond_with_error` parser.
237///
238/// - **Syntax:** `cond!(CONDITION, THING)`
239/// - **Output:** `Some(THING)` if the condition is true, else `None`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500240#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700241macro_rules! cond {
242 ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => {
243 if $cond {
244 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400245 ::std::result::Result::Ok((i, o)) =>
246 ::std::result::Result::Ok((i, ::std::option::Option::Some(o))),
247 ::std::result::Result::Err(x) => ::std::result::Result::Err(x),
David Tolnayb5a7b142016-09-13 22:46:39 -0700248 }
249 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400250 ::std::result::Result::Ok(($i, ::std::option::Option::None))
David Tolnayb5a7b142016-09-13 22:46:39 -0700251 }
David Tolnaycfe55022016-10-02 22:02:27 -0700252 };
253
254 ($i:expr, $cond:expr, $f:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700255 cond!($i, $cond, call!($f))
David Tolnaycfe55022016-10-02 22:02:27 -0700256 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700257}
258
David Tolnay1f16b602017-02-07 20:06:55 -0500259/// Fail to parse if condition is false, otherwise parse the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500260///
David Tolnay1f16b602017-02-07 20:06:55 -0500261/// This is typically used inside of `option!` or `alt!`.
262///
263/// - **Syntax:** `cond_reduce!(CONDITION, THING)`
264/// - **Output:** `THING`
Michael Layzell5bde96f2017-01-24 17:59:21 -0500265#[macro_export]
David Tolnayaf2557e2016-10-24 11:52:21 -0700266macro_rules! cond_reduce {
267 ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => {
268 if $cond {
269 $submac!($i, $($args)*)
270 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400271 $crate::parse_error()
David Tolnayaf2557e2016-10-24 11:52:21 -0700272 }
273 };
274
275 ($i:expr, $cond:expr, $f:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700276 cond_reduce!($i, $cond, call!($f))
David Tolnayaf2557e2016-10-24 11:52:21 -0700277 };
278}
279
David Tolnay1f16b602017-02-07 20:06:55 -0500280/// Parse two things, returning the value of the first.
Michael Layzell24645a32017-02-04 13:19:26 -0500281///
David Tolnay1f16b602017-02-07 20:06:55 -0500282/// - **Syntax:** `terminated!(THING, AFTER)`
Michael Layzell24645a32017-02-04 13:19:26 -0500283/// - **Output:** `THING`
284///
285/// ```rust
286/// extern crate syn;
287/// #[macro_use] extern crate synom;
288///
289/// use syn::Expr;
Alex Crichton954046c2017-05-30 21:49:42 -0700290/// use synom::tokens::Pound;
Michael Layzell24645a32017-02-04 13:19:26 -0500291///
292/// // An expression terminated by ##.
293/// named!(expr_pound_pound -> Expr,
Alex Crichton954046c2017-05-30 21:49:42 -0700294/// terminated!(syn!(Expr), tuple!(syn!(Pound), syn!(Pound)))
David Tolnay1f16b602017-02-07 20:06:55 -0500295/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500296///
Alex Crichton954046c2017-05-30 21:49:42 -0700297/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500298/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500299#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700300macro_rules! terminated {
301 ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => {
302 match tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) {
Michael Layzell760fd662017-05-31 22:46:05 -0400303 ::std::result::Result::Ok((i, (o, _))) =>
304 ::std::result::Result::Ok((i, o)),
305 ::std::result::Result::Err(err) =>
306 ::std::result::Result::Err(err),
David Tolnayb5a7b142016-09-13 22:46:39 -0700307 }
308 };
309
310 ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700311 terminated!($i, $submac!($($args)*), call!($g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700312 };
313
314 ($i:expr, $f:expr, $submac:ident!( $($args:tt)* )) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700315 terminated!($i, call!($f), $submac!($($args)*))
David Tolnayb5a7b142016-09-13 22:46:39 -0700316 };
317
318 ($i:expr, $f:expr, $g:expr) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700319 terminated!($i, call!($f), call!($g))
David Tolnayb5a7b142016-09-13 22:46:39 -0700320 };
321}
322
David Tolnay1f16b602017-02-07 20:06:55 -0500323/// Parse zero or more values using the given parser.
Michael Layzell24645a32017-02-04 13:19:26 -0500324///
325/// - **Syntax:** `many0!(THING)`
326/// - **Output:** `Vec<THING>`
327///
David Tolnay1f16b602017-02-07 20:06:55 -0500328/// You may also be looking for:
329///
Alex Crichton954046c2017-05-30 21:49:42 -0700330/// - `call!(Delimited::parse_separated)` - zero or more values with separator
331/// - `call!(Delimited::parse_separated_nonempty)` - one or more values
332/// - `call!(Delimited::parse_terminated)` - zero or more, allows trailing separator
David Tolnay1f16b602017-02-07 20:06:55 -0500333///
Michael Layzell24645a32017-02-04 13:19:26 -0500334/// ```rust
335/// extern crate syn;
336/// #[macro_use] extern crate synom;
337///
338/// use syn::Item;
Michael Layzell24645a32017-02-04 13:19:26 -0500339///
Alex Crichton954046c2017-05-30 21:49:42 -0700340/// named!(items -> Vec<Item>, many0!(syn!(Item)));
Michael Layzell24645a32017-02-04 13:19:26 -0500341///
Alex Crichton954046c2017-05-30 21:49:42 -0700342/// # fn main() {}
Michael Layzell5bde96f2017-01-24 17:59:21 -0500343#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700344macro_rules! many0 {
345 ($i:expr, $submac:ident!( $($args:tt)* )) => {{
346 let ret;
347 let mut res = ::std::vec::Vec::new();
348 let mut input = $i;
349
350 loop {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400351 if input.eof() {
Michael Layzell760fd662017-05-31 22:46:05 -0400352 ret = ::std::result::Result::Ok((input, res));
David Tolnayb5a7b142016-09-13 22:46:39 -0700353 break;
354 }
355
356 match $submac!(input, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400357 ::std::result::Result::Err(_) => {
358 ret = ::std::result::Result::Ok((input, res));
David Tolnayb5a7b142016-09-13 22:46:39 -0700359 break;
360 }
Michael Layzell760fd662017-05-31 22:46:05 -0400361 ::std::result::Result::Ok((i, o)) => {
David Tolnayb5a7b142016-09-13 22:46:39 -0700362 // loop trip must always consume (otherwise infinite loops)
Michael Layzell0a1a6632017-06-02 18:07:43 -0400363 if i == input {
Michael Layzell760fd662017-05-31 22:46:05 -0400364 ret = $crate::parse_error();
David Tolnayb5a7b142016-09-13 22:46:39 -0700365 break;
366 }
367
368 res.push(o);
369 input = i;
370 }
371 }
372 }
373
374 ret
375 }};
376
377 ($i:expr, $f:expr) => {
Michael Layzell5bde96f2017-01-24 17:59:21 -0500378 $crate::many0($i, $f)
David Tolnayb5a7b142016-09-13 22:46:39 -0700379 };
380}
381
David Tolnay1f16b602017-02-07 20:06:55 -0500382// Improve compile time by compiling this loop only once per type it is used
383// with.
384//
David Tolnay5fe14fc2017-01-27 16:22:08 -0800385// Not public API.
386#[doc(hidden)]
Michael Layzell760fd662017-05-31 22:46:05 -0400387pub fn many0<'a, T>(mut input: Cursor, f: fn(Cursor) -> PResult<T>) -> PResult<Vec<T>> {
David Tolnaybc84d5a2016-10-08 13:20:57 -0700388 let mut res = Vec::new();
389
390 loop {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400391 if input.eof() {
Michael Layzell760fd662017-05-31 22:46:05 -0400392 return Ok((input, res));
David Tolnaybc84d5a2016-10-08 13:20:57 -0700393 }
394
395 match f(input) {
Michael Layzell760fd662017-05-31 22:46:05 -0400396 Err(_) => {
397 return Ok((input, res));
David Tolnaybc84d5a2016-10-08 13:20:57 -0700398 }
Michael Layzell760fd662017-05-31 22:46:05 -0400399 Ok((i, o)) => {
David Tolnaybc84d5a2016-10-08 13:20:57 -0700400 // loop trip must always consume (otherwise infinite loops)
Michael Layzell0a1a6632017-06-02 18:07:43 -0400401 if i == input {
Michael Layzell760fd662017-05-31 22:46:05 -0400402 return parse_error();
David Tolnaybc84d5a2016-10-08 13:20:57 -0700403 }
404
405 res.push(o);
406 input = i;
407 }
408 }
409 }
410}
411
David Tolnay1f16b602017-02-07 20:06:55 -0500412/// Parse a value without consuming it from the input data.
Michael Layzell24645a32017-02-04 13:19:26 -0500413///
414/// - **Syntax:** `peek!(THING)`
David Tolnay1f16b602017-02-07 20:06:55 -0500415/// - **Output:** `THING`
Michael Layzell24645a32017-02-04 13:19:26 -0500416///
417/// ```rust
418/// extern crate syn;
419/// #[macro_use] extern crate synom;
420///
Alex Crichton954046c2017-05-30 21:49:42 -0700421/// use syn::{Expr, Ident};
Michael Layzell24645a32017-02-04 13:19:26 -0500422///
David Tolnay1f16b602017-02-07 20:06:55 -0500423/// // Parse an expression that begins with an identifier.
Alex Crichton954046c2017-05-30 21:49:42 -0700424/// named!(ident_expr -> (Ident, Expr),
425/// tuple!(peek!(syn!(Ident)), syn!(Expr))
David Tolnay1f16b602017-02-07 20:06:55 -0500426/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500427///
Alex Crichton954046c2017-05-30 21:49:42 -0700428/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500429/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500430#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700431macro_rules! peek {
432 ($i:expr, $submac:ident!( $($args:tt)* )) => {
433 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400434 ::std::result::Result::Ok((_, o)) => ::std::result::Result::Ok(($i, o)),
435 ::std::result::Result::Err(err) => ::std::result::Result::Err(err),
David Tolnayb5a7b142016-09-13 22:46:39 -0700436 }
437 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700438
David Tolnay1f16b602017-02-07 20:06:55 -0500439 ($i:expr, $f:expr) => {
440 peek!($i, call!($f))
David Tolnayb5a7b142016-09-13 22:46:39 -0700441 };
442}
443
David Tolnay1f16b602017-02-07 20:06:55 -0500444/// Pattern-match the result of a parser to select which other parser to run.
445///
446/// - **Syntax:** `switch!(TARGET, PAT1 => THEN1 | PAT2 => THEN2 | ...)`
447/// - **Output:** `T`, the return type of `THEN1` and `THEN2` and ...
448///
449/// ```rust
450/// extern crate syn;
451/// #[macro_use] extern crate synom;
452///
453/// use syn::{Ident, Ty};
Alex Crichton954046c2017-05-30 21:49:42 -0700454/// use synom::tokens::*;
David Tolnay1f16b602017-02-07 20:06:55 -0500455///
456/// #[derive(Debug)]
457/// enum UnitType {
458/// Struct {
459/// name: Ident,
460/// },
461/// Enum {
462/// name: Ident,
463/// variant: Ident,
464/// },
465/// }
466///
467/// // Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
468/// named!(unit_type -> UnitType, do_parse!(
Alex Crichton954046c2017-05-30 21:49:42 -0700469/// which: alt!(
470/// syn!(Struct) => { |_| 0 }
471/// |
472/// syn!(Enum) => { |_| 1 }
473/// ) >>
474/// id: syn!(Ident) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500475/// item: switch!(value!(which),
Alex Crichton954046c2017-05-30 21:49:42 -0700476/// 0 => map!(
477/// syn!(Semi),
David Tolnay1f16b602017-02-07 20:06:55 -0500478/// move |_| UnitType::Struct {
479/// name: id,
480/// }
481/// )
482/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700483/// 1 => map!(
484/// braces!(syn!(Ident)),
485/// move |(variant, _)| UnitType::Enum {
David Tolnay1f16b602017-02-07 20:06:55 -0500486/// name: id,
487/// variant: variant,
488/// }
489/// )
490/// ) >>
491/// (item)
492/// ));
493///
Alex Crichton954046c2017-05-30 21:49:42 -0700494/// # fn main() {}
David Tolnay1f16b602017-02-07 20:06:55 -0500495/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500496#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700497macro_rules! switch {
498 ($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => {
499 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400500 ::std::result::Result::Err(err) => ::std::result::Result::Err(err),
501 ::std::result::Result::Ok((i, o)) => match o {
David Tolnayb5a7b142016-09-13 22:46:39 -0700502 $(
503 $p => $subrule!(i, $($args2)*),
504 )*
Michael Layzell760fd662017-05-31 22:46:05 -0400505 _ => $crate::parse_error(),
David Tolnayb5a7b142016-09-13 22:46:39 -0700506 }
507 }
508 };
509}
510
Alex Crichton954046c2017-05-30 21:49:42 -0700511
David Tolnay1f16b602017-02-07 20:06:55 -0500512/// Produce the given value without parsing anything. Useful as an argument to
513/// `switch!`.
514///
515/// - **Syntax:** `value!(VALUE)`
516/// - **Output:** `VALUE`
517///
518/// ```rust
519/// extern crate syn;
520/// #[macro_use] extern crate synom;
521///
522/// use syn::{Ident, Ty};
Alex Crichton954046c2017-05-30 21:49:42 -0700523/// use synom::tokens::*;
David Tolnay1f16b602017-02-07 20:06:55 -0500524///
525/// #[derive(Debug)]
526/// enum UnitType {
527/// Struct {
528/// name: Ident,
529/// },
530/// Enum {
531/// name: Ident,
532/// variant: Ident,
533/// },
534/// }
535///
536/// // Parse a unit struct or enum: either `struct S;` or `enum E { V }`.
537/// named!(unit_type -> UnitType, do_parse!(
Alex Crichton954046c2017-05-30 21:49:42 -0700538/// which: alt!(
539/// syn!(Struct) => { |_| 0 }
540/// |
541/// syn!(Enum) => { |_| 1 }
542/// ) >>
543/// id: syn!(Ident) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500544/// item: switch!(value!(which),
Alex Crichton954046c2017-05-30 21:49:42 -0700545/// 0 => map!(
546/// syn!(Semi),
David Tolnay1f16b602017-02-07 20:06:55 -0500547/// move |_| UnitType::Struct {
548/// name: id,
549/// }
550/// )
551/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700552/// 1 => map!(
553/// braces!(syn!(Ident)),
554/// move |(variant, _)| UnitType::Enum {
David Tolnay1f16b602017-02-07 20:06:55 -0500555/// name: id,
556/// variant: variant,
557/// }
558/// )
559/// ) >>
560/// (item)
561/// ));
562///
Alex Crichton954046c2017-05-30 21:49:42 -0700563/// # fn main() {}
David Tolnay1f16b602017-02-07 20:06:55 -0500564/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500565#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700566macro_rules! value {
567 ($i:expr, $res:expr) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400568 ::std::result::Result::Ok(($i, $res))
David Tolnayb5a7b142016-09-13 22:46:39 -0700569 };
570}
571
David Tolnay1f16b602017-02-07 20:06:55 -0500572/// Run a series of parsers and produce all of the results in a tuple.
Michael Layzell24645a32017-02-04 13:19:26 -0500573///
David Tolnay1f16b602017-02-07 20:06:55 -0500574/// - **Syntax:** `tuple!(A, B, C, ...)`
575/// - **Output:** `(A, B, C, ...)`
Michael Layzell24645a32017-02-04 13:19:26 -0500576///
577/// ```rust
578/// extern crate syn;
579/// #[macro_use] extern crate synom;
580///
581/// use syn::Ty;
Michael Layzell24645a32017-02-04 13:19:26 -0500582///
Alex Crichton954046c2017-05-30 21:49:42 -0700583/// named!(two_types -> (Ty, Ty), tuple!(syn!(Ty), syn!(Ty)));
Michael Layzell24645a32017-02-04 13:19:26 -0500584///
Alex Crichton954046c2017-05-30 21:49:42 -0700585/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500586/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500587#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700588macro_rules! tuple {
589 ($i:expr, $($rest:tt)*) => {
590 tuple_parser!($i, (), $($rest)*)
591 };
592}
593
David Tolnay1f16b602017-02-07 20:06:55 -0500594/// Internal parser, do not use directly.
Michael Layzell5bde96f2017-01-24 17:59:21 -0500595#[doc(hidden)]
596#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700597macro_rules! tuple_parser {
598 ($i:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700599 tuple_parser!($i, ($($parsed),*), call!($e), $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700600 };
601
602 ($i:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => {
603 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400604 ::std::result::Result::Err(err) =>
605 ::std::result::Result::Err(err),
606 ::std::result::Result::Ok((i, o)) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700607 tuple_parser!(i, (o), $($rest)*),
608 }
609 };
610
611 ($i:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => {
612 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400613 ::std::result::Result::Err(err) =>
614 ::std::result::Result::Err(err),
615 ::std::result::Result::Ok((i, o)) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700616 tuple_parser!(i, ($($parsed)* , o), $($rest)*),
617 }
618 };
619
620 ($i:expr, ($($parsed:tt),*), $e:ident) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700621 tuple_parser!($i, ($($parsed),*), call!($e))
David Tolnayb5a7b142016-09-13 22:46:39 -0700622 };
623
624 ($i:expr, (), $submac:ident!( $($args:tt)* )) => {
625 $submac!($i, $($args)*)
626 };
627
628 ($i:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => {
629 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400630 ::std::result::Result::Err(err) =>
631 ::std::result::Result::Err(err),
632 ::std::result::Result::Ok((i, o)) =>
633 ::std::result::Result::Ok((i, ($($parsed),*, o))),
David Tolnayb5a7b142016-09-13 22:46:39 -0700634 }
635 };
636
637 ($i:expr, ($($parsed:expr),*)) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400638 ::std::result::Result::Ok(($i, ($($parsed),*)))
David Tolnayb5a7b142016-09-13 22:46:39 -0700639 };
640}
641
David Tolnay1f16b602017-02-07 20:06:55 -0500642/// Run a series of parsers, returning the result of the first one which
643/// succeeds.
Michael Layzell24645a32017-02-04 13:19:26 -0500644///
645/// Optionally allows for the result to be transformed.
646///
647/// - **Syntax:** `alt!(THING1 | THING2 => { FUNC } | ...)`
David Tolnay1f16b602017-02-07 20:06:55 -0500648/// - **Output:** `T`, the return type of `THING1` and `FUNC(THING2)` and ...
Michael Layzell24645a32017-02-04 13:19:26 -0500649///
650/// ```rust
651/// extern crate syn;
652/// #[macro_use] extern crate synom;
653///
654/// use syn::Ident;
Alex Crichton954046c2017-05-30 21:49:42 -0700655/// use synom::tokens::Bang;
Michael Layzell24645a32017-02-04 13:19:26 -0500656///
657/// named!(ident_or_bang -> Ident,
David Tolnay1f16b602017-02-07 20:06:55 -0500658/// alt!(
Alex Crichton954046c2017-05-30 21:49:42 -0700659/// syn!(Ident)
David Tolnay1f16b602017-02-07 20:06:55 -0500660/// |
Alex Crichton954046c2017-05-30 21:49:42 -0700661/// syn!(Bang) => { |_| "BANG".into() }
David Tolnay1f16b602017-02-07 20:06:55 -0500662/// )
663/// );
Michael Layzell24645a32017-02-04 13:19:26 -0500664///
Alex Crichton954046c2017-05-30 21:49:42 -0700665/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500666/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500667#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700668macro_rules! alt {
669 ($i:expr, $e:ident | $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700670 alt!($i, call!($e) | $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700671 };
672
673 ($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => {
674 match $subrule!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400675 res @ ::std::result::Result::Ok(_) => res,
David Tolnayb5a7b142016-09-13 22:46:39 -0700676 _ => alt!($i, $($rest)*)
677 }
678 };
679
680 ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => {
681 match $subrule!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400682 ::std::result::Result::Ok((i, o)) =>
683 ::std::result::Result::Ok((i, $gen(o))),
684 ::std::result::Result::Err(_) => alt!($i, $($rest)*),
David Tolnayb5a7b142016-09-13 22:46:39 -0700685 }
686 };
687
688 ($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700689 alt!($i, call!($e) => { $gen } | $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700690 };
691
692 ($i:expr, $e:ident => { $gen:expr }) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700693 alt!($i, call!($e) => { $gen })
David Tolnayb5a7b142016-09-13 22:46:39 -0700694 };
695
696 ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => {
697 match $subrule!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400698 ::std::result::Result::Ok((i, o)) =>
699 ::std::result::Result::Ok((i, $gen(o))),
700 ::std::result::Result::Err(err) =>
701 ::std::result::Result::Err(err),
David Tolnayb5a7b142016-09-13 22:46:39 -0700702 }
703 };
704
705 ($i:expr, $e:ident) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700706 alt!($i, call!($e))
David Tolnayb5a7b142016-09-13 22:46:39 -0700707 };
708
709 ($i:expr, $subrule:ident!( $($args:tt)*)) => {
David Tolnay5377b172016-10-25 01:13:12 -0700710 $subrule!($i, $($args)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700711 };
712}
713
Michael Layzell24645a32017-02-04 13:19:26 -0500714/// Run a series of parsers, one after another, optionally assigning the results
David Tolnay1f16b602017-02-07 20:06:55 -0500715/// a name. Fail if any of the parsers fails.
Michael Layzell24645a32017-02-04 13:19:26 -0500716///
David Tolnay1f16b602017-02-07 20:06:55 -0500717/// Produces the result of evaluating the final expression in parentheses with
718/// all of the previously named results bound.
Michael Layzell24645a32017-02-04 13:19:26 -0500719///
David Tolnay1f16b602017-02-07 20:06:55 -0500720/// - **Syntax:** `do_parse!(name: THING1 >> THING2 >> (RESULT))`
Michael Layzell24645a32017-02-04 13:19:26 -0500721/// - **Output:** `RESULT`
722///
723/// ```rust
724/// extern crate syn;
725/// #[macro_use] extern crate synom;
Alex Crichton954046c2017-05-30 21:49:42 -0700726/// extern crate proc_macro2;
Michael Layzell24645a32017-02-04 13:19:26 -0500727///
728/// use syn::{Ident, TokenTree};
Alex Crichton954046c2017-05-30 21:49:42 -0700729/// use synom::tokens::{Bang, Paren};
730/// use proc_macro2::TokenStream;
Michael Layzell24645a32017-02-04 13:19:26 -0500731///
David Tolnay1f16b602017-02-07 20:06:55 -0500732/// // Parse a macro invocation like `stringify!($args)`.
Alex Crichton954046c2017-05-30 21:49:42 -0700733/// named!(simple_mac -> (Ident, (TokenStream, Paren)), do_parse!(
734/// name: syn!(Ident) >>
735/// syn!(Bang) >>
736/// body: parens!(syn!(TokenStream)) >>
David Tolnay1f16b602017-02-07 20:06:55 -0500737/// (name, body)
738/// ));
Michael Layzell24645a32017-02-04 13:19:26 -0500739///
Alex Crichton954046c2017-05-30 21:49:42 -0700740/// # fn main() {}
Michael Layzell24645a32017-02-04 13:19:26 -0500741/// ```
Michael Layzell5bde96f2017-01-24 17:59:21 -0500742#[macro_export]
David Tolnayb5a7b142016-09-13 22:46:39 -0700743macro_rules! do_parse {
744 ($i:expr, ( $($rest:expr),* )) => {
Michael Layzell760fd662017-05-31 22:46:05 -0400745 ::std::result::Result::Ok(($i, ( $($rest),* )))
David Tolnayb5a7b142016-09-13 22:46:39 -0700746 };
747
748 ($i:expr, $e:ident >> $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700749 do_parse!($i, call!($e) >> $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700750 };
751
752 ($i:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
753 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400754 ::std::result::Result::Err(err) =>
755 ::std::result::Result::Err(err),
756 ::std::result::Result::Ok((i, _)) =>
David Tolnayb5a7b142016-09-13 22:46:39 -0700757 do_parse!(i, $($rest)*),
758 }
759 };
760
761 ($i:expr, $field:ident : $e:ident >> $($rest:tt)*) => {
David Tolnayb81c7a42016-10-25 10:12:12 -0700762 do_parse!($i, $field: call!($e) >> $($rest)*)
David Tolnayb5a7b142016-09-13 22:46:39 -0700763 };
764
765 ($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => {
766 match $submac!($i, $($args)*) {
Michael Layzell760fd662017-05-31 22:46:05 -0400767 ::std::result::Result::Err(err) =>
768 ::std::result::Result::Err(err),
769 ::std::result::Result::Ok((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 Layzell760fd662017-05-31 22:46:05 -0400782 ::std::result::Result::Err(err) =>
783 ::std::result::Result::Err(err),
784 ::std::result::Result::Ok((i, o)) => {
David Tolnayfa0edf22016-09-23 22:58:24 -0700785 let mut $field = o;
786 do_parse!(i, $($rest)*)
787 },
788 }
789 };
David Tolnayb5a7b142016-09-13 22:46:39 -0700790}
Michael Layzell416724e2017-05-24 21:12:34 -0400791
792#[macro_export]
793macro_rules! input_end {
794 ($i:expr,) => {
795 $crate::input_end($i)
796 };
797}
798
799// Not a public API
800#[doc(hidden)]
Michael Layzell760fd662017-05-31 22:46:05 -0400801pub fn input_end(input: Cursor) -> PResult<'static, &'static str> {
Michael Layzell0a1a6632017-06-02 18:07:43 -0400802 if input.eof() {
803 Ok((Cursor::empty(), ""))
Michael Layzell416724e2017-05-24 21:12:34 -0400804 } else {
Michael Layzell760fd662017-05-31 22:46:05 -0400805 parse_error()
Michael Layzell416724e2017-05-24 21:12:34 -0400806 }
807}