Lesson 8 of 15

Parenthesized Expressions

Parsing Parentheses

Parentheses let users override precedence: (2 + 3) * 4 should give 20, not 14.

In our grammar, parenthesized expressions live at the factor level — the tightest binding:

factor -> NUMBER | '(' expr ')'

Implementation

In parseFactor, check if the current token is LPAREN. If so, consume it, parse a full expression, then expect RPAREN:

parseFactor() {
    if (this.peek().type === "LPAREN") {
        this.advance(); // consume '('
        const expr = this.parseExpr();
        this.advance(); // consume ')'
        return expr;
    }
    const tok = this.advance();
    return { type: "NumberLiteral", value: Number(tok.value) };
}

The key insight: inside the parentheses, we call parseExpr() — the lowest precedence level. This means any expression can appear inside parens.

Your Task

Add parenthesis support to the parser. (2 + 3) * 4 should parse as (* (+ 2 3) 4).

Node.js loading...
Loading...
Click "Run" to execute your code.