Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DPDmancul opened this issue Nov 27, 2020 · 0 comments
Open

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

DPDmancul opened this issue Nov 27, 2020 · 0 comments

Comments

@DPDmancul
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant