From 80bd718677080227f7b2e26744456cb13debca27 Mon Sep 17 00:00:00 2001 From: Nadrieril Date: Wed, 11 Sep 2019 22:42:15 +0200 Subject: Various tweaks --- pest_consume/examples/csv/main.rs | 44 ++++++++++++++++++++++----------------- 1 file changed, 25 insertions(+), 19 deletions(-) (limited to 'pest_consume/examples/csv/main.rs') diff --git a/pest_consume/examples/csv/main.rs b/pest_consume/examples/csv/main.rs index bb9f8fc..efb83ad 100644 --- a/pest_consume/examples/csv/main.rs +++ b/pest_consume/examples/csv/main.rs @@ -1,57 +1,60 @@ #![feature(slice_patterns)] -use pest_consume::{match_nodes, Parser}; - -#[derive(pest_derive::Parser)] -#[grammar = "../examples/csv/csv.pest"] -struct CSVParser; - -type ParseResult = Result>; -type Node<'i> = pest_consume::Node<'i, Rule, ()>; +use pest_consume::{match_nodes, Error, Parser}; #[derive(Debug)] enum CSVField<'a> { Number(f64), String(&'a str), } - type CSVRecord<'a> = Vec>; type CSVFile<'a> = Vec>; +type Result = std::result::Result>; +type Node<'i> = pest_consume::Node<'i, Rule, ()>; + +#[derive(Parser)] +#[grammar = "../examples/csv/csv.pest"] +struct CSVParser; + #[pest_consume::parser(CSVParser, Rule)] impl CSVParser { - fn EOI(_input: Node) -> ParseResult<()> { + fn EOI(_input: Node) -> Result<()> { Ok(()) } - fn number(input: Node) -> ParseResult { - Ok(input.as_str().parse().unwrap()) + fn number(input: Node) -> Result { + input + .as_str() + .parse::() + // `input.error` links the error to the location in the input file where it occurred. + .map_err(|e| input.error(e.to_string())) } - fn string(input: Node) -> ParseResult<&str> { + fn string(input: Node) -> Result<&str> { Ok(input.as_str()) } - fn field(input: Node) -> ParseResult { + fn field(input: Node) -> Result { Ok(match_nodes!(input.children(); [number(n)] => CSVField::Number(n), [string(s)] => CSVField::String(s), )) } - fn record(input: Node) -> ParseResult { + fn record(input: Node) -> Result { Ok(match_nodes!(input.children(); [field(fields)..] => fields.collect(), )) } - fn file(input: Node) -> ParseResult { + fn file(input: Node) -> Result { Ok(match_nodes!(input.children(); [record(records).., EOI(_)] => records.collect(), )) } } -fn parse_csv(input_str: &str) -> ParseResult { +fn parse_csv(input_str: &str) -> Result { let inputs = CSVParser::parse(Rule::file, input_str)?; Ok(match_nodes!(; inputs; [file(e)] => e, @@ -59,6 +62,9 @@ fn parse_csv(input_str: &str) -> ParseResult { } fn main() { - let parsed = parse_csv("-273.15, ' a string '\n\n42, 0"); - println!("{:?}", parsed); + let successful_parse = parse_csv("-273.15, ' a string '\n\n42, 0"); + println!("success: {:?}", successful_parse.unwrap()); + + let unsuccessful_parse = parse_csv("0, 273.15.12"); + println!("failure: {}", unsuccessful_parse.unwrap_err()); } -- cgit v1.2.3