summaryrefslogtreecommitdiff
path: root/pest_consume/examples/csv/main.rs
blob: 037948b0b7368871f4f55e5c1c5949d5446278de (plain)
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
#![feature(slice_patterns)]
use pest_consume::{match_inputs, Parser};

#[derive(pest_derive::Parser)]
#[grammar = "../examples/csv/csv.pest"]
struct CSVParser;

type ParseResult<T> = Result<T, pest::error::Error<Rule>>;
type Node<'i> = pest_consume::Node<'i, Rule, ()>;

#[derive(Debug)]
enum CSVField<'a> {
    Number(f64),
    String(&'a str),
}

type CSVRecord<'a> = Vec<CSVField<'a>>;
type CSVFile<'a> = Vec<CSVRecord<'a>>;

#[pest_consume::parser(CSVParser, Rule)]
impl CSVParser {
    fn EOI(_input: Node) -> ParseResult<()> {
        Ok(())
    }

    fn number(input: Node) -> ParseResult<f64> {
        Ok(input.as_str().parse().unwrap())
    }

    fn string(input: Node) -> ParseResult<&str> {
        Ok(input.as_str())
    }

    fn field(input: Node) -> ParseResult<CSVField> {
        Ok(match_inputs!(input.children();
            [number(n)] => CSVField::Number(n),
            [string(s)] => CSVField::String(s),
        ))
    }

    fn record(input: Node) -> ParseResult<CSVRecord> {
        Ok(match_inputs!(input.children();
            [field(fields)..] => fields.collect(),
        ))
    }

    fn file(input: Node) -> ParseResult<CSVFile> {
        Ok(match_inputs!(input.children();
            [record(records).., EOI(_)] => records.collect(),
        ))
    }
}

fn parse_csv(input_str: &str) -> ParseResult<CSVFile> {
    let inputs = CSVParser::parse(Rule::file, input_str)?;
    Ok(match_inputs!(<CSVParser>; inputs;
        [file(e)] => e,
    ))
}

fn main() {
    let parsed = parse_csv("-273.15, ' a string '\n\n42, 0");
    println!("{:?}", parsed);
}