aboutsummaryrefslogtreecommitdiffstats
path: root/parser/src/pair_ext_parse.rs
blob: cbb51b0acb82f592c09be5e8420aa6937707385a (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
use std::str::FromStr;

use pest::error::{Error, ErrorVariant};
use pest::iterators::Pair;
use pest::Span;

pub trait PairExt<R>
where
    R: pest::RuleType,
{
    fn parse<T, E>(&self) -> Result<T, Box<Error<R>>>
    where
        T: FromStr<Err = E>,
        E: ToString;
}

impl<'l, R> PairExt<R> for Pair<'l, R>
where
    R: pest::RuleType,
{
    fn parse<T, E>(&self) -> Result<T, Box<Error<R>>>
    where
        T: FromStr<Err = E>,
        E: ToString,
    {
        self.as_str()
            .parse()
            .map_err(|e| to_parse_error(self.as_span(), &e))
    }
}

pub(crate) fn to_parse_error<E, R>(span: Span, e: &E) -> Box<Error<R>>
where
    E: ToString,
    R: pest::RuleType,
{
    let var: ErrorVariant<R> = ErrorVariant::CustomError {
        message: e.to_string(),
    };
    Box::new(Error::new_from_span(var, span))
}