Last active
October 31, 2018 16:52
-
-
Save teddywing/6f1c7e2ea72035da2fbf2f4e9c426288 to your computer and use it in GitHub Desktop.
Rust Combine error propagation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "parser-error-test" | |
version = "0.1.0" | |
[dependencies] | |
combine = "3.6.1" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate combine; | |
use std::collections::HashMap; | |
use combine::*; | |
use combine::parser::char::*; | |
fn beginning<I>() -> impl Parser<Input = I, Output = String> | |
where | |
I: Stream<Item = char>, | |
I::Error: ParseError<I::Item, I::Range, I::Position>, | |
{ | |
string("test").map(|s| s.to_string()) | |
} | |
fn item<I>() -> impl Parser<Input = I, Output = (String, String)> | |
where | |
I: Stream<Item = char>, | |
I::Error: ParseError<I::Item, I::Range, I::Position>, | |
{ | |
( | |
beginning(), | |
space(), | |
many(any()), | |
).map(|(beginning, _, rest)| | |
( | |
beginning, | |
rest, | |
) | |
) | |
} | |
fn items<I>() -> impl Parser<Input = I, Output = HashMap<String, String>> | |
where | |
I: Stream<Item = char>, | |
I::Error: ParseError<I::Item, I::Range, I::Position>, | |
{ | |
many(item()) | |
} | |
fn main() { | |
println!("{:?}", item().easy_parse("incorrect").map(|t| t.0)); | |
println!( | |
"{:?}", | |
items().easy_parse("incorrect hello").map(|t| t.0) | |
); | |
// Output: | |
// Err(Errors { position: PointerOffset(4368496305), errors: [Unexpected(Token('i')), Expected(Borrowed("test"))] }) | |
// Ok({}) | |
// Want: `Err` from `items()` parser | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment