ast icon indicating copy to clipboard operation
ast copied to clipboard

Suggestion: implementation of FromPest for std::str::FromStr

Open DPDmancul opened this issue 5 years ago • 0 comments

Adding this implementation in https://github.com/pest-parser/ast/blob/master/src/lib.rs:

impl<'pest, T: std::str::FromStr> FromPest<'pest> for T {
    type Rule = /* Rule */;
    type FatalError = T::Err;
    fn from_pest(pest: &mut Pairs<'pest, Self::Rule>) -> Result<T, ConversionError<Self::FatalError>> {
        pest.next().ok_or(ConversionError::NoMatch)?.as_str().parse::<T>().ok_or_else(|e|ConversionError::Malformed(e))
    }
}

simplifies the parsing of values (which is a common task) from

#[derive(Debug, FromPest)]
#[pest_ast(rule(Rule::field))]
pub struct Field {
    #[pest_ast(outer(with(span_into_str), with(str::parse), with(Result::unwrap)))]
    pub value: f64,
}

to

#[derive(Debug, FromPest)]
#[pest_ast(rule(Rule::field))]
pub struct Field {
    pub value: f64,
}

This implementation must be inserted in the crate since it cannot be inserted in the final code being both the FromPest and FromStr trials not part of the final code and implementation is allowed only for trials and types defined in the crate.

The problem is how to pass the Rule type.

DPDmancul avatar Nov 27 '20 19:11 DPDmancul