chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

Memory leak in `recursive` when using `define` function

Open mattnenterprise opened this issue 11 months ago • 8 comments

The recursive implementation leaks memory if it references itself and the parser definition is defined using the define function. See the following example that creates millions of parsers, but the memory is never released.

use chumsky::prelude::*;

#[derive(Debug, PartialEq)]
enum Chain {
    End,
    Link(char, Box<Chain>),
}

fn parser() -> impl Parser<char, Chain, Error = Simple<char>> {
    let mut chain = Recursive::<_, _, Simple<char>>::declare();

    chain.define(just('+')
        .then(chain.clone())
        .map(|(c, chain)| Chain::Link(c, Box::new(chain)))
        .or_not()
        .map(|chain| chain.unwrap_or(Chain::End)));

    chain
}

fn main() {
    for _n in 1..100_000_000 {
        parser();
    }
}

I originally found this issue in the jaq filter parser here.

mattnenterprise avatar Jul 24 '23 17:07 mattnenterprise