chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

MapExtra cannot infer state type

Open MechSlayer opened this issue 2 months ago • 1 comments

Whenever I try to access the state from MapExtra the compiler complains about not being able to infer the state. It doesn't matter if it's in select!. map_with or anything else.

Example:

fn parser<'a, I>() -> impl Parser<'a, I, (), extra::Full<Rich<'a, Token<'a>, TextSpan>, ParsingUnit, ()>>
    where I: ValueInput<'a, Token=Token<'a>, Span=TextSpan>
{
    let identifier = select! {
        Token::Identifier(string) = ex => ex.state().intern(string)
    };


    identifier.repeated().collect::<()>()
}

And the error:

   |
11 |         Token::Identifier(string) = ex => ex.state().intern(string)
   |                                                      ^^^^^^ cannot infer type

MechSlayer avatar Apr 16 '24 16:04 MechSlayer

Unfortunately, this is due to a limitation in rustc (interestingly, other Rust compilers like mrustc doesn't have this limitation and can in theory infer this type without extra hints). Rust will only permit a method call if, by the time that it meets the method call, it knows the full type of the left-hand side (or can infer it from the method call alone).

You can easily provide a hint to Rust by doing (e.state() as &mut MyStateType).intern(string).

zesterer avatar Apr 17 '24 05:04 zesterer