winnow-rs / winnow

Making parsing a breeze
https://docs.rs/winnow
Other
525 stars 40 forks source link

Location aware error context #410

Open urso opened 9 months ago

urso commented 9 months ago

Enhancement Request: https://github.com/winnow-rs/winnow/issues/409

This PR implements the LocationContextError. The implementation follows the ContextError type:

pub struct LocationContextError<L = usize, C = StrContext> {
   ...
}

Main differences to ContextError:

Although Location.location returns an usize, this type is not always appropriate in all situations. For example in one of my parsers I have a lexer phase and some parse steps that just recognize a sequence of tokens. The actual parsing happens later. For that reason I'm having a struct Span(Range<u32>) as location.

In order to make the location type configurable we allow users to set the location type via L.

Note: I didn't want to modify the Location trait to make the output type configurable yet. Although I think that would improve the usability of LocationContextError. This is why ParserError and AddContext are implemented for usize only. But their implementations can easily be copied for custom location types. The helper methods to merge/add context information only require L: Ord.

Testing: I didn't find tests for the other error types. So I didn't add new ones.

urso commented 9 months ago

Update: I removed the L location type parameter from LocationContextError. We store the position as usize and require the input stream to implement Location.