oxedyne/fe2o3/fe2o3_text/tests/annealer_corpus/nom_combinator.rs
27.5 KiB, 1 run
created by r1870400018:11754, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! General purpose combinators |
| 2 | |
| 3 | #![allow(unused_imports)] |
| 4 | |
| 5 | use core::marker::PhantomData; |
| 6 | |
| 7 | #[cfg(feature = "alloc")] |
| 8 | use crate::lib::std::boxed::Box; |
| 9 | |
| 10 | use crate::error::{ErrorKind, FromExternalError, ParseError}; |
| 11 | use crate::internal::*; |
| 12 | use crate::lib::std::borrow::Borrow; |
| 13 | use crate::lib::std::convert::Into; |
| 14 | #[cfg(feature = "std")] |
| 15 | use crate::lib::std::fmt::Debug; |
| 16 | use crate::lib::std::mem::transmute; |
| 17 | use crate::lib::std::ops::{Range, RangeFrom, RangeTo}; |
| 18 | use crate::traits::{AsChar, Input, ParseTo}; |
| 19 | use crate::traits::{Compare, CompareResult, Offset}; |
| 20 | |
| 21 | #[cfg(test)] |
| 22 | mod tests; |
| 23 | |
| 24 | /// Return the remaining input. |
| 25 | /// |
| 26 | /// ```rust |
| 27 | /// # use nom::error::ErrorKind; |
| 28 | /// use nom::combinator::rest; |
| 29 | /// assert_eq!(rest::<_,(_, ErrorKind)>("abc"), Ok(("", "abc"))); |
| 30 | /// assert_eq!(rest::<_,(_, ErrorKind)>(""), Ok(("", ""))); |
| 31 | /// ``` |
| 32 | #[inline] |
| 33 | pub fn rest<T, E: ParseError<T>>(input: T) -> IResult<T, T, E> |
| 34 | where |
| 35 | T: Input, |
| 36 | { |
| 37 | Ok(input.take_split(input.input_len())) |
| 38 | } |
| 39 | |
| 40 | /// Return the length of the remaining input. |
| 41 | /// |
| 42 | /// ```rust |
| 43 | /// # use nom::error::ErrorKind; |
| 44 | /// use nom::combinator::rest_len; |
| 45 | /// assert_eq!(rest_len::<_,(_, ErrorKind)>("abc"), Ok(("abc", 3))); |
| 46 | /// assert_eq!(rest_len::<_,(_, ErrorKind)>(""), Ok(("", 0))); |
| 47 | /// ``` |
| 48 | #[inline] |
| 49 | pub fn rest_len<T, E: ParseError<T>>(input: T) -> IResult<T, usize, E> |
| 50 | where |
| 51 | T: Input, |
| 52 | { |
| 53 | let len = input.input_len(); |
| 54 | Ok((input, len)) |
| 55 | } |
| 56 | |
| 57 | /// Maps a function on the result of a parser. |
| 58 | /// |
| 59 | /// ```rust |
| 60 | /// use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 61 | /// use nom::character::complete::digit1; |
| 62 | /// use nom::combinator::map; |
| 63 | /// # fn main() { |
| 64 | /// |
| 65 | /// let mut parser = map(digit1, |s: &str| s.len()); |
| 66 | /// |
| 67 | /// // the parser will count how many characters were returned by digit1 |
| 68 | /// assert_eq!(parser.parse("123456"), Ok(("", 6))); |
| 69 | /// |
| 70 | /// // this will fail if digit1 fails |
| 71 | /// assert_eq!(parser.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit)))); |
| 72 | /// # } |
| 73 | /// ``` |
| 74 | pub fn map<I, O, E: ParseError<I>, F, G>(parser: F, f: G) -> impl Parser<I, Output = O, Error = E> |
| 75 | where |
| 76 | F: Parser<I, Error = E>, |
| 77 | G: FnMut(<F as Parser<I>>::Output) -> O, |
| 78 | { |
| 79 | parser.map(f) |
| 80 | } |
| 81 | |
| 82 | /// Applies a function returning a `Result` over the result of a parser. |
| 83 | /// |
| 84 | /// ```rust |
| 85 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 86 | /// use nom::character::complete::digit1; |
| 87 | /// use nom::combinator::map_res; |
| 88 | /// # fn main() { |
| 89 | /// |
| 90 | /// let mut parse = map_res(digit1, |s: &str| s.parse::<u8>()); |
| 91 | /// |
| 92 | /// // the parser will convert the result of digit1 to a number |
| 93 | /// assert_eq!(parse.parse("123"), Ok(("", 123))); |
| 94 | /// |
| 95 | /// // this will fail if digit1 fails |
| 96 | /// assert_eq!(parse.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit)))); |
| 97 | /// |
| 98 | /// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`) |
| 99 | /// assert_eq!(parse.parse("123456"), Err(Err::Error(("123456", ErrorKind::MapRes)))); |
| 100 | /// # } |
| 101 | /// ``` |
| 102 | pub fn map_res<I: Clone, O, E: ParseError<I> + FromExternalError<I, E2>, E2, F, G>( |
| 103 | parser: F, |
| 104 | f: G, |
| 105 | ) -> impl Parser<I, Output = O, Error = E> |
| 106 | where |
| 107 | F: Parser<I, Error = E>, |
| 108 | G: FnMut(<F as Parser<I>>::Output) -> Result<O, E2>, |
| 109 | { |
| 110 | parser.map_res(f) |
| 111 | } |
| 112 | |
| 113 | /// Applies a function returning an `Option` over the result of a parser. |
| 114 | /// |
| 115 | /// ```rust |
| 116 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 117 | /// use nom::character::complete::digit1; |
| 118 | /// use nom::combinator::map_opt; |
| 119 | /// # fn main() { |
| 120 | /// |
| 121 | /// let mut parse = map_opt(digit1, |s: &str| s.parse::<u8>().ok()); |
| 122 | /// |
| 123 | /// // the parser will convert the result of digit1 to a number |
| 124 | /// assert_eq!(parse.parse("123"), Ok(("", 123))); |
| 125 | /// |
| 126 | /// // this will fail if digit1 fails |
| 127 | /// assert_eq!(parse.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit)))); |
| 128 | /// |
| 129 | /// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`) |
| 130 | /// assert_eq!(parse.parse("123456"), Err(Err::Error(("123456", ErrorKind::MapOpt)))); |
| 131 | /// # } |
| 132 | /// ``` |
| 133 | pub fn map_opt<I: Clone, O, E: ParseError<I>, F, G>( |
| 134 | parser: F, |
| 135 | f: G, |
| 136 | ) -> impl Parser<I, Output = O, Error = E> |
| 137 | where |
| 138 | F: Parser<I, Error = E>, |
| 139 | G: FnMut(<F as Parser<I>>::Output) -> Option<O>, |
| 140 | { |
| 141 | parser.map_opt(f) |
| 142 | } |
| 143 | |
| 144 | /// Applies a parser over the result of another one. |
| 145 | /// |
| 146 | /// ```rust |
| 147 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 148 | /// use nom::character::complete::digit1; |
| 149 | /// use nom::bytes::complete::take; |
| 150 | /// use nom::combinator::map_parser; |
| 151 | /// # fn main() { |
| 152 | /// |
| 153 | /// let mut parse = map_parser(take(5u8), digit1); |
| 154 | /// |
| 155 | /// assert_eq!(parse.parse("12345"), Ok(("", "12345"))); |
| 156 | /// assert_eq!(parse.parse("123ab"), Ok(("", "123"))); |
| 157 | /// assert_eq!(parse.parse("123"), Err(Err::Error(("123", ErrorKind::Eof)))); |
| 158 | /// # } |
| 159 | /// ``` |
| 160 | pub fn map_parser<I, O, E: ParseError<I>, F, G>( |
| 161 | parser: F, |
| 162 | applied_parser: G, |
| 163 | ) -> impl Parser<I, Output = O, Error = E> |
| 164 | where |
| 165 | F: Parser<I, Error = E>, |
| 166 | G: Parser<<F as Parser<I>>::Output, Output = O, Error = E>, |
| 167 | { |
| 168 | parser.and_then(applied_parser) |
| 169 | } |
| 170 | |
| 171 | /// Creates a new parser from the output of the first parser, then apply that parser over the rest of the input. |
| 172 | /// |
| 173 | /// ```rust |
| 174 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 175 | /// use nom::bytes::complete::take; |
| 176 | /// use nom::number::complete::u8; |
| 177 | /// use nom::combinator::flat_map; |
| 178 | /// # fn main() { |
| 179 | /// |
| 180 | /// let mut parse = flat_map(u8, take); |
| 181 | /// |
| 182 | /// assert_eq!(parse.parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..]))); |
| 183 | /// assert_eq!(parse.parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof)))); |
| 184 | /// # } |
| 185 | /// ``` |
| 186 | pub fn flat_map<I, O, E: ParseError<I>, F, G, H>( |
| 187 | parser: F, |
| 188 | applied_parser: G, |
| 189 | ) -> impl Parser<I, Output = O, Error = E> |
| 190 | where |
| 191 | F: Parser<I, Error = E>, |
| 192 | G: FnMut(<F as Parser<I>>::Output) -> H, |
| 193 | H: Parser<I, Output = O, Error = E>, |
| 194 | { |
| 195 | parser.flat_map(applied_parser) |
| 196 | } |
| 197 | |
| 198 | /// Optional parser, will return `None` on [`Err::Error`]. |
| 199 | /// |
| 200 | /// To chain an error up, see [`cut`]. |
| 201 | /// |
| 202 | /// ```rust |
| 203 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 204 | /// use nom::combinator::opt; |
| 205 | /// use nom::character::complete::alpha1; |
| 206 | /// # fn main() { |
| 207 | /// |
| 208 | /// fn parser(i: &str) -> IResult<&str, Option<&str>> { |
| 209 | /// opt(alpha1).parse(i) |
| 210 | /// } |
| 211 | /// |
| 212 | /// assert_eq!(parser("abcd;"), Ok((";", Some("abcd")))); |
| 213 | /// assert_eq!(parser("123;"), Ok(("123;", None))); |
| 214 | /// # } |
| 215 | /// ``` |
| 216 | pub fn opt<I: Clone, E: ParseError<I>, F>( |
| 217 | f: F, |
| 218 | ) -> impl Parser<I, Output = Option<<F as Parser<I>>::Output>, Error = E> |
| 219 | where |
| 220 | F: Parser<I, Error = E>, |
| 221 | { |
| 222 | Opt { parser: f } |
| 223 | } |
| 224 | |
| 225 | /// Parser implementation for [opt] |
| 226 | pub struct Opt<F> { |
| 227 | parser: F, |
| 228 | } |
| 229 | |
| 230 | impl<I, F: Parser<I>> Parser<I> for Opt<F> |
| 231 | where |
| 232 | I: Clone, |
| 233 | { |
| 234 | type Output = Option<<F as Parser<I>>::Output>; |
| 235 | |
| 236 | type Error = <F as Parser<I>>::Error; |
| 237 | |
| 238 | #[inline(always)] |
| 239 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 240 | let i = input.clone(); |
| 241 | match self |
| 242 | .parser |
| 243 | .process::<OutputM<OM::Output, Check, OM::Incomplete>>(input) |
| 244 | { |
| 245 | Ok((i, o)) => Ok((i, OM::Output::map(o, Some))), |
| 246 | Err(Err::Error(_)) => Ok((i, OM::Output::bind(|| None))), |
| 247 | Err(Err::Failure(e)) => Err(Err::Failure(e)), |
| 248 | Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)), |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// Calls the parser if the condition is met. |
| 254 | /// |
| 255 | /// ```rust |
| 256 | /// # use nom::{Err, error::{Error, ErrorKind}, IResult, Parser}; |
| 257 | /// use nom::combinator::cond; |
| 258 | /// use nom::character::complete::alpha1; |
| 259 | /// # fn main() { |
| 260 | /// |
| 261 | /// fn parser(b: bool, i: &str) -> IResult<&str, Option<&str>> { |
| 262 | /// cond(b, alpha1).parse(i) |
| 263 | /// } |
| 264 | /// |
| 265 | /// assert_eq!(parser(true, "abcd;"), Ok((";", Some("abcd")))); |
| 266 | /// assert_eq!(parser(false, "abcd;"), Ok(("abcd;", None))); |
| 267 | /// assert_eq!(parser(true, "123;"), Err(Err::Error(Error::new("123;", ErrorKind::Alpha)))); |
| 268 | /// assert_eq!(parser(false, "123;"), Ok(("123;", None))); |
| 269 | /// # } |
| 270 | /// ``` |
| 271 | pub fn cond<I, E: ParseError<I>, F>( |
| 272 | b: bool, |
| 273 | f: F, |
| 274 | ) -> impl Parser<I, Output = Option<<F as Parser<I>>::Output>, Error = E> |
| 275 | where |
| 276 | F: Parser<I, Error = E>, |
| 277 | { |
| 278 | Cond { |
| 279 | parser: if b { Some(f) } else { None }, |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | /// Parser implementation for [cond] |
| 284 | pub struct Cond<F> { |
| 285 | parser: Option<F>, |
| 286 | } |
| 287 | |
| 288 | impl<I, F> Parser<I> for Cond<F> |
| 289 | where |
| 290 | F: Parser<I>, |
| 291 | { |
| 292 | type Output = Option<<F as Parser<I>>::Output>; |
| 293 | type Error = <F as Parser<I>>::Error; |
| 294 | |
| 295 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 296 | match &mut self.parser { |
| 297 | None => Ok((input, OM::Output::bind(|| None))), |
| 298 | Some(f) => f |
| 299 | .process::<OM>(input) |
| 300 | .map(|(i, o)| (i, OM::Output::map(o, Some))), |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// Tries to apply its parser without consuming the input. |
| 306 | /// |
| 307 | /// ```rust |
| 308 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 309 | /// use nom::combinator::peek; |
| 310 | /// use nom::character::complete::alpha1; |
| 311 | /// # fn main() { |
| 312 | /// |
| 313 | /// let mut parser = peek(alpha1); |
| 314 | /// |
| 315 | /// assert_eq!(parser.parse("abcd;"), Ok(("abcd;", "abcd"))); |
| 316 | /// assert_eq!(parser.parse("123;"), Err(Err::Error(("123;", ErrorKind::Alpha)))); |
| 317 | /// # } |
| 318 | /// ``` |
| 319 | pub fn peek<I: Clone, F>( |
| 320 | parser: F, |
| 321 | ) -> impl Parser<I, Output = <F as Parser<I>>::Output, Error = <F as Parser<I>>::Error> |
| 322 | where |
| 323 | F: Parser<I>, |
| 324 | { |
| 325 | Peek { parser } |
| 326 | } |
| 327 | |
| 328 | /// Parsr implementation for [peek] |
| 329 | pub struct Peek<F> { |
| 330 | parser: F, |
| 331 | } |
| 332 | |
| 333 | impl<I, F> Parser<I> for Peek<F> |
| 334 | where |
| 335 | I: Clone, |
| 336 | F: Parser<I>, |
| 337 | { |
| 338 | type Output = <F as Parser<I>>::Output; |
| 339 | type Error = <F as Parser<I>>::Error; |
| 340 | |
| 341 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 342 | let i = input.clone(); |
| 343 | match self.parser.process::<OM>(input) { |
| 344 | Ok((_, o)) => Ok((i, o)), |
| 345 | Err(e) => Err(e), |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /// returns its input if it is at the end of input data |
| 351 | /// |
| 352 | /// When we're at the end of the data, this combinator |
| 353 | /// will succeed |
| 354 | /// |
| 355 | /// ``` |
| 356 | /// # use std::str; |
| 357 | /// # use nom::{Err, error::ErrorKind, IResult}; |
| 358 | /// # use nom::combinator::eof; |
| 359 | /// |
| 360 | /// # fn main() { |
| 361 | /// let parser = eof; |
| 362 | /// assert_eq!(parser("abc"), Err(Err::Error(("abc", ErrorKind::Eof)))); |
| 363 | /// assert_eq!(parser(""), Ok(("", ""))); |
| 364 | /// # } |
| 365 | /// ``` |
| 366 | pub fn eof<I: Input + Clone, E: ParseError<I>>(input: I) -> IResult<I, I, E> { |
| 367 | if input.input_len() == 0 { |
| 368 | let clone = input.clone(); |
| 369 | Ok((input, clone)) |
| 370 | } else { |
| 371 | Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof))) |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | /// Transforms Incomplete into `Error`. |
| 376 | /// |
| 377 | /// ```rust |
| 378 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 379 | /// use nom::bytes::streaming::take; |
| 380 | /// use nom::combinator::complete; |
| 381 | /// # fn main() { |
| 382 | /// |
| 383 | /// let mut parser = complete(take(5u8)); |
| 384 | /// |
| 385 | /// assert_eq!(parser.parse("abcdefg"), Ok(("fg", "abcde"))); |
| 386 | /// assert_eq!(parser.parse("abcd"), Err(Err::Error(("abcd", ErrorKind::Complete)))); |
| 387 | /// # } |
| 388 | /// ``` |
| 389 | pub fn complete<I: Clone, O, E: ParseError<I>, F>( |
| 390 | parser: F, |
| 391 | ) -> impl Parser<I, Output = O, Error = E> |
| 392 | where |
| 393 | F: Parser<I, Output = O, Error = E>, |
| 394 | { |
| 395 | MakeComplete { parser } |
| 396 | } |
| 397 | |
| 398 | /// Parser implementation for [complete] |
| 399 | pub struct MakeComplete<F> { |
| 400 | parser: F, |
| 401 | } |
| 402 | |
| 403 | impl<I, F> Parser<I> for MakeComplete<F> |
| 404 | where |
| 405 | I: Clone, |
| 406 | F: Parser<I>, |
| 407 | { |
| 408 | type Output = <F as Parser<I>>::Output; |
| 409 | type Error = <F as Parser<I>>::Error; |
| 410 | |
| 411 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 412 | let i = input.clone(); |
| 413 | |
| 414 | match self |
| 415 | .parser |
| 416 | .process::<OutputM<OM::Output, OM::Error, Complete>>(input) |
| 417 | { |
| 418 | Err(Err::Incomplete(_)) => Err(Err::Error(OM::Error::bind(|| { |
| 419 | <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Complete) |
| 420 | }))), |
| 421 | Err(e) => Err(e), |
| 422 | Ok(o) => Ok(o), |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | /// Succeeds if all the input has been consumed by its child parser. |
| 428 | /// |
| 429 | /// ```rust |
| 430 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 431 | /// use nom::combinator::all_consuming; |
| 432 | /// use nom::character::complete::alpha1; |
| 433 | /// # fn main() { |
| 434 | /// |
| 435 | /// let mut parser = all_consuming(alpha1); |
| 436 | /// |
| 437 | /// assert_eq!(parser.parse("abcd"), Ok(("", "abcd"))); |
| 438 | /// assert_eq!(parser.parse("abcd;"),Err(Err::Error((";", ErrorKind::Eof)))); |
| 439 | /// assert_eq!(parser.parse("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha)))); |
| 440 | /// # } |
| 441 | /// ``` |
| 442 | pub fn all_consuming<I, E: ParseError<I>, F>( |
| 443 | parser: F, |
| 444 | ) -> impl Parser<I, Output = <F as Parser<I>>::Output, Error = E> |
| 445 | where |
| 446 | I: Input, |
| 447 | F: Parser<I, Error = E>, |
| 448 | { |
| 449 | AllConsuming { parser } |
| 450 | } |
| 451 | |
| 452 | /// Parser implementation for [all_consuming] |
| 453 | pub struct AllConsuming<F> { |
| 454 | parser: F, |
| 455 | } |
| 456 | |
| 457 | impl<I, F> Parser<I> for AllConsuming<F> |
| 458 | where |
| 459 | I: Input, |
| 460 | F: Parser<I>, |
| 461 | { |
| 462 | type Output = <F as Parser<I>>::Output; |
| 463 | type Error = <F as Parser<I>>::Error; |
| 464 | |
| 465 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 466 | let (input, res) = self.parser.process::<OM>(input)?; |
| 467 | if input.input_len() == 0 { |
| 468 | Ok((input, res)) |
| 469 | } else { |
| 470 | Err(Err::Error(OM::Error::bind(|| { |
| 471 | <F as Parser<I>>::Error::from_error_kind(input, ErrorKind::Eof) |
| 472 | }))) |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | /// Returns the result of the child parser if it satisfies a verification function. |
| 478 | /// |
| 479 | /// The verification function takes as argument a reference to the output of the |
| 480 | /// parser. |
| 481 | /// |
| 482 | /// ```rust |
| 483 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 484 | /// use nom::combinator::verify; |
| 485 | /// use nom::character::complete::alpha1; |
| 486 | /// # fn main() { |
| 487 | /// |
| 488 | /// let mut parser = verify(alpha1, |s: &str| s.len() == 4); |
| 489 | /// |
| 490 | /// assert_eq!(parser.parse("abcd"), Ok(("", "abcd"))); |
| 491 | /// assert_eq!(parser.parse("abcde"), Err(Err::Error(("abcde", ErrorKind::Verify)))); |
| 492 | /// assert_eq!(parser.parse("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha)))); |
| 493 | /// # } |
| 494 | /// ``` |
| 495 | pub fn verify<I: Clone, O2, E: ParseError<I>, F, G>( |
| 496 | first: F, |
| 497 | second: G, |
| 498 | ) -> impl Parser<I, Output = <F as Parser<I>>::Output, Error = E> |
| 499 | where |
| 500 | F: Parser<I, Error = E>, |
| 501 | G: Fn(&O2) -> bool, |
| 502 | <F as Parser<I>>::Output: Borrow<O2>, |
| 503 | O2: ?Sized, |
| 504 | { |
| 505 | Verify { |
| 506 | first, |
| 507 | second, |
| 508 | o2: PhantomData, |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | /// Parser iplementation for verify |
| 513 | pub struct Verify<F, G, O2: ?Sized> { |
| 514 | first: F, |
| 515 | second: G, |
| 516 | o2: PhantomData<O2>, |
| 517 | } |
| 518 | |
| 519 | impl<I, F: Parser<I>, G, O2> Parser<I> for Verify<F, G, O2> |
| 520 | where |
| 521 | I: Clone, |
| 522 | G: Fn(&O2) -> bool, |
| 523 | <F as Parser<I>>::Output: Borrow<O2>, |
| 524 | O2: ?Sized, |
| 525 | { |
| 526 | type Output = <F as Parser<I>>::Output; |
| 527 | |
| 528 | type Error = <F as Parser<I>>::Error; |
| 529 | |
| 530 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 531 | let (i, o) = self |
| 532 | .first |
| 533 | .process::<OutputM<Emit, OM::Error, OM::Incomplete>>(input.clone())?; |
| 534 | |
| 535 | if (self.second)(o.borrow()) { |
| 536 | Ok((i, OM::Output::bind(|| o))) |
| 537 | } else { |
| 538 | Err(Err::Error(OM::Error::bind(move || { |
| 539 | let e: ErrorKind = ErrorKind::Verify; |
| 540 | <F as Parser<I>>::Error::from_error_kind(input, e) |
| 541 | }))) |
| 542 | } |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | /// Returns the provided value if the child parser succeeds. |
| 547 | /// |
| 548 | /// ```rust |
| 549 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 550 | /// use nom::combinator::value; |
| 551 | /// use nom::character::complete::alpha1; |
| 552 | /// # fn main() { |
| 553 | /// |
| 554 | /// let mut parser = value(1234, alpha1); |
| 555 | /// |
| 556 | /// assert_eq!(parser.parse("abcd"), Ok(("", 1234))); |
| 557 | /// assert_eq!(parser.parse("123abcd;"), Err(Err::Error(("123abcd;", ErrorKind::Alpha)))); |
| 558 | /// # } |
| 559 | /// ``` |
| 560 | pub fn value<I, O1: Clone, E: ParseError<I>, F>( |
| 561 | val: O1, |
| 562 | parser: F, |
| 563 | ) -> impl Parser<I, Output = O1, Error = E> |
| 564 | where |
| 565 | F: Parser<I, Error = E>, |
| 566 | { |
| 567 | parser.map(move |_| val.clone()) |
| 568 | } |
| 569 | |
| 570 | /// Succeeds if the child parser returns an error. |
| 571 | /// |
| 572 | /// ```rust |
| 573 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 574 | /// use nom::combinator::not; |
| 575 | /// use nom::character::complete::alpha1; |
| 576 | /// # fn main() { |
| 577 | /// |
| 578 | /// let mut parser = not(alpha1); |
| 579 | /// |
| 580 | /// assert_eq!(parser.parse("123"), Ok(("123", ()))); |
| 581 | /// assert_eq!(parser.parse("abcd"), Err(Err::Error(("abcd", ErrorKind::Not)))); |
| 582 | /// # } |
| 583 | /// ``` |
| 584 | pub fn not<I: Clone, E: ParseError<I>, F>(parser: F) -> impl Parser<I, Output = (), Error = E> |
| 585 | where |
| 586 | F: Parser<I, Error = E>, |
| 587 | { |
| 588 | Not { parser } |
| 589 | } |
| 590 | |
| 591 | /// Parser implementation for [not] |
| 592 | pub struct Not<F> { |
| 593 | parser: F, |
| 594 | } |
| 595 | |
| 596 | impl<I, F> Parser<I> for Not<F> |
| 597 | where |
| 598 | I: Clone, |
| 599 | F: Parser<I>, |
| 600 | { |
| 601 | type Output = (); |
| 602 | type Error = <F as Parser<I>>::Error; |
| 603 | |
| 604 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 605 | let i = input.clone(); |
| 606 | match self.parser.process::<OM>(input) { |
| 607 | Ok(_) => Err(Err::Error(OM::Error::bind(|| { |
| 608 | <F as Parser<I>>::Error::from_error_kind(i, ErrorKind::Not) |
| 609 | }))), |
| 610 | Err(Err::Error(_)) => Ok((i, OM::Output::bind(|| ()))), |
| 611 | Err(e) => Err(e), |
| 612 | } |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | /// If the child parser was successful, return the consumed input as produced value. |
| 617 | /// |
| 618 | /// ```rust |
| 619 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 620 | /// use nom::combinator::recognize; |
| 621 | /// use nom::character::complete::{char, alpha1}; |
| 622 | /// use nom::sequence::separated_pair; |
| 623 | /// # fn main() { |
| 624 | /// |
| 625 | /// let mut parser = recognize(separated_pair(alpha1, char(','), alpha1)); |
| 626 | /// |
| 627 | /// assert_eq!(parser.parse("abcd,efgh"), Ok(("", "abcd,efgh"))); |
| 628 | /// assert_eq!(parser.parse("abcd;"),Err(Err::Error((";", ErrorKind::Char)))); |
| 629 | /// # } |
| 630 | /// ``` |
| 631 | pub fn recognize<I: Clone + Offset + Input, E: ParseError<I>, F>( |
| 632 | parser: F, |
| 633 | ) -> impl Parser<I, Output = I, Error = E> |
| 634 | where |
| 635 | F: Parser<I, Error = E>, |
| 636 | { |
| 637 | Recognize { parser } |
| 638 | } |
| 639 | |
| 640 | /// Parser implementation for [recognize] |
| 641 | pub struct Recognize<F> { |
| 642 | parser: F, |
| 643 | } |
| 644 | |
| 645 | impl<I, F> Parser<I> for Recognize<F> |
| 646 | where |
| 647 | I: Clone + Offset + Input, |
| 648 | F: Parser<I>, |
| 649 | { |
| 650 | type Output = I; |
| 651 | type Error = <F as Parser<I>>::Error; |
| 652 | |
| 653 | #[inline(always)] |
| 654 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 655 | let i = input.clone(); |
| 656 | match self |
| 657 | .parser |
| 658 | .process::<OutputM<Check, OM::Error, OM::Incomplete>>(i) |
| 659 | { |
| 660 | Ok((i, _)) => { |
| 661 | let index = input.offset(&i); |
| 662 | Ok((i, OM::Output::bind(|| input.take(index)))) |
| 663 | } |
| 664 | Err(e) => Err(e), |
| 665 | } |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | /// if the child parser was successful, return the consumed input with the output |
| 670 | /// as a tuple. Functions similarly to [recognize](fn.recognize.html) except it |
| 671 | /// returns the parser output as well. |
| 672 | /// |
| 673 | /// This can be useful especially in cases where the output is not the same type |
| 674 | /// as the input, or the input is a user defined type. |
| 675 | /// |
| 676 | /// Returned tuple is of the format `(consumed input, produced output)`. |
| 677 | /// |
| 678 | /// ```rust |
| 679 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 680 | /// use nom::combinator::{consumed, value, recognize, map}; |
| 681 | /// use nom::character::complete::{char, alpha1}; |
| 682 | /// use nom::bytes::complete::tag; |
| 683 | /// use nom::sequence::separated_pair; |
| 684 | /// |
| 685 | /// fn inner_parser(input: &str) -> IResult<&str, bool> { |
| 686 | /// value(true, tag("1234")).parse(input) |
| 687 | /// } |
| 688 | /// |
| 689 | /// # fn main() { |
| 690 | /// |
| 691 | /// let mut consumed_parser = consumed(value(true, separated_pair(alpha1, char(','), alpha1))); |
| 692 | /// |
| 693 | /// assert_eq!(consumed_parser.parse("abcd,efgh1"), Ok(("1", ("abcd,efgh", true)))); |
| 694 | /// assert_eq!(consumed_parser.parse("abcd;"),Err(Err::Error((";", ErrorKind::Char)))); |
| 695 | /// |
| 696 | /// |
| 697 | /// // the first output (representing the consumed input) |
| 698 | /// // should be the same as that of the `recognize` parser. |
| 699 | /// let mut recognize_parser = recognize(inner_parser); |
| 700 | /// let mut consumed_parser = map(consumed(inner_parser), |(consumed, output)| consumed); |
| 701 | /// |
| 702 | /// assert_eq!(recognize_parser.parse("1234"), consumed_parser.parse("1234")); |
| 703 | /// assert_eq!(recognize_parser.parse("abcd"), consumed_parser.parse("abcd")); |
| 704 | /// # } |
| 705 | /// ``` |
| 706 | pub fn consumed<I, F, E>( |
| 707 | parser: F, |
| 708 | ) -> impl Parser<I, Output = (I, <F as Parser<I>>::Output), Error = E> |
| 709 | where |
| 710 | I: Clone + Offset + Input, |
| 711 | E: ParseError<I>, |
| 712 | F: Parser<I, Error = E>, |
| 713 | { |
| 714 | Consumed { parser } |
| 715 | } |
| 716 | |
| 717 | /// Parser implementation for [consumed] |
| 718 | pub struct Consumed<F> { |
| 719 | parser: F, |
| 720 | } |
| 721 | |
| 722 | impl<I, F> Parser<I> for Consumed<F> |
| 723 | where |
| 724 | I: Clone + Offset + Input, |
| 725 | F: Parser<I>, |
| 726 | { |
| 727 | type Output = (I, <F as Parser<I>>::Output); |
| 728 | type Error = <F as Parser<I>>::Error; |
| 729 | |
| 730 | #[inline(always)] |
| 731 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 732 | let i = input.clone(); |
| 733 | match self.parser.process::<OM>(i) { |
| 734 | Ok((remaining, result)) => { |
| 735 | let index = input.offset(&remaining); |
| 736 | |
| 737 | Ok(( |
| 738 | remaining, |
| 739 | OM::Output::map(result, |res| { |
| 740 | let consumed = input.take(index); |
| 741 | (consumed, res) |
| 742 | }), |
| 743 | )) |
| 744 | } |
| 745 | Err(e) => Err(e), |
| 746 | } |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | /// Transforms an [`Err::Error`] (recoverable) to [`Err::Failure`] (unrecoverable) |
| 751 | /// |
| 752 | /// This commits the parse result, preventing alternative branch paths like with |
| 753 | /// [`nom::branch::alt`][crate::branch::alt]. |
| 754 | /// |
| 755 | /// # Example |
| 756 | /// |
| 757 | /// Without `cut`: |
| 758 | /// ```rust |
| 759 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 760 | /// # use nom::character::complete::{one_of, digit1}; |
| 761 | /// # use nom::combinator::rest; |
| 762 | /// # use nom::branch::alt; |
| 763 | /// # use nom::sequence::preceded; |
| 764 | /// # fn main() { |
| 765 | /// |
| 766 | /// fn parser(input: &str) -> IResult<&str, &str> { |
| 767 | /// alt(( |
| 768 | /// preceded(one_of("+-"), digit1), |
| 769 | /// rest |
| 770 | /// )).parse(input) |
| 771 | /// } |
| 772 | /// |
| 773 | /// assert_eq!(parser("+10 ab"), Ok((" ab", "10"))); |
| 774 | /// assert_eq!(parser("ab"), Ok(("", "ab"))); |
| 775 | /// assert_eq!(parser("+"), Ok(("", "+"))); |
| 776 | /// # } |
| 777 | /// ``` |
| 778 | /// |
| 779 | /// With `cut`: |
| 780 | /// ```rust |
| 781 | /// # use nom::{Err,error::ErrorKind, IResult, Parser, error::Error}; |
| 782 | /// # use nom::character::complete::{one_of, digit1}; |
| 783 | /// # use nom::combinator::rest; |
| 784 | /// # use nom::branch::alt; |
| 785 | /// # use nom::sequence::preceded; |
| 786 | /// use nom::combinator::cut; |
| 787 | /// # fn main() { |
| 788 | /// |
| 789 | /// fn parser(input: &str) -> IResult<&str, &str> { |
| 790 | /// alt(( |
| 791 | /// preceded(one_of("+-"), cut(digit1)), |
| 792 | /// rest |
| 793 | /// )).parse(input) |
| 794 | /// } |
| 795 | /// |
| 796 | /// assert_eq!(parser("+10 ab"), Ok((" ab", "10"))); |
| 797 | /// assert_eq!(parser("ab"), Ok(("", "ab"))); |
| 798 | /// assert_eq!(parser("+"), Err(Err::Failure(Error { input: "", code: ErrorKind::Digit }))); |
| 799 | /// # } |
| 800 | /// ``` |
| 801 | pub fn cut<I, E: ParseError<I>, F>( |
| 802 | parser: F, |
| 803 | ) -> impl Parser<I, Output = <F as Parser<I>>::Output, Error = E> |
| 804 | where |
| 805 | F: Parser<I, Error = E>, |
| 806 | { |
| 807 | Cut { parser } |
| 808 | } |
| 809 | |
| 810 | /// Parser implementation for [cut] |
| 811 | pub struct Cut<F> { |
| 812 | parser: F, |
| 813 | } |
| 814 | |
| 815 | impl<I, F> Parser<I> for Cut<F> |
| 816 | where |
| 817 | F: Parser<I>, |
| 818 | { |
| 819 | type Output = <F as Parser<I>>::Output; |
| 820 | |
| 821 | type Error = <F as Parser<I>>::Error; |
| 822 | |
| 823 | #[inline(always)] |
| 824 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 825 | match self |
| 826 | .parser |
| 827 | .process::<OutputM<OM::Output, Emit, OM::Incomplete>>(input) |
| 828 | { |
| 829 | Err(Err::Error(e)) => Err(Err::Failure(e)), |
| 830 | Err(Err::Failure(e)) => Err(Err::Failure(e)), |
| 831 | Err(Err::Incomplete(i)) => Err(Err::Incomplete(i)), |
| 832 | Ok((i, o)) => Ok((i, o)), |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | /// automatically converts the child parser's result to another type |
| 838 | /// |
| 839 | /// it will be able to convert the output value and the error value |
| 840 | /// as long as the `Into` implementations are available |
| 841 | /// |
| 842 | /// ```rust |
| 843 | /// # use nom::{IResult, Parser}; |
| 844 | /// use nom::combinator::into; |
| 845 | /// use nom::character::complete::alpha1; |
| 846 | /// # fn main() { |
| 847 | /// |
| 848 | /// fn parser1(i: &str) -> IResult<&str, &str> { |
| 849 | /// alpha1(i) |
| 850 | /// } |
| 851 | /// |
| 852 | /// let mut parser2 = into(parser1); |
| 853 | /// |
| 854 | /// // the parser converts the &str output of the child parser into a Vec<u8> |
| 855 | /// let bytes: IResult<&str, Vec<u8>> = parser2.parse("abcd"); |
| 856 | /// assert_eq!(bytes, Ok(("", vec![97, 98, 99, 100]))); |
| 857 | /// # } |
| 858 | /// ``` |
| 859 | pub fn into<I, O1, O2, E1, E2, F>(parser: F) -> impl Parser<I, Output = O2, Error = E2> |
| 860 | where |
| 861 | O2: From<O1>, |
| 862 | E2: From<E1>, |
| 863 | E1: ParseError<I>, |
| 864 | E2: ParseError<I>, |
| 865 | F: Parser<I, Output = O1, Error = E1>, |
| 866 | { |
| 867 | parser.into::<O2, E2>() |
| 868 | } |
| 869 | |
| 870 | /// Creates an iterator from input data and a parser. |
| 871 | /// |
| 872 | /// Call the iterator's [ParserIterator::finish] method to get the remaining input if successful, |
| 873 | /// or the error value if we encountered an error. |
| 874 | /// |
| 875 | /// On [`Err::Error`], iteration will stop. To instead chain an error up, see [`cut`]. |
| 876 | /// |
| 877 | /// ```rust |
| 878 | /// use nom::{combinator::iterator, IResult, bytes::complete::tag, character::complete::alpha1, sequence::terminated}; |
| 879 | /// use std::collections::HashMap; |
| 880 | /// |
| 881 | /// let data = "abc|defg|hijkl|mnopqr|123"; |
| 882 | /// let mut it = iterator(data, terminated(alpha1, tag("|"))); |
| 883 | /// |
| 884 | /// let parsed = it.by_ref().map(|v| (v, v.len())).collect::<HashMap<_,_>>(); |
| 885 | /// let res: IResult<_,_> = it.finish(); |
| 886 | /// |
| 887 | /// assert_eq!(parsed, [("abc", 3usize), ("defg", 4), ("hijkl", 5), ("mnopqr", 6)].iter().cloned().collect()); |
| 888 | /// assert_eq!(res, Ok(("123", ()))); |
| 889 | /// ``` |
| 890 | pub fn iterator<Input, Error, F>(input: Input, f: F) -> ParserIterator<Input, Error, F> |
| 891 | where |
| 892 | F: Parser<Input>, |
| 893 | Error: ParseError<Input>, |
| 894 | { |
| 895 | ParserIterator { |
| 896 | iterator: f, |
| 897 | input, |
| 898 | state: Some(State::Running), |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | /// Main structure associated to the [iterator] function. |
| 903 | pub struct ParserIterator<I, E, F> { |
| 904 | iterator: F, |
| 905 | input: I, |
| 906 | state: Option<State<E>>, |
| 907 | } |
| 908 | |
| 909 | impl<I: Clone, E, F> ParserIterator<I, E, F> { |
| 910 | /// Returns the remaining input if parsing was successful, or the error if we encountered an error. |
| 911 | pub fn finish(mut self) -> IResult<I, (), E> { |
| 912 | match self.state.take().unwrap() { |
| 913 | State::Running | State::Done => Ok((self.input, ())), |
| 914 | State::Failure(e) => Err(Err::Failure(e)), |
| 915 | State::Incomplete(i) => Err(Err::Incomplete(i)), |
| 916 | } |
| 917 | } |
| 918 | } |
| 919 | |
| 920 | impl<Input, Output, Error, F> core::iter::Iterator for ParserIterator<Input, Error, F> |
| 921 | where |
| 922 | F: Parser<Input, Output = Output, Error = Error>, |
| 923 | Input: Clone, |
| 924 | { |
| 925 | type Item = Output; |
| 926 | |
| 927 | fn next(&mut self) -> Option<Self::Item> { |
| 928 | if let State::Running = self.state.take().unwrap() { |
| 929 | let input = self.input.clone(); |
| 930 | |
| 931 | match (self.iterator).parse(input) { |
| 932 | Ok((i, o)) => { |
| 933 | self.input = i; |
| 934 | self.state = Some(State::Running); |
| 935 | Some(o) |
| 936 | } |
| 937 | Err(Err::Error(_)) => { |
| 938 | self.state = Some(State::Done); |
| 939 | None |
| 940 | } |
| 941 | Err(Err::Failure(e)) => { |
| 942 | self.state = Some(State::Failure(e)); |
| 943 | None |
| 944 | } |
| 945 | Err(Err::Incomplete(i)) => { |
| 946 | self.state = Some(State::Incomplete(i)); |
| 947 | None |
| 948 | } |
| 949 | } |
| 950 | } else { |
| 951 | None |
| 952 | } |
| 953 | } |
| 954 | } |
| 955 | |
| 956 | enum State<E> { |
| 957 | Running, |
| 958 | Done, |
| 959 | Failure(E), |
| 960 | Incomplete(Needed), |
| 961 | } |
| 962 | |
| 963 | /// a parser which always succeeds with given value without consuming any input. |
| 964 | /// |
| 965 | /// It can be used for example as the last alternative in `alt` to |
| 966 | /// specify the default case. |
| 967 | /// |
| 968 | /// ```rust |
| 969 | /// # use nom::{Err,error::ErrorKind, IResult, Parser}; |
| 970 | /// use nom::branch::alt; |
| 971 | /// use nom::combinator::{success, value}; |
| 972 | /// use nom::character::complete::char; |
| 973 | /// # fn main() { |
| 974 | /// |
| 975 | /// let mut parser = success::<_,_,(_,ErrorKind)>(10); |
| 976 | /// assert_eq!(parser.parse("xyz"), Ok(("xyz", 10))); |
| 977 | /// |
| 978 | /// let mut sign = alt((value(-1, char('-')), value(1, char('+')), success::<_,_,(_,ErrorKind)>(1))); |
| 979 | /// assert_eq!(sign.parse("+10"), Ok(("10", 1))); |
| 980 | /// assert_eq!(sign.parse("-10"), Ok(("10", -1))); |
| 981 | /// assert_eq!(sign.parse("10"), Ok(("10", 1))); |
| 982 | /// # } |
| 983 | /// ``` |
| 984 | pub fn success<I, O: Clone, E: ParseError<I>>(val: O) -> impl Parser<I, Output = O, Error = E> { |
| 985 | Success { |
| 986 | val, |
| 987 | e: PhantomData, |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | /// Parser implementation for [success] |
| 992 | pub struct Success<O: Clone, E> { |
| 993 | val: O, |
| 994 | e: PhantomData<E>, |
| 995 | } |
| 996 | |
| 997 | impl<I, O, E> Parser<I> for Success<O, E> |
| 998 | where |
| 999 | O: Clone, |
| 1000 | E: ParseError<I>, |
| 1001 | { |
| 1002 | type Output = O; |
| 1003 | type Error = E; |
| 1004 | |
| 1005 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 1006 | Ok((input, OM::Output::bind(|| self.val.clone()))) |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | /// A parser which always fails. |
| 1011 | /// |
| 1012 | /// ```rust |
| 1013 | /// # use nom::{Err, error::ErrorKind, IResult, Parser}; |
| 1014 | /// use nom::combinator::fail; |
| 1015 | /// |
| 1016 | /// let s = "string"; |
| 1017 | /// assert_eq!(fail::<_, &str, _>().parse(s), Err(Err::Error((s, ErrorKind::Fail)))); |
| 1018 | /// ``` |
| 1019 | pub fn fail<I, O, E: ParseError<I>>() -> impl Parser<I, Output = O, Error = E> { |
| 1020 | Fail { |
| 1021 | o: PhantomData, |
| 1022 | e: PhantomData, |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | /// Parser implementation for [fail] |
| 1027 | pub struct Fail<O, E> { |
| 1028 | o: PhantomData<O>, |
| 1029 | e: PhantomData<E>, |
| 1030 | } |
| 1031 | |
| 1032 | impl<I, O, E> Parser<I> for Fail<O, E> |
| 1033 | where |
| 1034 | E: ParseError<I>, |
| 1035 | { |
| 1036 | type Output = O; |
| 1037 | type Error = E; |
| 1038 | |
| 1039 | fn process<OM: OutputMode>(&mut self, input: I) -> PResult<OM, I, Self::Output, Self::Error> { |
| 1040 | Err(Err::Error(OM::Error::bind(|| { |
| 1041 | E::from_error_kind(input, ErrorKind::Fail) |
| 1042 | }))) |
| 1043 | } |
| 1044 | } |