chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

recursive forces a specific lifetime on the implementation.

Open nevakrien opened this issue 2 months ago • 1 comments

so basically i am trying to do a

impl for<'a> Parser<'a, &'a str, LocExpr, PErr<'a>>

for a recursive parser and i am getting an error on the impl. now that seems like it makes no sesne from context. like why would a specific lifetime be forced here?

nevakrien avatar Oct 29 '25 15:10 nevakrien

This is a consequence of the way recursive works and, to some extent, the entire crate.

In an ideal world, parsers would just implement Parser<I, O> and then it would instead be the .parse(...) function that is generic over the lifetime, not the entire parser.

Sadly, this isn't possible for rather subtle reasons (words like 'invariance' crop up a lot) and the crate has simply evolved over time around that constraint.

The practical consequences of this are almost non-existent. Most of the time parsers are only used in one place, and Rust will happily infer a suitable lifetime. If a parser needs using in multiple places, recreating the parser is usually cheap enough that it doesn't matter. In the exceedingly rare case that the cost is high enough to matter, and the parser does need using in multiple places, there is a workaround in the form of the Cache type, which allows reusing a parser with any lifetime in a sound manner.

TL;DR: You're best off just avoiding HRTBs and instead just making whatever function creates your parser generic over the input lifetime. I've yet to see a case where this isn't sufficient.

zesterer avatar Oct 29 '25 20:10 zesterer