chumsky
chumsky copied to clipboard
idiomatic way to express (optional) delimiters?
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.
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.