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)._
Keep practising Compiler Design
Browse all Compiler Design questions for GATE CSE, or explore more Computer Science topics.
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 whenLL parsers (recursive descent) parse from thePANIC MODE error recovery in a parser works byWhat is a SYNTAX ERROR?An AMBIGUOUS grammar is one where