Skip to main content

combpop/
parser.rs

1use Stream;
2use combinators;
3use iter;
4
5#[derive(Debug)]
6pub enum ParseError {
7    EOF,
8    NotReady,
9    SyntaxError,
10}
11impl ParseError {
12    pub fn is_recoverable(&self) -> bool {
13        match self {
14            &ParseError::EOF | &ParseError::SyntaxError => true,
15            &ParseError::NotReady => false,
16        }
17    }
18}
19
20pub type ParseResult<T> = Result<T, ParseError>;
21
22/// A flag to indicate whether a parser consumed a token or not.
23///
24/// # Example
25///
26/// ```
27/// # extern crate combpop;
28/// # use combpop::Consume;
29/// # fn main() {
30/// assert_eq!(Consume::Empty | Consume::Consumed, Consume::Consumed);
31/// assert_eq!(Consume::Empty & Consume::Consumed, Consume::Empty);
32/// # }
33/// ```
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35pub enum Consume {
36    Consumed,
37    Empty,
38}
39impl Default for Consume {
40    fn default() -> Self {
41        Consume::Consumed
42    }
43}
44impl ::std::ops::BitAnd for Consume {
45    type Output = Self;
46    fn bitand(self, rhs: Self) -> Self {
47        match self {
48            Consume::Consumed => rhs,
49            Consume::Empty => Consume::Empty,
50        }
51    }
52}
53impl ::std::ops::BitAndAssign for Consume {
54    fn bitand_assign(&mut self, rhs: Self) {
55        *self = *self & rhs;
56    }
57}
58impl ::std::ops::BitOr for Consume {
59    type Output = Self;
60    fn bitor(self, rhs: Self) -> Self {
61        match self {
62            Consume::Consumed => Consume::Consumed,
63            Consume::Empty => rhs,
64        }
65    }
66}
67impl ::std::ops::BitOrAssign for Consume {
68    fn bitor_assign(&mut self, rhs: Self) {
69        *self = *self | rhs;
70    }
71}
72
73/// Stream-independent properties of parsers and parser-building methods.
74///
75/// See `Parser` for the actual parsing functionality. See `combinators`, `iter`, and `bytes` for
76/// other parser-building functions.
77pub trait ParserBase {
78    /// The input type of the parser. `u8` for byte-eating parsers.
79    type Input;
80    /// The output type which this monadic parser produces.
81    type Output;
82    /// Whether the parser "usually" accepts the empty sequence. Only used in `emit_expectations`.
83    fn emptiable() -> bool
84    where
85        Self: Sized,
86    {
87        false
88    }
89
90    /// Converts a semantic value after parsing. Similar to `ParserBase::map`, but accepts `FnOnce`
91    /// closures.
92    fn map_once<O, F>(self, f: F) -> combinators::Map<O, Self, F>
93    where
94        Self: Sized,
95        F: FnOnce(Self::Output) -> O,
96    {
97        combinators::map_once(self, f)
98    }
99
100    /// Converts a semantic value after parsing. Similar to `ParserBase::map`, but accepts `FnMut`
101    /// closures.
102    fn map_mut<O, F>(self, f: F) -> combinators::Map<O, Self, F>
103    where
104        Self: Sized,
105        F: FnMut(Self::Output) -> O,
106    {
107        combinators::map_mut(self, f)
108    }
109
110    /// Converts a semantic value after parsing.
111    fn map<O, F>(self, f: F) -> combinators::Map<O, Self, F>
112    where
113        Self: Sized,
114        F: Fn(Self::Output) -> O,
115    {
116        combinators::map(self, f)
117    }
118
119    /// Monadic operator: run another parser `f(x)` after parsing. Similar to
120    /// `ParserBase::and_then`, but accepts `FnOnce` closures.
121    fn and_then_once<P, F>(self, f: F) -> combinators::AndThen<Self, P, F>
122    where
123        Self: Sized,
124        P: ParserBase<Input = Self::Input>,
125        F: FnOnce(Self::Output) -> P,
126    {
127        combinators::and_then_once(self, f)
128    }
129
130    /// Monadic operator: run another parser `f(x)` after parsing. Similar to
131    /// `ParserBase::and_then`, but accepts `FnMut` closures.
132    fn and_then_mut<P, F>(self, f: F) -> combinators::AndThen<Self, P, F>
133    where
134        Self: Sized,
135        P: ParserBase<Input = Self::Input>,
136        F: FnMut(Self::Output) -> P,
137    {
138        combinators::and_then_mut(self, f)
139    }
140
141    /// Monadic operator: run another parser `f(x)` after parsing.
142    ///
143    /// # Restrictions
144    ///
145    /// Applicative construction (`concat` + `map`) is recommended than `and_then`. Since the
146    /// value-dependency of the monadic construction, it may prevent useful optimizations. For
147    /// example, `AndThen::emit_expectations` cannot emit expectations from the latter parser.
148    fn and_then<P, F>(self, f: F) -> combinators::AndThen<Self, P, F>
149    where
150        Self: Sized,
151        P: ParserBase<Input = Self::Input>,
152        F: Fn(Self::Output) -> P,
153    {
154        combinators::and_then(self, f)
155    }
156
157    /// Applicative operator: run another parser `p` after parsing. The result is a pair of the
158    /// result of the parsers.
159    fn concat<P>(self, p: P) -> combinators::Concat2<Self, P>
160    where
161        Self: Sized,
162        P: ParserBase<Input = Self::Input>,
163    {
164        combinators::concat2(self, p)
165    }
166
167    /// If the parser failed without consumption, try another parser.
168    fn or<P>(self, p: P) -> combinators::Choice2<Self, P>
169    where
170        Self: Sized,
171        P: ParserBase<Input = Self::Input, Output = Self::Output>,
172    {
173        combinators::choice2(self, p)
174    }
175
176    /// Returns a `ParserIteratorBase` that collects one or more objects from this parser.
177    fn many1(self) -> iter::Many1<Self>
178    where
179        Self: Sized,
180    {
181        iter::many1(self)
182    }
183}
184pub trait ParserOnce<S: Stream<Item = Self::Input> + ?Sized>: ParserBase {
185    fn parse_lookahead_once(self, stream: &mut S) -> ParseResult<Option<(Self::Output, Consume)>>
186    where
187        Self: Sized;
188    fn emit_expectations(&self, stream: &mut S);
189}
190pub trait ParserMut<S: Stream<Item = Self::Input> + ?Sized>: ParserOnce<S> {
191    fn parse_mut(&mut self, stream: &mut S) -> ParseResult<Self::Output> {
192        Ok(self.parse_consume_mut(stream)?.0)
193    }
194    fn parse_consume_mut(&mut self, stream: &mut S) -> ParseResult<(Self::Output, Consume)> {
195        if let Some(x) = self.parse_lookahead_mut(stream)? {
196            Ok(x)
197        } else {
198            self.emit_expectations(stream);
199            Err(ParseError::SyntaxError)
200        }
201    }
202    fn parse_lookahead_mut(
203        &mut self,
204        stream: &mut S,
205    ) -> ParseResult<Option<(Self::Output, Consume)>>;
206}
207pub trait Parser<S: Stream<Item = Self::Input> + ?Sized>: ParserMut<S> {
208    fn parse(&self, stream: &mut S) -> ParseResult<Self::Output> {
209        Ok(self.parse_consume(stream)?.0)
210    }
211    fn parse_consume(&self, stream: &mut S) -> ParseResult<(Self::Output, Consume)> {
212        if let Some(x) = self.parse_lookahead(stream)? {
213            Ok(x)
214        } else {
215            self.emit_expectations(stream);
216            Err(ParseError::SyntaxError)
217        }
218    }
219    fn parse_lookahead(&self, stream: &mut S) -> ParseResult<Option<(Self::Output, Consume)>>;
220}
221
222macro_rules! delegate_parser_once {
223    ($this:expr) => {
224        fn parse_lookahead_once(self, stream: &mut S)
225            -> ParseResult<Option<(Self::Output, Consume)>>
226        where
227            Self: Sized,
228        {
229            ParserOnce::parse_lookahead_once($this, stream)
230        }
231    }
232}
233macro_rules! delegate_parser_mut {
234    ($this:expr) => {
235        fn parse_mut(&mut self, stream: &mut S) -> ParseResult<Self::Output> {
236            ParserMut::parse_mut($this, stream)
237        }
238        fn parse_consume_mut(&mut self, stream: &mut S) -> ParseResult<(Self::Output, Consume)> {
239            ParserMut::parse_consume_mut($this, stream)
240        }
241        fn parse_lookahead_mut(&mut self, stream: &mut S)
242            -> ParseResult<Option<(Self::Output, Consume)>> {
243            ParserMut::parse_lookahead_mut($this, stream)
244        }
245    }
246}
247macro_rules! delegate_parser {
248    ($this:expr) => {
249        fn parse(&self, stream: &mut S) -> ParseResult<Self::Output> {
250            Parser::parse($this, stream)
251        }
252        fn parse_consume(&self, stream: &mut S) -> ParseResult<(Self::Output, Consume)> {
253            Parser::parse_consume($this, stream)
254        }
255        fn parse_lookahead(&self, stream: &mut S)
256            -> ParseResult<Option<(Self::Output, Consume)>> {
257            Parser::parse_lookahead($this, stream)
258        }
259    }
260}