Skip to content

Memory leak in recursive when using define function #486

Open
@mattnenterprise

Description

@mattnenterprise

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions