Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Operator-precedence parsing

Operator-precedence parsing is a bottom-up parsing technique that uses precedence relations between terminals (operators) to decide shift/reduce actions without full LR tables; it is useful for expression parsing and simple operator grammars.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Two or three sentences: Operator-precedence parsing is an efficient, table-driven bottom-up parsing method an engineer uses when building expression parsers (for arithmetic, Boolean, or simple domain-specific languages) where operators have clear precedences and associativities. It is simpler to implement than full LR parsers and is used inside compilers (parsing phase) and some parser-generators for expression sublanguages.

Key ideas

Start from first principles and define terms before use.

  • Parsing: the process of analysing a string of tokens to determine its syntactic structure according to a grammar (assumes you know about grammars from the Front end topic).
  • Bottom-up parsing: a style of parsing that builds parse trees from leaves (tokens) to root (start symbol) by successively replacing handles (see below) with nonterminals; operator-precedence parsing is a bottom-up method related to shift-reduce parsing.
  • Operator-precedence parsing: a table-driven shift-reduce technique that uses binary relations between terminals (usually operators and delimiters) to decide whether to shift the next input token or reduce the symbols on the stack. It works for a restricted class of grammars called operator-precedence grammars.

Definition (Operator-precedence grammar). Bold each condition:

  • A grammar G is an operator-precedence grammar if (1) it has no ε (empty string) productions, and (2) it has no production whose right-hand side contains two adjacent nonterminals. These restrictions guarantee that precedence relations between terminals are well-defined.

