Skip to content

How to deal with left recursion #31

Answered by zesterer
ambroisie asked this question in Q&A
Discussion options

You must be logged in to vote

The typical way to solve left recursion is to rewrite the pattern as a right-recursive one and then reverse the output.

A technique I've used in my own lang is to use a helper enum to allow me to restate patterns like yours in an iterative manner, as if it were a chain of 'tails' following the original expression.

let var = parse_id().map(ast::Lvalue::Var).labelled("variable");

enum Tail {
    Field(...),
    Call(...),
}

let tail =
    // Field access
    DOT.then(FIELD).map(Tail::Field)
    // Call
    .or(EXPR.separated_by(LBRACKET, RBRACKET)).map(Tail::Call);

let chain = var.then(tail.repeated()).foldl(|lhs, tail| {
    match tail {
        Tail::Field(field) => ast::LValue::Field(lhs

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by ambroisie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants