Step 1 of 3 · Reading · ~2 min
Parsing Binary and Unary Operations
Parsing Expressions
Filling In the Precedence Ladder
You've seen the shape of the grammar; now you're implementing all the rungs of it — every binary operator level (term, factor, comparison, equality) plus unary, the one rule in the ladder that isn't left-associative-binary but right-recursive-prefix.
Unary Operators Are Different
! (logical not) and - (negation) are prefix operators — they appear before their single operand, and they can stack: !!true, --5. That means unary can't use the "parse one operand, then loop over operators" pattern from binary rules. Instead it recurses into itself:
Recursing into unary() rather than primary() is what makes --5 parse as Unary(-, Unary(-, 5)) instead of failing after the first -. If your unary rule fell through to primary() after consuming one prefix operator, a second consecutive ! or - would have nowhere to go.
Building the Four Binary Levels
term, factor, comparison, and equality are structurally identical — only the accepted operator tokens and the next-level-down call change:
Because term calls factor() for its operands (not term() again directly), a * or / embedded inside a +/- expression is automatically absorbed into a tighter-binding subtree before term's loop ever sees it. This is the entire precedence mechanism — there's no separate precedence-comparison logic anywhere; it emerges purely from which function calls which.
Common Bugs at This Stage
- Wrong call target: if
termmistakenly calledterm()instead offactor()for its right operand, you'd get infinite recursion (or, if guarded, wrong precedence). - Right-associativity where you wanted left: building
Binary(right, op, expr)instead ofBinary(expr, op, right)silently reverses associativity —1 - 2 - 3would evaluate as1 - (2 - 3) = 2instead of the correct(1 - 2) - 3 = -4. - Forgetting
unaryrecurses into itself: leads to!!xor double-negation failing to parse, or parsing only the first prefix operator correctly.
Test each level in isolation with expressions that only use that level's operators and things one level down (e.g. test factor with 2 * -3, which requires both factor's loop and unary's recursion to be correct together) before combining everything into full expressions.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…