1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
use crate::result::{Error, Res};
use std::marker::PhantomData;
use std::ops::{RangeFrom, RangeInclusive, RangeToInclusive};
/// A trait for parsers
///
/// A parser takes in input and either outputs a value or reports an error.
///
/// # Implementing the trait
///
/// 1. Decide what types to provide for the input, output and error. For example a type that
/// implements `Parser<&str, u8, String>` can accept `&str` as input to `try_parse()`, and is
/// expected to output `u8`s. If an error occurs, it is reported as
/// [`Error\<String\>`](crate::result::Error).
/// 2. Implement `try_parse()`
/// 3. Use combinators.
/// 4. ??profit??
///
/// The `Parser` trait is already implemented for a couple primitive types. Check out the impl
/// sections below for more concrete examples
pub trait Parser<In, Out, E> {
/// Recognizes a value from the input and returns the result
///
/// Reports an error if the input could not be matched.
fn try_parse(&self, input: In) -> Res<In, Out, E>;
/// Returns a parser that maps a `Parser<In, Out, E>` to `Parser<In, Mapped, E>` by applying a
/// function to the result of the parser if it succeeded.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "a";
///
/// let (value, _) = "a".map(str::to_ascii_uppercase).try_parse(msg).unwrap();
///
/// assert_eq!(value, "A");
/// ```
fn map<F, Mapped>(self, f: F) -> Map<Self, F, Out>
where
Self: Sized,
F: Fn(Out) -> Mapped,
{
Map {
parser: self,
f,
_param: PhantomData,
}
}
/// Returns a parser that maps a `Parser<In, Out, E>` to `Parser<In, Out, Mapped>` by applying
/// a function to the error reported by the parser if it failed.
///
/// ```
/// use parser_compose::{Error, Parser};
///
/// enum MyError { Fail }
///
/// let msg = "a";
///
/// let result = "b".map_err(|_| Error::Custom(MyError::Fail)).try_parse(msg);
///
/// assert!(result.is_err());
/// assert!(matches!(result, Err(Error::Custom(MyError::Fail))));
///
/// ```
fn map_err<F, M>(self, f: F) -> MapErr<Self, F, E>
where
Self: Sized,
F: Fn(Error<E>) -> Error<M>,
{
MapErr {
parser: self,
f,
_param: PhantomData,
}
}
/// Returns a parser that succeeds if `self` does. Otherwise, it's outcome is that of `next`.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "a";
///
/// let (value, _) = "1".or("a").try_parse(msg).unwrap();
///
/// assert_eq!(value, "a");
/// ```
fn or<P>(self, next: P) -> Or<Self, P>
where
Self: Sized,
{
Or {
parser1: self,
parser2: next,
}
}
/// Returns a new parser that succeeds if the predicate returns true. The predicate is given the
/// extracted value of the current parser as an argument
///
/// ```
/// use parser_compose::{any_str,Parser};
///
/// let msg = "boo";
///
/// let (value, _) = any_str.when(|s| s == "b").try_parse(msg).unwrap();
///
/// assert_eq!(value, "b");
/// ```
fn when<F>(self, pred: F) -> Predicate<Self, F>
where
Self: Sized,
F: Fn(Out) -> bool,
{
Predicate {
parser: self,
predicate: pred,
}
}
/// Returns a parser that suceeds if it is able to repeat `count` times.
///
/// `count` can be:
///
/// - A single `usize` (e.g. `8`): The parser will try to match at least 8 times and return a `Vec`
/// of length 8 if it succeeds
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "AAAA";
///
/// let (value, rest) = "A".repeated(3).try_parse(msg).unwrap();
///
/// assert_eq!(value, vec!["A", "A", "A"]);
/// assert_eq!(rest, "A");
/// ```
///
/// - A range bounded inclusively from below (e.g. `3..`): The parser will try to match at
/// least 3 times, but possibly more. If it succeeds, the returned `Vec` is be guaranteed to
/// have a value greater than 3.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "AAAA";
/// let (value, rest) = "A".repeated(2..).try_parse(msg).unwrap();
///
/// assert_eq!(value, vec!["A", "A", "A", "A"]);
/// assert_eq!(rest, "");
/// ```
///
/// - A range bounded inclusively from above (e.g. `..=4`): The parser will try to match at
/// most 4 times, but possibly less (including zero times!). If it succeeds, the returned `Vec`
/// will have at most 4 elements
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "AA";
/// let (value, rest) = "A".repeated(..=4).try_parse(msg).unwrap();
///
/// assert_eq!(value, vec!["A", "A"]);
/// assert_eq!(rest, "");
/// ```
///
/// - A range bounded inclusively from above and below (e.g. `3..=5`): The parser will try to
/// match at least 3 times and at most 5 times. If it succeeds, the returned `Vec` will have a
/// length between 3 and 5
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "AAAA";
/// let (value, rest) = "A".repeated(2..=3).try_parse(msg).unwrap();
///
/// assert_eq!(value, vec!["A", "A", "A"]);
/// assert_eq!(rest, "A");
/// ```
fn repeated<R: RepetitionArgument>(self, count: R) -> Repeat<Self, R>
where
Self: Sized,
{
Repeat {
parser: self,
count,
}
}
/// Returns a parser always succeeds but wraps the output in an `Option<Out>`. If the original
/// parser would have failed, the parser outputs a `None`.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "a";
///
/// let ((b, a), _) = ("b".optional(), "a").try_parse(msg).unwrap();
///
/// assert_eq!(b, None);
/// assert_eq!(a, "a");
/// ```
fn optional(self) -> Optional<Self>
where
Self: Sized,
{
Optional { inner: self }
}
/// Returns a parser that succeeds or fails as normal, but never consumes any input
/// regardless of the outcome. This can be used to look ahead.
///
/// It corresponds to the "and-predicate" operator in Parsing Expression Grammars.
///
/// ```
/// use parser_compose::Parser;
///
/// // Recognize the sequence "a" followed by "b", but only if it is followed by a "c"
/// let a_then_b = ("a", "b", "c".peeked());
///
/// let (value, rest) = a_then_b.try_parse("abc").unwrap();
/// // note: the value gets recognized and returned, but it does not consume it.
/// assert_eq!(value, ("a", "b", "c"));
/// assert_eq!(rest, "c");
///
/// let result = a_then_b.try_parse("abb");
/// assert!(result.is_err());
/// ```
fn peeked(self) -> Peeked<Self>
where
Self: Sized,
{
Peeked { inner: self }
}
/// Reverse of [`peeked()`](crate::Parser::peeked). Returns a parse that succeeds if it was not
/// able to recognize the input and fails if it was able to.
///
/// It corresponds to the "not-predicate" operator in Parsing Expression Grammars.
///
/// ```
/// use parser_compose::Parser;
///
/// // This parser matches "foo", but only if it is not followed by "bar"
/// let parser = ("foo", "bar".not_peeked());
///
/// let msg = "foobar";
///
/// let result = parser.try_parse(msg);
///
/// assert!(result.is_err());
///
/// let (value, rest) = parser.try_parse("foobaz").unwrap();
///
/// assert_eq!(value, ("foo", ()));
/// assert_eq!(rest, "baz");
/// ```
fn not_peeked(self) -> NotPeeked<Self, Out>
where
Self: Sized,
{
NotPeeked { inner: self, _phantom: PhantomData }
}
/// Returns a parser that is similar to [`map()`](crate::Parser::map) in its behavior, except
/// that the provided closure may fail, which affects the outcome of the parser.
///
/// ```
/// use std::str::from_utf8;
/// use parser_compose::{Error,Parser};
///
/// let msg = [98].as_slice();
///
/// let (value, _) = [98].and_then(|b| {
/// // converting to utf8 can fail
/// from_utf8(b).map_err(|_| Error::Mismatch)
/// }).try_parse(msg).unwrap();
///
/// assert_eq!("b", value);
/// ```
fn and_then<F, U>(self, f: F) -> AndThen<Self, F, Out>
where
Self: Sized,
F: Fn(Out) -> Result<U, Error<E>>,
{
AndThen {
inner: self,
f,
phantom: PhantomData,
}
}
}
/// The [`Parser`](crate::Parser) trait is automatically implemented for any function with
/// the following signature:
///
/// `Fn(In) -> parser_compose::Res<In, Out, Err>`
///
/// See the trait documentation for more info about the type parameters.
///
/// Let's say you have a `VecDeque<String>`that you want to parse. No methods in this crate
/// explicitly take a `VecDeque<String>`, but that is not a problem. All the combinators are
/// generic over input, output and errors. So you only need to implement one parser:
/// ```
/// use parser_compose::{Parser, Error, Res} ;
/// use std::collections::vec_deque::VecDeque;
///
/// // A parser that matches any string at the start of the input.
/// fn any_string(mut input: VecDeque<String>) -> Res<VecDeque<String>, String, ()> {
/// let first = input.pop_front().ok_or(Error::Mismatch)?;
/// Ok((first, input))
/// }
///
/// let msg = VecDeque::from([
/// String::from("Hello"),
/// String::from("Hello"),
/// String::from("World"),
/// ]);
///
/// // The function can be used with combinators
/// let parse_hellos = any_string.when(|s| s == "Hello").repeated(2);
/// let parse_world = any_string.when(|s| s == "World");
///
/// let ((hellos, world), rest) = (parse_hellos, parse_world).try_parse(msg).unwrap();
///
/// assert_eq!(hellos, vec!["Hello", "Hello"]);
/// assert_eq!(world, "World");
/// assert_eq!(rest, VecDeque::<String>::new());
///
/// ```
impl<In, Out, E, F> Parser<In, Out, E> for F
where
F: Fn(In) -> Res<In, Out, E>,
{
fn try_parse(&self, input: In) -> Res<In, Out, E> {
(self)(input)
}
}
/// A slice is treated as a parser that tries to match itself at the start of some longer slice
///
/// The [`Parser`](crate::Parser) trait is implemented for all slices, which all
/// `&[T]` will have the `try_parse()` method for all `T`.
///
/// Calling it will try to do a prefix match of the input with the slice used as the pattern.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = &['H', 'E', 'L', 'L', 'O'][..];
///
/// let (res, rest) = ['H', 'E'].as_slice().try_parse(msg).unwrap();
///
///
/// assert_eq!(res, &['H', 'E'][..]);
/// assert_eq!(rest, &['L', 'L', 'O'][..]);
/// ```
impl<'pat, 'input, T> Parser<&'input [T], &'pat [T], ()> for &'pat [T]
where
T: PartialEq,
{
fn try_parse(&self, input: &'input [T]) -> Res<&'input [T], &'pat [T], ()> {
match input.starts_with(self) {
true => Ok((self, &input[self.len()..])),
false => Err(Error::Mismatch),
}
}
}
/// The [`Parser`](crate::Parser) trait is implemented for string slices, which means all
/// `&str`s will have the `try_parse()` method.
///
/// Calling it will try to do a prefix match of the input with the `&str` used as the pattern.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "HELLO";
///
/// let (res, rest) = "HE".try_parse(msg).unwrap();
///
/// assert_eq!(res, "HE");
/// assert_eq!(rest, "LLO");
/// ```
impl<'input, 'pat> Parser<&'input str, &'pat str, ()> for &'pat str {
fn try_parse(&self, input: &'input str) -> Res<&'input str, &'pat str, ()> {
match input.starts_with(self) {
true => Ok((self, &input[self.len()..])),
false => Err(Error::Mismatch),
}
}
}
/// A parser that recognizes the first unicode scalar value at the start of a string slice.
///
/// A unicode scalar value is not always what you might consider a
/// "character". This function will output the first thing that rust considers a [`char`](char).
///
/// # Errors
///
/// An error is reported if the string slice is empty
///
/// ```
/// use parser_compose::{Parser, any_str};
///
/// let msg = "👻Boo";
///
/// let (value, rest) = any_str(msg).unwrap();
///
/// assert_eq!(value, "👻");
/// ```
pub fn any_str(input: &str) -> Res<&str, &str, ()> {
let mut iter = input.char_indices();
let (start_idx, _) = iter.next().ok_or(Error::Mismatch)?;
// If there was just one char in the &str, this next call would return `None`.
let (end_idx, _) = iter.next().unwrap_or((input.len(), ' '));
Ok((&input[start_idx..end_idx], &input[end_idx..]))
}
/// Returns a parser that recognizes the first byte in a string slice if its value is in the
/// specified range
///
/// The range must be bounded on both ends. Only inclusive ranges are allowed.
///
/// Note: that the first byte in a string slice might not be valid unicode. Only use this if the
/// thing you are parsing is limited to the ASCII character set.
///
/// ```
/// use parser_compose::{Parser, ascii_str};
///
/// let msg = "a1";
///
/// let alphabetic = ascii_str(97..=122);
/// let (value, rest) = alphabetic.try_parse(msg).unwrap();
///
/// assert_eq!(value, "a");
/// assert_eq!(rest, "1");
///
/// let result = alphabetic.try_parse(rest);
/// assert!(result.is_err());
///
/// ```
pub fn ascii_str(range: RangeInclusive<u8>) -> AsciiStr {
AsciiStr { range }
}
/// A parser that recognizes the first byte in a byte slice.
///
/// # Errors
///
/// An error is reported if the byte slice is empty
///
/// ```
/// use parser_compose::{Parser, any_byte};
///
/// let msg = &[254, 1, 2][..];
///
/// let (value, rest) = any_byte(msg).unwrap();
///
/// assert_eq!(value, [254]);
/// ```
pub fn any_byte(input: &[u8]) -> Res<&[u8], &[u8], ()> {
if input.is_empty() {
Err(Error::Mismatch)
} else {
Ok((&input[0..1], &input[1..]))
}
}
/// Returns a parser that recognizes the first byte in a byte slice if its value is in the
/// specified range
///
/// The range must be bounded on both ends. Only inclusive ranges are allowed
///
/// ```
/// use parser_compose::{Parser, byte};
///
/// let msg = &[0, 1][..];
///
/// let zero = byte(0..=0);
/// let (value, rest) = zero.try_parse(msg).unwrap();
///
/// assert_eq!(value, [0]);
/// assert_eq!(rest, [1]);
///
/// let result = zero.try_parse(rest);
/// assert!(result.is_err());
///
/// ```
pub fn byte(range: RangeInclusive<u8>) -> Byte {
Byte { range }
}
/// A parser that recognizes an ascii `str` in the given range. See
/// [`ascii_str`](crate::parser::ascii_str)
pub struct AsciiStr {
range: RangeInclusive<u8>,
}
/// A parser that recognizes an byte in the given range. See [`byte`](crate::parser::byte)
pub struct Byte {
range: RangeInclusive<u8>,
}
impl<'input> Parser<&'input str, &'input str, ()> for AsciiStr {
fn try_parse(&self, input: &'input str) -> Res<&'input str, &'input str, ()> {
any_str
.when(|s| {
let b = s.as_bytes();
b[0] >= *self.range.start() && b[0] <= *self.range.end()
})
.try_parse(input)
}
}
impl<'input> Parser<&'input [u8], &'input [u8], ()> for Byte {
fn try_parse(&self, input: &'input [u8]) -> Res<&'input [u8], &'input [u8], ()> {
any_byte
.when(|s| s[0] >= *self.range.start() && s[0] <= *self.range.end())
.try_parse(input)
}
}
/// Trait used to accept the different argument forms we allow for the
/// [repeated](crate::Parser::repeated) combinator
pub trait RepetitionArgument {
/// The minimum amount of times the _thing_ should be repeated
fn at_least(&self) -> usize;
/// The maximum aount of times the _thing_ should be repeated. If it is unbounded, this will
/// return `None`
fn at_most(&self) -> Option<usize>;
}
impl RepetitionArgument for RangeFrom<usize> {
fn at_least(&self) -> usize {
self.start
}
fn at_most(&self) -> Option<usize> {
None
}
}
impl RepetitionArgument for RangeInclusive<usize> {
fn at_least(&self) -> usize {
*self.start()
}
fn at_most(&self) -> Option<usize> {
Some(*self.end())
}
}
impl RepetitionArgument for RangeToInclusive<usize> {
fn at_least(&self) -> usize {
0
}
fn at_most(&self) -> Option<usize> {
Some(self.end)
}
}
impl RepetitionArgument for usize {
fn at_least(&self) -> usize {
*self
}
fn at_most(&self) -> Option<usize> {
Some(*self)
}
}
/// A parser that succeeds if it matches the specified number of times. See
/// [`repeated()`](crate::Parser::repeated)
pub struct Repeat<P, R: RepetitionArgument> {
parser: P,
count: R,
}
impl<In, Out, E, P, R> Parser<In, Vec<Out>, E> for Repeat<P, R>
where
P: Parser<In, Out, E>,
R: RepetitionArgument,
In: Clone,
{
fn try_parse(&self, input: In) -> Res<In, Vec<Out>, E> {
let lower_bound = self.count.at_least();
let upper_bound = self.count.at_most();
let mut results = vec![];
let mut rest = input.clone();
let mut satisfied_lower_bound = false;
if let Some(u) = upper_bound {
assert!(
u >= lower_bound,
"upper bound should be greater than lower bound"
);
if u == 0 {
return Ok((results, rest));
}
}
if lower_bound == 0 {
satisfied_lower_bound = true;
}
while let Ok((value, remaining)) = self.parser.try_parse(rest.clone()) {
results.push(value);
rest = remaining;
if results.len() >= lower_bound {
satisfied_lower_bound = true;
}
if let Some(u) = upper_bound {
if results.len() == u {
// If we've satisfied the upper bound, we don't need to look any further
return Ok((results, rest));
}
};
}
if satisfied_lower_bound {
return Ok((results, rest));
}
Err(Error::Mismatch)
}
}
/// A parser that only succeeds if it does not report an error and the predicate returns `true`.
/// See [`when()`](crate::Parser::when)
pub struct Predicate<P, F> {
parser: P,
predicate: F,
}
impl<In, Out, E, P, F> Parser<In, Out, E> for Predicate<P, F>
where
P: Parser<In, Out, E>,
F: Fn(Out) -> bool,
Out: Clone,
{
fn try_parse(&self, input: In) -> Res<In, Out, E> {
match self.parser.try_parse(input) {
Ok((value, rest)) => match (self.predicate)(value.clone()) {
true => Ok((value, rest)),
false => Err(Error::Mismatch),
},
Err(e) => Err(e),
}
}
}
/// A parser that always succeeds but will wrap its value in an `Option`. See
/// [`optional()`](crate::Parser::optional)
pub struct Optional<P> {
inner: P,
}
impl<In, Out, E, P> Parser<In, Option<Out>, E> for Optional<P>
where
In: Clone,
P: Parser<In, Out, E>,
{
fn try_parse(&self, input: In) -> Res<In, Option<Out>, E> {
match self.inner.try_parse(input.clone()) {
Ok((value, rest)) => Ok((Some(value), rest)),
Err(_) => Ok((None, input)),
}
}
}
/// A parser that does not consume any input regardless of its outcome. See
/// [`peeked()`](crate::Parser::peeked)
pub struct Peeked<P> {
inner: P,
}
impl<In, Out, E, P> Parser<In, Out, E> for Peeked<P>
where
In: Clone,
P: Parser<In, Out, E>,
{
fn try_parse(&self, input: In) -> Res<In, Out, E> {
match self.inner.try_parse(input.clone()) {
Ok((value, _)) => Ok((value, input)),
Err(e) => Err(e),
}
}
}
/// See [`not_peeked()`](crate::Parser::not_peeked)
pub struct NotPeeked<P, Z> {
inner: P,
_phantom: PhantomData<Z>
}
impl<In, Out, E, P> Parser<In, (), E> for NotPeeked<P, Out>
where
In: Clone,
P: Parser<In, Out, E>,
{
fn try_parse(&self, input: In) -> Res<In, (), E> {
match self.inner.try_parse(input.clone()) {
Ok(_) => Err(Error::Mismatch),
Err(_) => Ok(((), input)),
}
}
}
/// A parser that reports an error if it fails, otherwise calls a function with the wrapped value
/// and returns the result. See [`and_then()`](crate::Parser::and_then)
pub struct AndThen<P, F, Z> {
inner: P,
f: F,
phantom: PhantomData<Z>,
}
impl<In, Out, E, P, F, U> Parser<In, U, E> for AndThen<P, F, Out>
where
P: Parser<In, Out, E>,
F: Fn(Out) -> Result<U, Error<E>>,
{
fn try_parse(&self, input: In) -> Res<In, U, E> {
match self.inner.try_parse(input) {
Ok((value, rest)) => match (self.f)(value) {
Ok(m) => Ok((m, rest)),
Err(e) => Err(e),
},
Err(e) => Err(e),
}
}
}
macro_rules! impl_tuple {
($($parser:ident : $parser_type:ident : $out:ident : $out_type:ident),+) => {
/// A tuple of parsers is treated as a parser that tries its inner parsers in turn, feeding
/// the leftover input from the first as the input to the other and so on
///
/// Calling the `.try_parse()` on the tuple returns a new tuple containing the extracted values.
///
/// This is implemented for tuples up to 12 items long
impl<In $(, $parser_type, $out_type)+, E> Parser<In,($($out_type,)+) ,E> for ($($parser_type,)+)
where $($parser_type: $crate::Parser<In, $out_type, E>,)+
{
fn try_parse(&self, input: In) -> $crate::result::Res<In, ($($out_type,)+), E> {
let rest = input;
let ( $( $parser, )+) = self;
$(
let ($out, rest) = match $parser.try_parse(rest) {
Ok(v) => v,
Err(e) => return Err(e),
};
) *
Ok((($($out, )+) , rest))
}
}
}
}
// Ah, good 'ole macros.
//
// The purpose of the `impl_tuple` macro is to generate the following impl for a tuple whose length
// is the number of arguments to the macro.
// `impl Parser<...> for (T1, ) where T1: Parser<..> { ... }`
//
// So this call: `impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1);` generates the Parser impl for tuples of
// length 2.
// This call to `impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2);` generates the impl for
// tuples of length 3, and so on.
//
// Each argument to the macro is a colon delimited keyword that will be used as is in the
// implementation to refer to the type/name of the parser or its output at that tuple location
impl_tuple!(p0:P0:o0:O0);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5, p6:P6:o6:O6);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5, p6:P6:o6:O6, p7:P7:o7:O7);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5, p6:P6:o6:O6, p7:P7:o7:O7, p8:P8:o8:O8);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5, p6:P6:o6:O6, p7:P7:o7:O7, p8:P8:o8:O8, p9:P9:o9:O9);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5, p6:P6:o6:O6, p7:P7:o7:O7, p8:P8:o8:O8, p9:P9:o9:O9, p10:P10:o10:O10);
impl_tuple!(p0:P0:o0:O0, p1:P1:o1:O1, p2:P2:o2:O2, p3:P3:o3:O3, p4:P4:o4:O4, p5:P5:o5:O5, p6:P6:o6:O6, p7:P7:o7:O7, p8:P8:o8:O8, p9:P9:o9:O9, p10:P10:o10:O10, p11:P11:o11:O11);
/// A parser that succeeds if at least one inner parser succeeds. See [`or()`](crate::Parser::or)
pub struct Or<P1, P2> {
parser1: P1,
parser2: P2,
}
impl<In, Out, E, P1, P2> Parser<In, Out, E> for Or<P1, P2>
where
P1: Parser<In, Out, E>,
P2: Parser<In, Out, E>,
In: Clone,
{
fn try_parse(&self, input: In) -> Res<In, Out, E> {
match self.parser1.try_parse(input.clone()) {
Ok((value, rest)) => Ok((value, rest)),
Err(_) => match self.parser2.try_parse(input) {
Ok((value, rest)) => Ok((value, rest)),
Err(e) => Err(e),
},
}
}
}
/// A parser that reports an error if it fails, but pipes its value through a function if it succeeds.
/// See [`map()`](crate::Parser::map).
pub struct Map<P, F, V> {
parser: P,
f: F,
_param: PhantomData<V>,
}
impl<In, Out, E, P, F, M> Parser<In, M, E> for Map<P, F, Out>
where
P: Parser<In, Out, E>,
F: Fn(Out) -> M,
{
fn try_parse(&self, input: In) -> Res<In, M, E> {
match self.parser.try_parse(input) {
Ok((v, rest)) => Ok(((self.f)(v), rest)),
Err(e) => Err(e),
}
}
}
/// A parser that returns its value if it succeeds, but pipes its error through a function if it fails.
/// See [`map_err()`](crate::Parser::map_err)
pub struct MapErr<P, F, E> {
parser: P,
f: F,
_param: PhantomData<E>,
}
impl<In, Out, E, P, F, M> Parser<In, Out, M> for MapErr<P, F, E>
where
P: Parser<In, Out, E>,
F: Fn(Error<E>) -> Error<M>,
{
fn try_parse(&self, input: In) -> Res<In, Out, M> {
match self.parser.try_parse(input) {
Ok((v, rest)) => Ok((v, rest)),
Err(e) => Err((self.f)(e)),
}
}
}
#[cfg(test)]
mod test {
use crate::{Parser, Res};
fn first_elem(mut input: Vec<&str>) -> Res<Vec<&str>, &str, ()> {
let first = input.remove(0);
Ok((first, input))
}
#[test]
fn combinators_can_use_any_input_that_is_clone() {
let msg = vec!["HELLO", "HELLO", "WORLD"];
let (value, rest) = first_elem.repeated(2).try_parse(msg).unwrap();
assert_eq!(value, vec!["HELLO", "HELLO"]);
assert_eq!(rest, vec!["WORLD"]);
}
}
#[cfg(test)]
mod test_map_combinator {
use crate::{Error, Parser};
#[test]
fn test_matry_parse() {
let msg = "AAA";
let (value, rest) = "A".map(str::as_bytes).try_parse(msg).unwrap();
assert_eq!(value, [65]);
assert_eq!(rest, "AA");
}
struct BWasNotFound {}
#[test]
fn test_map_err() {
let msg = "AA";
let result = "B"
.map(str::as_bytes)
.map_err(|_| Error::Custom(BWasNotFound {}))
.try_parse(msg);
assert!(result.is_err());
assert!(matches!(result, Err(Error::Custom(BWasNotFound {}))));
}
}
#[cfg(test)]
mod test_or_combinator {
use crate::Parser;
#[test]
fn it_works() {
let msg = "GET";
let result = "POST".or("PUT").try_parse(msg);
assert!(result.is_err());
let (value, _) = "GET".or("POST").try_parse(msg).unwrap();
assert_eq!(value, "GET");
// The first match is reported
let (value, _) = "G".or("GE").or("GET").try_parse(msg).unwrap();
assert_eq!(value, "G");
}
}
#[cfg(test)]
mod test_when_combinator {
use crate::Parser;
#[test]
fn it_works() {
let msg = "GET";
let pass = false;
let result = "GET".when(|_| pass).try_parse(msg);
assert!(result.is_err());
let pass = true;
let (value, _) = "GET".when(|_| pass).try_parse(msg).unwrap();
assert_eq!(value, "GET");
}
}
#[cfg(test)]
mod test_tuple_combinator {
use crate::{any_str, Parser, Res};
fn whitespace(input: &str) -> Res<&str, &str, ()> {
any_str.when(|c| c == " ").try_parse(input)
}
#[test]
fn it_works() {
let msg = "GET https://example.org HTTP/1.1";
let method_parser = "GET".or("POST").or("PUT");
let scheme_parser = "http://".or("https://");
let authority_parser = "example.org";
let version_parser = "HTTP/1.0".or("HTTP/1.1");
let (method, _, scheme, authority, _, version) = (
method_parser,
whitespace,
scheme_parser,
authority_parser,
whitespace,
version_parser,
)
.try_parse(msg)
.unwrap()
.0;
assert_eq!(method, "GET");
assert_eq!(scheme, "https://");
assert_eq!(authority, "example.org");
assert_eq!(version, "HTTP/1.1");
}
}
#[cfg(test)]
mod test_repeated_combinator {
use crate::Parser;
#[test]
fn test_single_value_count() {
let msg = "AAA";
let (value, rest) = "A".repeated(2).try_parse(msg).unwrap();
assert_eq!(value, vec!["A", "A"]);
assert_eq!(rest, "A");
let result = "A".repeated(4).try_parse(msg);
assert!(result.is_err());
let (value, rest) = "A".repeated(0).try_parse(msg).unwrap();
assert!(value.is_empty());
assert_eq!(rest, "AAA");
}
#[test]
fn test_bounded_both_sides() {
let msg = "AAAABB";
let (value, rest) = "A".repeated(0..=0).try_parse(msg).unwrap();
assert!(value.is_empty());
assert_eq!(rest, msg);
let (value, rest) = "A".repeated(1..=1).try_parse(msg).unwrap();
assert_eq!(value, vec!["A"]);
assert_eq!(rest, "AAABB");
let (value, rest) = "A".repeated(1..=3).try_parse(msg).unwrap();
assert_eq!(value, vec!["A", "A", "A"]);
assert_eq!(rest, "ABB");
let (value, rest) = "A".repeated(1..=10).try_parse(msg).unwrap();
assert_eq!(value, vec!["A", "A", "A", "A"]);
assert_eq!(rest, "BB");
}
#[test]
#[should_panic]
fn test_bounded_both_sides_panics_if_lower_is_greater_than_upper() {
let msg = "AAAABB";
let _ = "A".repeated(1..=0).try_parse(msg);
}
#[test]
fn test_lower_bound() {
let msg = "AAAB";
let result = "A".repeated(4..).try_parse(msg);
assert!(result.is_err());
let (value, rest) = "A".repeated(1..).try_parse(msg).unwrap();
assert_eq!(value, vec!["A", "A", "A"]);
assert_eq!(rest, "B");
}
#[test]
fn test_upper_bound() {
let msg = "BB";
let (value, rest) = "A".repeated(..=3).try_parse(msg).unwrap();
assert!(value.is_empty());
assert_eq!(rest, "BB");
let msg = "AAB";
let (value, rest) = "A".repeated(..=0).try_parse(msg).unwrap();
assert!(value.is_empty());
assert_eq!(rest, "AAB");
let (value, rest) = "A".repeated(..=1).try_parse(msg).unwrap();
assert_eq!(value, vec!["A"]);
assert_eq!(rest, "AB");
let (value, rest) = "A".repeated(..=10).try_parse(msg).unwrap();
assert_eq!(value, vec!["A", "A"]);
assert_eq!(rest, "B");
}
#[test]
fn always_succeeds_with_zero_lower_bound() {
let msg = "GG";
let (value, rest) = "A".repeated(0..).try_parse(msg).unwrap();
assert_eq!(value, vec![] as Vec<&str>);
assert_eq!(rest, "GG");
}
}
#[cfg(test)]
mod test_peeked_combinator {
use crate::Parser;
#[test]
fn test_attempt_does_not_consume_input_on_success() {
let msg = "AAAAB";
let ((a, b), rest) = (
"A".repeated(1..).map(|s| s.into_iter().collect::<String>()),
"B".peeked(),
)
.try_parse(msg)
.unwrap();
assert_eq!(a, "AAAA");
assert_eq!(b, "B");
assert_eq!(rest, "B");
}
#[test]
fn test_not_peeeked() {
// This parser matches a single "a", but only if it is not part of an arbitrary long
// sequence of "a"'s followed by a "b".
// I got this from the wikipedia page on parsing expression grammars
let tricky = (("a".repeated(1..), "b").not_peeked(), "a");
let fail = "aaaba";
let pass = "aaaa";
let result = tricky.try_parse(fail);
assert!(result.is_err());
let (value, rest) = tricky.try_parse(pass).unwrap();
assert_eq!(value, ((), "a"));
assert_eq!(rest, "aaa");
}
}
#[cfg(test)]
mod test_str_parsers {
use crate::{any_str, ascii_str, Parser};
#[test]
fn empty_str() {
let msg = "H";
let (value, rest) = "".try_parse(msg).unwrap();
assert_eq!(value, "");
assert_eq!(rest, msg);
}
#[test]
fn test_any_str() {
let msg = "🏠";
let (value, rest) = any_str.try_parse(msg).unwrap();
assert_eq!(value, "🏠");
assert_eq!(rest, "");
}
#[test]
fn ascii_range_parsers() {
let msg = "abc";
let (value, rest) = ascii_str(97..=97).try_parse(msg).unwrap();
assert_eq!(value, "a");
let result = ascii_str(97..=97).try_parse(rest);
assert!(result.is_err());
}
}