pest
pest copied to clipboard
Blanket FromStr implementation to enable Span::parse()?
I just defined this in my code. Maybe It would be a good idea to create a blanket implementation for FromStr
in Pest itself?
trait PairExt<R> where R: pest::RuleType {
fn parse<T, E>(&self) -> Result<T, pest::error::Error<R>> where T: std::str::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, pest::error::Error<R>> where T: std::str::FromStr<Err = E>, E: ToString {
self.as_str().parse().map_err(|e: T::Err| {
use pest::error::{Error,ErrorVariant};
let var: ErrorVariant<R> = ErrorVariant::CustomError { message: e.to_string() };
Error::new_from_span(var, self.as_span())
})
}
}
This way a thing that implements FromStr
can be created via a some_pair.parse()?
and the user sees some underlining pointing out where the parse error happened.
It would be even nicer to have it defined on Span
, but that’s impossible since the error type providing the nice formatting is generic over the rule type. CustomError
of course doesn’t use the rule type, but of course the type system can’t know that.
Interesting proposal. I haven't really thought about implementing FromStr
until now because of the Rule
type complication. I think this would be a good place to start discussing parser typing for 3.0.