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