Home › GATE CSE › computerscience › Compiler Design › How does a parser typically encode OPERATOR PREC…
How does a parser typically encode OPERATOR PRECEDENCE in the grammar?
Aencoded as code comments
Bnon-terminal per precedence level
Cchecked at runtime during execution
Dhandled inside the lexer (scanner)
Answer & Solution
Correct answer: B. non-terminal per precedence level
1. CASCADING precedence: each precedence LEVEL gets its own non-terminal. Higher-precedence rules sit BENEATH lower ones.
2. Standard hierarchy (low to high):
- Expression: equality, comparison, addition, multiplication, unary, primary
3. Grammar:
- $E \to A \,(==\, A)^*$ (equality, lowest)
- $A \to M\, (+\, M)^*$ (additive)
- $M \to U\, (*\, U)^*$ (multiplicative)
- $U \to !U \mid P$ (unary)
- $P \to NUM \mid (E)$ (primary, highest)
4. The deeper in the recursion = higher precedence (binds tighter). Same approach in Crafting Interpreters Lox grammar.
5. Other options don't encode precedence properly.
_Source: Bob Nystrom, "Crafting Interpreters", Ch 6.2 (Recursive descent — precedence ladder)._
Related questions
The FOLLOW(A) set in LL parsing isThe FIRST(α) set of a string α in LL parsing isAfter the parser produces an AST, the next compiler phase is typicallyA SHIFT/REDUCE CONFLICT in an LR parser occurs whenWhich of these is a BOTTOM-UP (LR) parser feature?An LL(1) grammar requires that, given the leftmost non-terminal and ONE token of lookaheadLL parsers (recursive descent) parse from thePANIC MODE error recovery in a parser works by