winnow-rs / winnow

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

derive `Default` for `Stateful` #524

Closed TennyZhuang closed 4 months ago

TennyZhuang commented 4 months ago

Please complete the following tasks

winnow version

0.6.8

Describe your use case

I want to utilize the subparser pattern, to minimize the scope of the parser state.

Currently, my solution is like this:

fn with_state<S, State, O, ParseNext>(mut parse_next: ParseNext) -> impl Parser<S, O, ContextError>
where
    S: TokenStream,
    State: Default,
    ParseNext: Parser<Stateful<S, State>, O, ContextError>,
{
    move |input: &mut S| -> PResult<O> {
        let state = State::default();
        let input2 = std::mem::take(input);
        let mut stateful = Stateful {
            input: input2,
            state,
        };
        let output = parse_next.parse_next(&mut stateful);
        *input = stateful.input;
        output
    }
}

This works well, unless I want to use Stateful<Stateful<S, State1>, State2>, which doesn't implement Default even if both S, State1 and State2 implemented Default.

Describe the solution you'd like

Derive Default for Stateful.

It's harmless for any other use case. Only when both input and state implemented Default, Stateful<I, S> will implemented Default.

Alternatives, if applicable

No response

Additional Context

No response