chumsky icon indicating copy to clipboard operation
chumsky copied to clipboard

idiomatic way to express (optional) delimiters?

Open femtomc opened this issue 1 year ago • 1 comments

Hi again!

I want to write a parser where the delimiters are optional. I tried the following:

        let lapp__ = expr
            .clone()
            .then_ignore(just(Token::Space))
            .then_ignore(just(Token::RParen))
            .then(expr.clone());

        let lapp_ = choice((
            just(Token::LParen)
                .ignore_then(lapp__)
                .then_ignore(just(Token::RParen)),
            lapp__,
        ))
        .map(|(e1, e2)| LApp(e1, e2));

the issue here is that lapp_ is moved in choice -- which makes me think that there is a better idiom than what I'm trying to do here.

femtomc avatar Jul 11 '22 23:07 femtomc

My usual approach looks something like the following:

let inner = ... ;

let outer = inner.clone()
    .delimited_by(just(Token::LParen), just(Token::RParen))
    .or(inner);

Cloning a parser is usually relatively cheap and, most importantly, happens during parser construction and not during parsing itself so you need not worry about the performance implications.

zesterer avatar Jul 12 '22 08:07 zesterer