The idea: a grammar can give one string two meanings

A grammar says which strings belong to a language. A parser does more: it builds a parse tree that shows how the string was made, and later stages read the meaning from that tree. If a grammar lets one string have two different trees, the string has two meanings. Such a grammar is ambiguous. With E → E + E | E * E | id the string id + id * id has two trees. With id = 2, 3, 4 one tree computes 2 + (3 * 4) = 14, the other (2 + 3) * 4 = 20.

Two parse trees for id + id * id under E → E + E | E - E | E * E | id. Tree 1 has E → E + E at the root and E → E * E under its right child; its value is 2 + (3 * 4) = 14. Tree 2 has E → E * E at the root and E → E + E under its left child; its value is (2 + 3) * 4 = 20. The leaves of both read id + id * id.
Same leaves, same grammar, two shapes: the lower operator is computed first, so the two trees give 14 and 20.

This page derives each tree step by step, counts the trees, evaluates them, and then shows the two standard fixes: rewrite the grammar in levels, or state a rule such as "else goes to the nearest if".

Grammars and derivations

A grammar has terminals (the tokens: id, +, if …), nonterminals (names for parts: E, S), a start symbol, and productions such as E → E + E. A derivation starts with the start symbol. Each step picks one nonterminal and replaces it by the right side of one of its productions. Every string on the way is a sentential form. When only terminals are left, the string is derived: it is in the language.

Leftmost and rightmost derivations

When a form has several nonterminals, any of them may be replaced next. Two fixed orders are useful. A leftmost derivation always replaces the leftmost nonterminal; a rightmost derivation always replaces the rightmost one. For tree 1 of id + id * id:

stepleftmostrightmost
0EE
1E + EE + E
2id + EE + E * E
3id + E * EE + E * id
4id + id * EE + id * id
5id + id * idid + id * id

The order differs, the productions used are the same, and both take 5 steps. The canvas numbers each node ①, ②, … in the order it was expanded, so the two orders can be compared on one tree (Demo: leftmost vs rightmost, same tree). A top-down parser such as LL(1) builds a leftmost derivation; a bottom-up parser such as LR builds a rightmost derivation in reverse.

Parse trees

A parse tree keeps which production expanded which nonterminal and forgets the order. The root is the start symbol. Each inner node is a nonterminal, and its children are the right side of the production used for it. The leaves are terminals; read left to right they spell the input. This string of leaves is the yield. On the canvas every leaf has its own column, in input order, so the yield reads left to right.

  • A derivation takes one step per inner node: 5 for each tree above, 8 for the E/T/F tree below.
  • Each parse tree has exactly one leftmost derivation and exactly one rightmost derivation.
  • So "two parse trees", "two leftmost derivations" and "two rightmost derivations" all say the same thing.

Ambiguity

A grammar is ambiguous if at least one string has two or more parse trees. One such string is enough. The grammar E → E + E | E - E | E * E | id fails twice:

inputtree 1tree 2what is not fixed
id + id * id (2, 3, 4)2 + (3 * 4) = 14(2 + 3) * 4 = 20precedence: which operator binds tighter
id - id - id (8, 3, 2)(8 - 3) - 2 = 38 - (3 - 2) = 7associativity: which way equal operators group

(Demos: two trees for id + id * id; two trees for id - id - id.) Ambiguity belongs to the grammar, not to the language: the same strings can have an unambiguous grammar, as the next section shows.

Fixing it with levels: E, T, F

The usual fix gives each precedence level its own nonterminal:

E → E + T | E - T | T      (a sum of terms)
T → T * F | F              (a product of factors)
F → ( E ) | id             (one factor)

Precedence comes from the levels. A * can only appear inside a T, and a T is a whole operand of +. So * always sits lower in the tree and is computed first. Associativity comes from the side of the recursion. In E → E - T the recursion is on the left, and the right operand is a single T, so 8 - 3 - 2 can only group as (8 - 3) - 2. Recursion on the right (E → T - E) would group from the right, as wanted for powers.

The only parse tree of id + id * id under the E/T/F grammar. E → E + T at the root; the left E goes E → T → F → id; the right T is T → T * F, with T → F → id and F → id below it. A band on the left labels the levels E (sums), T (products) and F (factors). The value is 2 + (3 * 4) = 14.
With one nonterminal per level, the * can only be built inside a T, below the +, so there is one tree: 14.
grammarid + id * idid - id - idleftmost steps
E → E + E | E - E | E * E | id2 trees: 14, 202 trees: 3, 75 and 5
E / T / F levels1 tree: 141 tree: 38 and 9

