lib/grammar/
parser.rs

1// use pest::error::ErrorVariant;
2use pest::iterators::Pairs;
3use pest::Parser;
4use pest_derive::Parser;
5use std::fmt;
6
7const SIEVE_MARKER: u8 = 0xff;
8
9#[derive(Parser)]
10#[grammar = "grammar.pest"]
11pub struct SieveParser;
12
13impl SieveParser {
14    pub fn serialize(pairs: &Pairs<'_, Rule>) -> Result<Vec<u8>, Box<bincode::ErrorKind>> {
15        let mut buf = Vec::with_capacity(bincode::serialized_size(pairs)? as usize + 2);
16
17        buf.push(SIEVE_MARKER);
18        bincode::serialize_into(&mut buf, pairs).unwrap();
19        Ok(buf)
20    }
21}
22
23// use pest::error::*;
24
25#[derive(Debug)]
26pub struct ParserError {
27    code: usize,
28    // message: String,
29    // location: (usize, usize),
30}
31
32impl fmt::Display for ParserError {
33    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34        let err_msg = match self.code {
35            404 => "Sorry, Can not find the Page!",
36            _ => "Sorry, something is wrong! Please Try Again!",
37        };
38
39        write!(f, "{}", err_msg)
40    }
41}
42
43pub fn parse<'r>(src: &'r str) -> Result<Pairs<'r, Rule>, ParserError> {
44    match SieveParser::parse(Rule::sieve, &src[..]) {
45        Ok(pairs) => Ok(pairs),
46        Err(e) => {
47            eprintln!("Error: {}", e);
48
49            // let location = match e.location {
50            //     InputLocation::Pos(a) => (a, a),
51            //     InputLocation::Span((a, b)) => (a, b),
52            // };
53
54            // let message = match &e.variant {
55            //     ErrorVariant::ParsingError {
56            //         positives,
57            //         negatives: _s,
58            //     } => {
59            //         // println!("Error: {:?}", e);
60            //         // println!("Error: {:?}", positives);
61            //         // println!("Error: {:?}", negatives);
62            //         "Parsing error".to_string()
63            //     }
64            //     ErrorVariant::CustomError { message } => message.to_string(),
65            // };
66
67            Err(ParserError {
68                code: 404,
69                // location,
70                // message,
71            })
72        }
73    }
74}