Definitions of relations. For terminals a and b we define three precedence relations (Floyd's relations):

  • a <· b (read: a has lower precedence than b, or a yields precedence to b) — indicates the parser should shift when top terminal is a and next input is b.
  • a = b (read: a is equal precedence to b, often used for paired delimiters like '(' and ')') — indicates tokens are in the same precedence band (used to group symbols that form a single handle border).
  • a ·> b (read: a has higher precedence than b, or a takes precedence over b) — indicates the parser should reduce when top terminal is a and next input is b.

We must build a precedence table that tells, for each pair (a,b) of terminals that can appear adjacent in some sentential form (including marker $), which relation holds; cells for pairs that never appear may be left blank. If any pair receives more than one relation (a conflict), the grammar is not an operator-precedence grammar. You may optionally add precedence/associativity declarations (by language design) to fill otherwise blank cells that affect parsing.

Key algorithmic objects (defined):

  • FirstVT(A): the set of terminals that can appear first in some string derived from nonterminal A (more formally: all terminals a such that A =>* a α or A =>* B a α for some α, B). Compute it with a closure algorithm below.
  • LastVT(A): the set of terminals that can appear last in some string derived from A (all terminals a such that A =>* α a or A =>* α a B for some α, B). Also computed by a closure.
  • Handle: a substring of the right sentential form that matches the right-hand side of some production and whose reduction represents one step in the reverse of a rightmost derivation; operator-precedence parsing locates the handle by comparing precedence relations of adjacent terminals.

Rules to fill the precedence table (exact statements universities ask for): Given a production A → X1 X2 ... Xn (Xi are terminals or nonterminals), for every occurrence of patterns in the RHS do:

  1. If there is a pattern a B b in the RHS (a and b are terminals with exactly one nonterminal B between them), set a = b.
  2. If Xi is a terminal a and Xi+1 is a nonterminal B, then for every terminal b in FirstVT(B) set a <· b.
  3. If Xi is a nonterminal B and Xi+1 is a terminal a, then for every terminal b in LastVT(B) set b ·> a. Additionally, include the end-marker $ as a terminal and set $ <· a and a ·> $ for every terminal a ≠ $; and set $ = $.

Assumptions and consequences: these rules assume (i) no ε-productions and (ii) no adjacent nonterminals. Blank cells are acceptable for terminal pairs that never occur adjacent in any right-sentential form; what is disallowed is assigning more than one relation to the same ordered pair. You may add explicit precedence/associativity (by language design) to fill additional cells when needed for parsing.

What to draw for an exam diagram: draw a square table with terminals + $ both as row headers (top, left-to-right) and column headers (left side, top-to-bottom). Label each cell (row a, column b) with one of <·, =, ·>, or blank if undefined. For a worked parsing trace, draw the stack (vertical list) left and the remaining input (horizontal), and at each step write the precedence comparison used (e.g., top-terminal <· next-input → SHIFT).

Formulas

For this programming/algorithmic topic, list the key syntax/steps to remember (each on its own line): Compute FirstVT and LastVT by closure rules: If A -> a ... then add a to FirstVT(A). If A -> B ... and b in FirstVT(B) then add b to FirstVT(A). If A -> ... a then add a to LastVT(A). If A -> ... B and b in LastVT(B) then add b to LastVT(A). Precedence-table rules: If production has ... a b ... (both terminals) set a = b. If production has ... a B ... then for each b in FirstVT(B) set a <· b. If production has ... B a ... then for each b in LastVT(B) set b ·> a. Add $ relations: for each a in FirstVT(S) set $ <· a; for each a in LastVT(S) set a ·> $; set $ = $. Parsing main action (loop): let a = topmost terminal on stack, b = current input symbol. if a <· b then SHIFT (push b); else if a = b then SHIFT (push b); else if a ·> b then REDUCE (scan left to find the nearest pair of consecutive terminals p and q on the stack with p <· q; the symbols between p and q form the handle; replace that substring by its LHS); else error. (Meaning of symbols: SHIFT pushes the input symbol; REDUCE replaces a handle by a nonterminal.)

Worked examples

Example 1 — build FirstVT/LastVT and precedence relations. Grammar: E -> E + E | E * E | ( E ) | id. Terminals: +, *, (, ), id, and end-marker $. Step 1: compute FirstVT(E) and LastVT(E).

  • From E -> id, add id to FirstVT(E) and to LastVT(E).
  • From E -> ( E ), add ( to FirstVT(E) and ) to LastVT(E).
  • Recursions via E -> E + E and E -> E * E do not introduce new terminal starters or enders. So: FirstVT(E) = { id, ( }, LastVT(E) = { id, ) }.

Step 2: apply table rules to productions.

  • From E -> E + E: for every a in LastVT(E) = {id, )} set a ·> + (so id ·> + and ) ·> +). For every b in FirstVT(E) = {id, (} set + <· b (so + <· id, + <· ().
  • From E -> E * E: similarly set id ·> *, ) ·> *, and * <· id, * <· (.
  • From E -> ( E ): set ( <· id, ( <· ((since FirstVT(E) has(), and id ·> ), )·>)(from LastVT(E)); and set( = )` (from the equality rule with one nonterminal between them).
  • From E -> id: no table entries added here except that id is terminal itself.

Step 3: add $ relations using FirstVT and LastVT of start symbol E: $ <· id, $ <· (; and id ·> $, ) ·> $; and $ = $.

At this point some pairs such as + vs * may be undefined by grammar rules above. That means the grammar, as written, does not determine precedence between + and * solely by the mechanical rules. In practice we assign precedences: declare * has higher precedence than + and both are left-associative. This gives additional entries + <· * and * ·> +, and for left-associativity set + ·> + and * ·> * (so when same operator meets, reduce). After filling these, you get a full table usable by the parser.

Example 2 — parse input id + id * id using the completed table (show stack/input steps). Use $ as end marker. The table decisions used (after we added + <· *) are shown. Initial: Stack: [$] Input: id + id * id $

  1. Compare $ and id: $ <· id → SHIFT. Stack: [$ id] Input: + id * id $
  2. Top terminal id vs +: id ·> + → REDUCE. Reduce id → E. Stack: [$ E] Input: + id * id $
  3. Top terminal $ (nearest terminal on stack) vs +: $ <· + → SHIFT. Stack: [$ E +] Input: id * id $
  4. + vs id: + <· id → SHIFT. Stack: [$ E + id] Input: * id $
  5. id vs *: id ·> * → REDUCE. Reduce id → E. Stack: [$ E + E] Input: * id $
  6. Compare topmost terminal + vs *: from our precedence assignment + <· * → SHIFT. Stack: [$ E + E *] Input: id $
  7. * vs id: * <· id → SHIFT. Stack: [$ E + E * id] Input: $
  8. id vs $: id ·> $ → REDUCE. Reduce id → E. Stack: [$ E + E * E] Input: $
  9. Now top terminal * vs $: * ·> $ → REDUCE. Pop handle E * E and reduce to E. Stack: [$ E + E] Input: $
  10. Now + vs $: + ·> $ → REDUCE. Pop handle E + E and reduce to E. Stack: [$ E] Input: $
  11. $ vs $: $ = $ → accept when stack is [$ E] and input is $ (or apply final reduction to start symbol if needed). Final: input accepted; parse corresponds to usual precedence * before +.

This step-by-step trace is the level of detail expected in exams. Note where we inserted extra precedence (+ <· *) — that was a language design decision to fill an otherwise undefined table cell.

Common mistakes

  • Not adding $ relations ($ <· a and a ·> $) — leads to parser stuck at end.
  • Assuming the grammar will always give a complete table: many grammars leave some pairs undefined; you must either declare the grammar is not operator-precedence or supply precedence/associativity manually.
  • During reduction step, incorrectly locating the left boundary of the handle: you must pop until you find a left terminal t such that t <· u where u is the first terminal right of the popped region.

For your exam

Types of questions you will get and what full-marks answers include:

  • Definitions: state exactly what operator-precedence parsing is, and the formal conditions for operator-precedence grammars. Mention no ε and no adjacent nonterminals.
  • Derivations: show algorithm to compute FirstVT and LastVT and prove closure steps (show iterations until fixed point).
  • Table construction: given a grammar, list FirstVT/LastVT sets, show each application of the three table rules to specific productions, show final table, mention any undefined cells and state whether grammar is operator-precedence or not (or how you would resolve by specifying precedence/associativity).
  • Parsing trace: show stack/input table with exact SHIFT/REDUCE decisions and the relation used at every step; show final acceptance or error.
  • Short notes: compare with shift-reduce/LR parsing (mention that operator-precedence is weaker but simpler, and refer to LR parsers like SLR/LALR in the course list).

Full-marks answers must be precise: give sets, show every table entry derivation, and show reduction handles' boundaries.

Quick check

  1. Define FirstVT(A) in one sentence.
  2. What three precedence relations does operator-precedence parsing use?
  3. Why is $ required and what two relations involving $ are normally set?

Answers: FirstVT(A) = set of terminals that can appear as the first terminal in some string derived from A; the relations are <· (less), = (equal), and ·> (greater); and $ is the input-end marker, with $ <· a and a ·> $ for all terminals a ≠ $.

(Reviewer notes: where I was unsure, I flagged that some operator pairs may remain undefined by the mechanical rules and that languages often need explicit precedence/associativity to fill them — verify the exact closure rules wording for FirstVT/LastVT against your preferred textbook.)

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?