The price is a taller tree: the unit steps E → T → F → id add nodes, so the derivation of id + id * id grows from 5 to 8 steps (Demos: E/T/F levels give one tree; E/T/F is left-associative). The left recursion in E → E + T is fine for this grammar, but a top-down parser cannot use it as it is; LL(1) Parsing shows how to remove it. The tree itself, once built, is what Expression Trees evaluates and traverses.

The dangling else

Statements have the same problem. With

S → if c then S | if c then S else S | s

the string if c then if c then s else s has two trees. In tree 1 the else belongs to the inner if; in tree 2 it belongs to the outer if. With real code the two trees run different statements when the first condition is false.

Two parse trees for if c then if c then s else s. In tree 1 the root is S → if c then S, and the inner S → if c then S else S holds the else, so the else belongs to the inner if. In tree 2 the root is S → if c then S else S, so the else belongs to the outer if, and the inner S is if c then s.
The same eight tokens, two trees: the else hangs from the inner if (tree 1, the rule languages use) or from the outer if (tree 2).

C, Java and Pascal choose tree 1: an else belongs to the nearest if that has no else yet. There are two ways to get it:

  • Keep the grammar and add the rule. An LR parser meets a shift/reduce conflict at else; shifting the else gives the nearest-if tree. Yacc and Bison shift by default (see LR Parsing).
  • Rewrite the grammar. Split statements into matched ones M (every if has its else) and unmatched ones U. Between then and else only a matched statement may stand, so the else cannot jump over an inner if.
S → M | U
M → if c then M else M | s
U → if c then S | if c then M else U

This grammar gives the string one tree, the nearest-if one, in 6 leftmost steps instead of 4 (Demos: dangling else: two trees; matched/unmatched).

Can a program check a grammar?

Not in general: whether a context-free grammar is ambiguous is undecidable. Some languages are even inherently ambiguous: every grammar for them is ambiguous. In practice two checks help. A parser generator for LL(1) or LR(1) reports a conflict for every ambiguous grammar (and for some unambiguous ones too). For one given string, a general parser such as CYK or Earley finds every tree, which is how this page counts them.

See also Probabilistic CYK, which resolves a PP-attachment ambiguity by comparing the probabilities of the two trees.

What the page leaves out

Empty (ε) productions, precedence declarations such as %left '+' in a parser generator, abstract syntax trees (the parse tree without the unit nodes), the proof that ambiguity is undecidable, inherently ambiguous languages such as aibjck with i = j or j = k, and ambiguity in natural language (see CYK Parsing for a sentence with two trees).

On the mind map

Open the Java & the JVM mind mapJava & the JVMFrom source to bytecode: translate first, or while runningFrom source to bytecodeStartup and class loading: what happens before main()Startup and class loadingJIT compilers: compile hot code using profilesJIT compilersMemory and GC: find and free unreachable objectsMemory and GCCollections: how java.util stores keysCollectionsThreads and memory model: Java threads on real coresThreads and memory modelSpring framework: a container builds your objectsSpring frameworkCompiler vs interpreterCompiler vs interpretercompile once ahead, or decode every runTiny compilerTiny compilerlexer, parser, code generator, VMThree-address codeThree-address codeFold + copy prop make code dead: 15→13Hindley-Milner inferenceHindley-Milner inferenceEquations per node, unify into SStatic vs Dynamic ScopingStatic vs Dynamic ScopingWritten-in vs called-from decides xLL(1) ParsingLL(1) ParsingStack top + one token pick the productionGrammar ambiguityTwo parse trees = two meaningsLR parsingLR parsingShift tokens, reduce handles bottom upjavacjavacsource to type-checked .class bytecodeLambdas and invokedynamicLambdas and invokedynamicfirst call bootstraps, then links onceOpen the Java & the JVM mind mapJava & the JVMtranslate first, or while runningFrom source to bytecodeCompiler vs interpreterCompiler vs interpretercompile once ahead, or decode every runTiny compilerTiny compilerlexer, parser, code generator, VMThree-address codeThree-address codeFold + copy prop make code dead: 15→13Hindley-Milner inferenceHindley-Milner inferenceEquations per node, unify into SStatic vs Dynamic ScopingStatic vs Dynamic ScopingWritten-in vs called-from decides xLL(1) ParsingLL(1) ParsingStack top + one token pick the productionGrammar ambiguityTwo parse trees = two meaningsLR parsingLR parsingShift tokens, reduce handles bottom upjavacjavacsource to type-checked .class bytecodeLambdas and invokedynamicLambdas and invokedynamicfirst call bootstraps, then links once
This page on the Java & the JVM mind map · 37 pages in 7 branches · open it to see the whole map and test yourself in recall mode.