1 //! Basic types to build the parsers
2 
3 use self::Needed::*;
4 
5 #[cfg(feature = "verbose-errors")]
6 use verbose_errors::Context;
7 
8 #[cfg(not(feature = "verbose-errors"))]
9 use simple_errors::Context;
10 
11 /// Holds the result of parsing functions
12 ///
13 /// It depends on I, the input type, O, the output type, and E, the error type (by default u32)
14 ///
15 /// The `Ok` side is an enum containing the remainder of the input (the part of the data that
16 /// was not parsed) and the produced value. The `Err` side contains an instance of `nom::Err`.
17 ///
18 pub type IResult<I, O, E = u32> = Result<(I, O), Err<I, E>>;
19 
20 /// Contains information on needed data if a parser returned `Incomplete`
21 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
22 pub enum Needed {
23   /// needs more data, but we do not know how much
24   Unknown,
25   /// contains the required data size
26   Size(usize),
27 }
28 
29 impl Needed {
is_known(&self) -> bool30   pub fn is_known(&self) -> bool {
31     *self != Unknown
32   }
33 
34   /// Maps a `Needed` to `Needed` by appling a function to a contained `Size` value.
35   #[inline]
map<F: FnOnce(usize) -> usize>(self, f: F) -> Needed36   pub fn map<F: FnOnce(usize) -> usize>(self, f: F) -> Needed {
37     match self {
38       Unknown => Unknown,
39       Size(n) => Size(f(n)),
40     }
41   }
42 }
43 
44 /// The `Err` enum indicates the parser was not successful
45 ///
46 /// It has three cases:
47 ///
48 /// * `Incomplete` indicates that more data is needed to decide. The `Needed` enum
49 /// can contain how many additional bytes are necessary. If you are sure your parser
50 /// is working on full data, you can wrap your parser with the `complete` combinator
51 /// to transform that case in `Error`
52 /// * `Error` means some parser did not succeed, but another one might (as an example,
53 /// when testing different branches of an `alt` combinator)
54 /// * `Failure` indicates an unrecoverable error. As an example, if you recognize a prefix
55 /// to decide on the next parser to apply, and that parser fails, you know there's no need
56 /// to try other parsers, you were already in the right branch, so the data is invalid
57 ///
58 /// Depending on a compilation flag, the content of the `Context` enum
59 /// can change. In the default case, it will only have one variant:
60 /// `Context::Code(I, ErrorKind<E=u32>)` (with `I` and `E` configurable).
61 /// It contains an error code and the input position that triggered it.
62 ///
63 /// If you activate the `verbose-errors` compilation flags, it will add another
64 /// variant to the enum: `Context::List(Vec<(I, ErrorKind<E>)>)`.
65 /// This variant aggregates positions and error codes as the code backtracks
66 /// through the nested parsers.
67 /// The verbose errors feature allows for very flexible error management:
68 /// you can know precisely which parser got to which part of the input.
69 /// The main drawback is that it is a lot slower than default error
70 /// management.
71 #[derive(Debug, Clone, PartialEq)]
72 pub enum Err<I, E = u32> {
73   /// There was not enough data
74   Incomplete(Needed),
75   /// The parser had an error (recoverable)
76   Error(Context<I, E>),
77   /// The parser had an unrecoverable error: we got to the right
78   /// branch and we know other branches won't work, so backtrack
79   /// as fast as possible
80   Failure(Context<I, E>),
81 }
82 
83 #[cfg(feature = "std")]
84 use std::fmt;
85 
86 #[cfg(feature = "std")]
87 impl<I, E> fmt::Display for Err<I, E>
88 where
89   I: fmt::Debug,
90   E: fmt::Debug,
91 {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result92   fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93     write!(f, "{:?}", self)
94   }
95 }
96 
97 #[cfg(feature = "std")]
98 use std::error::Error;
99 
100 #[cfg(feature = "std")]
101 impl<I, E> Error for Err<I, E>
102 where
103   I: fmt::Debug,
104   E: fmt::Debug,
105 {
description(&self) -> &str106   fn description(&self) -> &str {
107     match self {
108       &Err::Incomplete(..) => "there was not enough data",
109       &Err::Error(Context::Code(_, ref error_kind)) | &Err::Failure(Context::Code(_, ref error_kind)) => error_kind.description(),
110       #[cfg(feature = "verbose-errors")]
111       &Err::Error(Context::List(..)) | &Err::Failure(Context::List(..)) => "list of errors",
112     }
113   }
114 
cause(&self) -> Option<&Error>115   fn cause(&self) -> Option<&Error> {
116     None
117   }
118 }
119 
120 use util::Convert;
121 
122 impl<I, H: From<I>, F, E: From<F>> Convert<Err<I, F>> for Err<H, E> {
convert(e: Err<I, F>) -> Self123   fn convert(e: Err<I, F>) -> Self {
124     match e {
125       Err::Incomplete(n) => Err::Incomplete(n),
126       Err::Failure(c) => Err::Failure(Context::convert(c)),
127       Err::Error(c) => Err::Error(Context::convert(c)),
128     }
129   }
130 }
131 
132 impl<I, E> Err<I, E> {
into_error_kind(self) -> ::util::ErrorKind<E>133   pub fn into_error_kind(self) -> ::util::ErrorKind<E> {
134     match self {
135       Err::Incomplete(_) => ::util::ErrorKind::Complete,
136       Err::Failure(c) => c.into_error_kind(),
137       Err::Error(c) => c.into_error_kind(),
138     }
139   }
140 
is_incomplete(&self) -> bool141   pub fn is_incomplete(&self) -> bool {
142     match *self {
143       Err::Incomplete(_) => true,
144       _ => false,
145     }
146   }
147 }
148 
149 /*
150 #[cfg(feature = "verbose-errors")]
151 /// This is the same as IResult, but without Done
152 ///
153 /// This is used as the Error type when converting to std::result::Result
154 #[derive(Debug,PartialEq,Eq,Clone)]
155 pub enum IError<I,E=u32> {
156   Error(Err<I,E>),
157   Incomplete(Needed)
158 }
159 
160 #[cfg(not(feature = "verbose-errors"))]
161 /// This is the same as IResult, but without Done
162 ///
163 /// This is used as the Error type when converting to std::result::Result
164 #[derive(Debug,PartialEq,Eq,Clone)]
165 pub enum IError<E=u32> {
166   Error(Err<E>),
167   Incomplete(Needed)
168 }
169 
170 impl<I,O,E> IResult<I,O,E> {
171   pub fn is_done(&self) -> bool {
172     match *self {
173       Done(_,_) => true,
174       _         => false
175     }
176   }
177 
178   pub fn is_err(&self) -> bool {
179     match *self {
180       Error(_) => true,
181       _        => false
182     }
183   }
184 
185   pub fn is_incomplete(&self) -> bool {
186     match *self {
187       Incomplete(_) => true,
188       _             => false
189     }
190   }
191 
192   pub fn or(self, other: IResult<I, O, E>) -> IResult<I, O, E> {
193     if self.is_done() {
194       self
195     } else {
196       other
197     }
198   }
199 
200   /// Maps a `IResult<I, O, E>` to `IResult<I, N, E>` by appling a function
201   /// to a contained `Done` value, leaving `Error` and `Incomplete` value
202   /// untouched.
203   #[inline]
204   pub fn map<N, F: FnOnce(O) -> N>(self, f: F) -> IResult<I, N, E> {
205     match self {
206       Done(i, o)    => Done(i, f(o)),
207       Error(e)      => Error(e),
208       Incomplete(n) => Incomplete(n),
209     }
210   }
211 
212   /// Maps a `IResult<I, O, E>` to `IResult<I, O, E>` by appling a function
213   /// to a contained `Incomplete` value, leaving `Done` and `Error` value
214   /// untouched.
215   #[inline]
216   pub fn map_inc<F>(self, f: F) -> IResult<I, O, E>
217    where F: FnOnce(Needed) -> Needed {
218     match self {
219       Error(e)      => Error(e),
220       Incomplete(n) => Incomplete(f(n)),
221       Done(i, o)    => Done(i, o),
222     }
223   }
224 
225   /// Unwrap the contained `Done(I, O)` value, or panic if the `IResult` is not
226   /// `Done`.
227   pub fn unwrap(self) -> (I, O) {
228     match self {
229       Done(i, o)    => (i, o),
230       Incomplete(_) => panic!("unwrap() called on an IResult that is Incomplete"),
231       Error(_)      => panic!("unwrap() called on an IResult that is Error")
232     }
233   }
234 
235   /// Unwrap the contained `Done(I, O)` value or a default if the `IResult` is not
236   /// `Done`.
237   pub fn unwrap_or(self, default: (I, O)) -> (I, O) {
238     match self {
239       Done(i, o)    => (i, o),
240       Incomplete(_) => default,
241       Error(_)      => default
242     }
243   }
244 
245   /// Unwrap the contained `Incomplete(n)` value, or panic if the `IResult` is not
246   /// `Incomplete`.
247   pub fn unwrap_inc(self) -> Needed {
248     match self {
249       Incomplete(n) => n,
250       Done(_, _)    => panic!("unwrap_inc() called on an IResult that is Done"),
251       Error(_)      => panic!("unwrap_inc() called on an IResult that is Error")
252     }
253   }
254 }
255 
256 pub trait GetInput<I> {
257   fn remaining_input(&self) -> Option<I>;
258 }
259 
260 pub trait GetOutput<O> {
261   fn output(&self) -> Option<O>;
262 }
263 
264 impl<'a,I,O,E> GetInput<&'a[I]> for IResult<&'a[I],O,E> {
265   fn remaining_input(&self) -> Option<&'a[I]> {
266     match *self {
267       Done(ref i,_) => Some(*i),
268       _             => None
269     }
270   }
271 }
272 
273 impl<O,E> GetInput<()> for IResult<(),O,E> {
274   fn remaining_input(&self) -> Option<()> {
275     match *self {
276       Done((),_) => Some(()),
277       _          => None
278     }
279   }
280 }
281 
282 impl<'a,O,E> GetInput<&'a str> for IResult<&'a str,O,E> {
283   fn remaining_input(&self) -> Option<&'a str> {
284     match *self {
285       Done(ref i,_) => Some(*i),
286       _          => None
287     }
288   }
289 }
290 
291 impl<'a,I,O,E> GetOutput<&'a[O]> for IResult<I,&'a[O],E> {
292   fn output(&self) -> Option<&'a[O]> {
293     match *self {
294       Done(_, ref o) => Some(*o),
295       _              => None
296     }
297   }
298 }
299 
300 impl<I,E> GetOutput<()> for IResult<I,(),E> {
301   fn output(&self) -> Option<()> {
302     match *self {
303       Done(_,()) => Some(()),
304       _          => None
305     }
306   }
307 }
308 
309 impl<'a,I,E> GetOutput<&'a str> for IResult<I,&'a str,E> {
310   fn output(&self) -> Option<&'a str> {
311     match *self {
312       Done(_,ref o) => Some(*o),
313       _          => None
314     }
315   }
316 }*/
317 
318 #[cfg(feature = "verbose-errors")]
319 /// creates a parse error from a `nom::ErrorKind`
320 /// and the position in the input
321 /// if "verbose-errors" is not activated,
322 /// it default to only the error code
323 #[macro_export(local_inner_macros)]
324 macro_rules! error_position(
325   ($input: expr, $code:expr) => ({
326     $crate::Context::Code($input, $code)
327   });
328 );
329 
330 #[cfg(not(feature = "verbose-errors"))]
331 /// creates a parse error from a `nom::ErrorKind`
332 /// and the position in the input
333 /// if "verbose-errors" is not activated,
334 /// it default to only the error code
335 #[allow(unused_variables)]
336 #[macro_export(local_inner_macros)]
337 macro_rules! error_position(
338   ($input:expr, $code:expr) => ({
339     $crate::Context::Code($input, $code)
340   });
341 );
342 
343 #[cfg(feature = "verbose-errors")]
344 /// creates a parse error from a `nom::ErrorKind`,
345 /// the position in the input and the next error in
346 /// the parsing tree.
347 /// if "verbose-errors" is not activated,
348 /// it default to only the error code
349 #[macro_export(local_inner_macros)]
350 macro_rules! error_node_position(
351   ($input:expr, $code:expr, $next:expr) => {
352     {
353     let mut error_vec = match $next {
354       $crate::Context::Code(i, e) => {
355         let mut v = $crate::lib::std::vec::Vec::new();
356         v.push((i, e));
357         v
358       },
359       $crate::Context::List(v) => {
360         v
361       },
362     };
363 
364     error_vec.push(($input, $code));
365     $crate::Context::List(error_vec)
366     }
367   }
368 );
369 
370 #[cfg(not(feature = "verbose-errors"))]
371 /// creates a parse error from a `nom::ErrorKind`,
372 /// the position in the input and the next error in
373 /// the parsing tree.
374 /// if "verbose-errors" is not activated,
375 /// it default to only the error code
376 #[allow(unused_variables)]
377 #[macro_export(local_inner_macros)]
378 macro_rules! error_node_position(
379   ($input:expr, $code:expr, $next:expr) => ({
380     fn unify_types<T>(_: &T, _: &T) {}
381     let res = $crate::Context::Code($input, $code);
382     unify_types(&res, &$next);
383     res
384   });
385 );
386 
387 #[cfg(test)]
388 mod tests {
389 
390   /*
391   const REST: [u8; 0] = [];
392   const DONE: IResult<&'static [u8], u32> = Ok((&REST, 5));
393   const ERROR: IResult<&'static [u8], u32> = Err(Err::Error(Context::Code(&b""[..], ErrorKind::Tag)));
394   const INCOMPLETE: IResult<&'static [u8], u32> = Err(Err::Incomplete(Needed::Unknown));
395   */
396 
397   /*
398   #[test]
399   fn iresult_or() {
400     assert_eq!(DONE.or(ERROR), DONE);
401     assert_eq!(ERROR.or(DONE), DONE);
402     assert_eq!(INCOMPLETE.or(ERROR), ERROR);
403   }
404 
405   #[test]
406   fn needed_map() {
407     let unknown = Needed::Unknown;
408     let size = Needed::Size(5);
409 
410     assert_eq!(size.map(|x| x * 2), Needed::Size(10));
411     assert_eq!(unknown.map(|x| x * 2), Needed::Unknown);
412   }
413 
414   #[test]
415   fn iresult_map() {
416     assert_eq!(DONE.map(|x| x * 2), IResult::Done(&b""[..], 10));
417     assert_eq!(ERROR.map(|x| x * 2), IResult::Error(error_code!(ErrorKind::Tag)));
418     assert_eq!(INCOMPLETE.map(|x| x * 2), IResult::Incomplete(Needed::Unknown));
419   }
420 
421   #[test]
422   fn iresult_map_inc() {
423     let inc_unknown: IResult<&[u8], u32> = IResult::Incomplete(Needed::Unknown);
424     let inc_size: IResult<&[u8], u32> = IResult::Incomplete(Needed::Size(5));
425 
426     assert_eq!(DONE.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Done(&b""[..], 5));
427     assert_eq!(ERROR.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Error(error_code!(ErrorKind::Tag)));
428     assert_eq!(inc_unknown.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Incomplete(Needed::Unknown));
429     assert_eq!(inc_size.map_inc(|n| if let Needed::Size(i) = n {Needed::Size(i+1)} else {n}), IResult::Incomplete(Needed::Size(6)));
430   }
431 
432   #[test]
433   #[cfg(feature = "std")]
434   fn iresult_map_err() {
435     #[derive(Clone, Copy, Debug, PartialEq, Eq)]
436     struct Error(u32);
437 
438     let error_kind = error_code!(ErrorKind::Custom(Error(5)));
439 
440     assert_eq!(DONE.map_err(|_| error_kind.clone()), IResult::Done(&b""[..], 5));
441     assert_eq!(ERROR.map_err(|x| {println!("err: {:?}", x); error_kind.clone()}), IResult::Error(error_kind.clone()));
442     assert_eq!(INCOMPLETE.map_err(|x| {println!("err: {:?}", x); error_kind.clone()}), IResult::Incomplete(Needed::Unknown));
443   }
444 
445   #[test]
446   fn iresult_unwrap_on_done() {
447     assert_eq!(DONE.unwrap(), (&b""[..], 5));
448   }
449 
450   #[test]
451   #[should_panic]
452   fn iresult_unwrap_on_err() {
453     ERROR.unwrap();
454   }
455 
456   #[test]
457   #[should_panic]
458   fn iresult_unwrap_on_inc() {
459     INCOMPLETE.unwrap();
460   }
461 
462   #[test]
463   fn iresult_unwrap_or_on_done() {
464     assert_eq!(DONE.unwrap_or((&b""[..], 2)), (&b""[..], 5));
465   }
466 
467   #[test]
468   fn iresult_unwrap_or_on_err() {
469     assert_eq!(ERROR.unwrap_or((&b""[..], 2)), (&b""[..], 2));
470   }
471 
472   #[test]
473   fn iresult_unwrap_or_on_inc() {
474     assert_eq!(INCOMPLETE.unwrap_or((&b""[..], 2)), (&b""[..], 2));
475   }
476 
477   #[test]
478   #[should_panic]
479   fn iresult_unwrap_err_on_done() {
480     DONE.unwrap_err();
481   }
482 
483   #[test]
484   fn iresult_unwrap_err_on_err() {
485     assert_eq!(ERROR.unwrap_err(), error_code!(ErrorKind::Tag));
486   }
487 
488   #[test]
489   #[should_panic]
490   fn iresult_unwrap_err_on_inc() {
491     INCOMPLETE.unwrap_err();
492   }
493 
494   #[test]
495   #[should_panic]
496   fn iresult_unwrap_inc_on_done() {
497     DONE.unwrap_inc();
498   }
499 
500   #[test]
501   #[should_panic]
502   fn iresult_unwrap_inc_on_err() {
503     ERROR.unwrap_inc();
504   }
505 
506   #[test]
507   fn iresult_unwrap_inc_on_inc() {
508     assert_eq!(INCOMPLETE.unwrap_inc(), Needed::Unknown);
509   }
510 
511   #[test]
512   fn iresult_to_result() {
513     assert_eq!(DONE.to_result(), Ok(5));
514     assert_eq!(ERROR.to_result(), Err(error_code!(ErrorKind::Tag)));
515   }
516 
517   #[test]
518   #[should_panic]
519   fn iresult_to_result_on_incomplete() {
520     INCOMPLETE.to_result().unwrap();
521   }
522 
523   #[test]
524   fn iresult_to_full_result() {
525     assert_eq!(DONE.to_full_result(), Ok(5));
526     assert_eq!(INCOMPLETE.to_full_result(), Err(IError::Incomplete(Needed::Unknown)));
527     assert_eq!(ERROR.to_full_result(), Err(IError::Error(error_code!(ErrorKind::Tag))));
528   }
529   */
530 }
531