Algorithm Search⌘K

Proofs: Canonical LR(1) parsing

These are the human proofs of Canonical LR(1) parsing, at full length.

With a table free of conflicts, the canonical LR(1) parser stops after O(n) steps on every input full

This proof shows: time.worst, space.extra, time.build, space.table.

We use the notation and Lemmas 1 to 4 and Theorem 2 of the correctness proof. The grammar GG is fixed, has no useless symbols, and its table has no conflict. Let NN be the number of states, ∣V∣|V| the number of nonterminals, and mG≥1m_G \ge 1 the largest length of a right side. A step is one pass through the loop of lines L19 to L24.

Lemma A (a run on a sentence). Let ww be any input, and let the parser make at least tt steps on it. Let uu be the input read before step tt and aa the next symbol then. There is a sentence w′∈L(G)w' \in L(G) that begins with uu followed by aa (or w′=uw' = u if a=$a = \$) such that the run on w′w' begins with the same tt steps.

Proof. Step tt uses an entry of ACTION[st(γ),a][\mathrm{st}(\gamma), a], where γ\gamma is the string of stack symbols. The entry comes from an item of st(γ)\mathrm{st}(\gamma), which by Lemma 4 is valid for γ\gamma through S′⇒rm∗δAx⇒rmδαβxS' \Rightarrow^*_{rm} \delta A x \Rightarrow_{rm} \delta\alpha\beta x with γ=δα\gamma = \delta\alpha. By Lemma 3, γ⇒∗u\gamma \Rightarrow^* u, and β\beta derives some terminal string yy, so w′=uyxw' = u y x is a sentence. For a shift, β\beta begins with aa, so yy does; for a reduce or accept, β=ε\beta = \varepsilon and aa is the first symbol of x$x\$. The first tt steps read only uu and look only at symbols of uu and at aa, so they are the same on w′w'. □\square

Lemma B (small parse trees). Let TT be the unique parse tree of a sentence (unique by Theorem 2). A subtree of TT whose yield is empty has fewer than cε=(mG+1)∣V∣c_\varepsilon = (m_G + 1)^{|V|} nodes. A subtree with a yield of length ℓ≥1\ell \ge 1 has at most c ℓc \, \ell inner nodes, where c=2∣V∣(1+mGcε)c = 2|V|(1 + m_G c_\varepsilon).

Proof. If a path in a subtree with empty yield had two nodes with the same label AA, replacing the subtree of the upper one by the subtree of the lower one would give a second parse tree of the same sentence. So each path has at most ∣V∣|V| inner nodes, each with at most mGm_G children, and the subtree has at most ∑i≤∣V∣mGi<cε\sum_{i \le |V|} m_G^i < c_\varepsilon nodes.

For a yield of length ℓ≥1\ell \ge 1, the spans of the nodes with a nonempty yield form a laminar family of nonempty intervals of ℓ\ell positions, which has at most 2ℓ−12\ell - 1 members. Two nodes with the same nonempty span are an ancestor and a descendant, and every node between them has that span too. If two of them had the same label, removing the part between them would give a second tree of the same sentence. So each span has at most ∣V∣|V| nodes, and there are at most (2ℓ−1)∣V∣(2\ell - 1)|V| nodes with a nonempty yield. Every other inner node lies in a maximal subtree with empty yield, whose root is a child of a node with a nonempty yield. There are at most mG(2ℓ−1)∣V∣m_G (2\ell - 1)|V| such subtrees, each with fewer than cεc_\varepsilon nodes. The total is at most (2ℓ−1)∣V∣(1+mGcε)≤c ℓ(2\ell - 1)|V|(1 + m_G c_\varepsilon) \le c\,\ell. □\square

Lemma C (short runs of empty symbols). At each step on any input, a block of consecutive stack symbols that all derive ε\varepsilon in the run (their part of uu in Lemma 3 is empty) has fewer than NN symbols.

Proof. Let the stack symbols be X1⋯XmX_1 \cdots X_m, and let Xk+1,…,Xk+rX_{k+1}, \ldots, X_{k+r} be such a block. By Lemma 3, the input read after XjX_j was pushed is the part of uu derived from Xj+1⋯XmX_{j+1} \cdots X_m. So no shift happened between the push of XkX_{k} (or the start, if k=0k = 0) and the push of Xk+rX_{k+r}, and the lookahead bb stayed the same. Let τj\tau_j be the time just after the push of Xk+jX_{k+j}, for 0≤j≤r0 \le j \le r. Between τj\tau_j and the end, the stack never becomes shorter than k+jk + j, because Xk+jX_{k+j} is still on it.

Suppose that the top states at τj\tau_j and τj′\tau_{j'} are the same state qq, for some j<j′j < j'. From τj\tau_j on, as long as no shift happens and the stack stays above height k+jk + j, each action depends only on the states above height k+jk + j, on qq, and on bb. So from τj′\tau_{j'} the parser repeats, one level higher, the steps it made from τj\tau_j, reaches the top state qq again without a shift, and does so forever. Take the sentence w′w' of Lemma A for the current step: its run agrees with this run up to the current step and has the same lookahead bb at this position, so it is infinite. This contradicts Theorem 2. Hence the r+1r + 1 top states at τ0,…,τr\tau_0, \ldots, \tau_r are distinct, and r<Nr < N. □\square

Theorem (time and space of the parse). On an input of length nn, the parser stops after at most (n+1)+c n+cε(n+1)(N+1)=O(n)(n + 1) + c \, n + c_\varepsilon (n + 1)(N + 1) = O(n) steps. The stack never holds more than n+1+(n+1)N=O(n)n + 1 + (n + 1) N = O(n) states.

Proof. Take any step tt, with stack symbols X1⋯XmX_1 \cdots X_m, input read uu, and the sentence w′w' of Lemma A with its tree T′T'. Since the run on w′w' begins with the same tt steps, Theorem 2 says that each reduction so far made an inner node of T′T', and that these nodes are exactly the inner nodes of the subtrees of T′T' rooted at X1,…,XmX_1, \ldots, X_m. Their yields split uu. At most ∣u∣≤n|u| \le n of the XjX_j have a nonempty yield, and by Lemma C the others form at most ∣u∣+1|u| + 1 blocks of fewer than NN symbols each. So m≤n+(n+1)Nm \le n + (n + 1) N, plus the state 0 at the bottom, which bounds the stack. By Lemma B, the subtrees with nonempty yields have at most c ∣u∣≤c nc\,|u| \le c\,n inner nodes in total, and the others at most cεmc_\varepsilon m. There are at most nn shifts, because $\$ is never shifted, and at most one accept, so tt is bounded by the number in the statement. This bound does not depend on tt, so the run is finite. A step does O(1)O(1) work, apart from popping at most mGm_G states, so the time is O(n)O(n) for the fixed grammar. ■\blacksquare

The constant in O(n)O(n) grows with NN, which can be exponential in ∣G∣|G|. For a sentence the count is smaller: by Theorem 2 the steps are the nn shifts, the inner nodes of the tree, and the accept, and by Lemma B there are at most c n+cεc\,n + c_\varepsilon inner nodes.

The cost of the construction. Let MM be the number of LR(1) items. A production A→αA \to \alpha has 1+∣α∣1 + |\alpha| dot positions, so M≤∣G∣(σ+1)M \le |G|(\sigma + 1). A CLOSURE puts each of at most MM items on the work list once. For an item [A→α⋅Bβ,a][A \to \alpha \cdot B\beta, a] it computes FIRST(βa)(\beta a) in O(∣β∣ σ)O(|\beta|\,\sigma) time from the FIRST sets, which are computed once in advance, and then for each of at most σ+1\sigma + 1 lookaheads it scans the productions of BB, O(∣G∣)O(|G|) work. So one CLOSURE takes O(M∣G∣σ)=O(∣G∣2σ2)O(M |G| \sigma) = O(|G|^2 \sigma^2) time. A state has at most ∣G∣|G| symbols after a dot; for each, line L17 forms the kernel in O(M)O(M) time and closes it, and line L6 looks the set up in a trie of flag vectors of length MM, in O(M)O(M) time. A state therefore costs O(∣G∣3σ2)O(|G|^3 \sigma^2), and lines L1 to L8 cost O(N∣G∣3σ2)O(N |G|^3 \sigma^2). Lines L9 to L13 look at each item of each state once, O(NM)O(N M) time. The ACTION table has N(σ+1)N(\sigma + 1) entries and the GOTO table N∣V∣≤N∣G∣N |V| \le N |G| entries, so the tables take O(N(∣G∣+σ))O(N(|G| + \sigma)) space.

The canonical LR(1) parser outputs only rightmost derivations, and with a table free of conflicts it parses every sentence full

This proof shows: correctness.

We use the augmented grammar G′G' with S′→SS' \to S and the end marker $\$. The item sets are the list CC built by lines L1 to L8, and TT is the transition function of line L7. For a string γ=X1⋯Xm\gamma = X_1 \cdots X_m of grammar symbols, write st(γ)\mathrm{st}(\gamma) for the state reached from state 0 by following TT on X1,…,XmX_1, \ldots, X_m, when all these transitions are defined. FIRST(θ)(\theta) denotes the set computed from the FIRST sets of the symbols, as in line L15. For every grammar it contains each terminal that begins a terminal string derived from θ\theta: the fixpoint adds a terminal for each way it can begin such a string. A derivation step is rightmost when it rewrites the rightmost nonterminal of the form.

Lemma 1 (shape of items). If the item [A→α⋅β,a][A \to \alpha \cdot \beta, a] is in st(γ)\mathrm{st}(\gamma), then α\alpha is a suffix of γ\gamma. If moreover α=α′X\alpha = \alpha' X, then [A→α′⋅Xβ,a][A \to \alpha' \cdot X \beta, a] is in st(γ′)\mathrm{st}(\gamma'), where γ=γ′X\gamma = \gamma' X.

Proof. By induction on ∣γ∣|\gamma|. The items of a CLOSURE are the given items and items with the dot at the left end, which have α=ε\alpha = \varepsilon. For γ=ε\gamma = \varepsilon the state is I0I_0, whose only item that is not added by closure is [S′→⋅S,$][S' \to \cdot S, \$], so every item has α=ε\alpha = \varepsilon. For γ=γ′X\gamma = \gamma' X, the state is GOTO(st(γ′),X)(\mathrm{st}(\gamma'), X) by line L5. By line L17 an item with α≠ε\alpha \ne \varepsilon in it comes from an item [A→α′⋅Xβ,a][A \to \alpha' \cdot X \beta, a] of st(γ′)\mathrm{st}(\gamma') with α=α′X\alpha = \alpha' X. By the induction hypothesis α′\alpha' is a suffix of γ′\gamma', so α\alpha is a suffix of γ\gamma. □\square

Lemma 2 (validity). If the item [A→α⋅β,a][A \to \alpha \cdot \beta, a] is valid for γ\gamma, then st(γ)\mathrm{st}(\gamma) is defined and contains the item.

Proof. The item is valid through a rightmost derivation S′⇒rm∗δAx⇒rmδαβxS' \Rightarrow^*_{rm} \delta A x \Rightarrow_{rm} \delta\alpha\beta x with γ=δα\gamma = \delta\alpha and aa the first symbol of x$x\$. Let rr be the number of steps of S′⇒rm∗δAxS' \Rightarrow^*_{rm} \delta A x. We use induction on the pair (r,∣α∣)(r, |\alpha|) in lexicographic order.

Case α=α′X\alpha = \alpha' X. The item [A→α′⋅Xβ,a][A \to \alpha' \cdot X\beta, a] is valid for δα′\delta\alpha' through the same derivation, with the same rr and a shorter α′\alpha'. By the induction hypothesis it is in st(δα′)\mathrm{st}(\delta\alpha'). So XX follows a dot in that state, line L7 defines TT on XX, and line L17 puts [A→α⋅β,a][A \to \alpha \cdot \beta, a] into GOTO(st(δα′),X)=st(γ)(\mathrm{st}(\delta\alpha'), X) = \mathrm{st}(\gamma).

Case α=ε\alpha = \varepsilon and r=0r = 0. Then δAx=S′\delta A x = S', so γ=ε\gamma = \varepsilon, A=S′A = S', x=εx = \varepsilon and a=$a = \$. The only production of S′S' is S′→SS' \to S, and [S′→⋅S,$][S' \to \cdot S, \$] is in I0=st(ε)I_0 = \mathrm{st}(\varepsilon) by line L1.

Case α=ε\alpha = \varepsilon and r≥1r \ge 1. Here γ=δ\gamma = \delta. Look at the step of the derivation that created this occurrence of AA: a step δ′By⇒rmδ′ηAθy\delta' B y \Rightarrow_{rm} \delta' \eta A \theta y by a production B→ηAθB \to \eta A \theta, where yy is a terminal string because the step is rightmost. After this step, a rightmost derivation rewrites the nonterminals right of AA before AA itself, and it does not touch the symbols left of AA until AA is rewritten. So the derivation has the form

S′⇒rm∗δ′By⇒rmδ′ηAθy⇒rm∗δ′ηAzy=δAx,S' \Rightarrow^*_{rm} \delta' B y \Rightarrow_{rm} \delta'\eta A \theta y \Rightarrow^*_{rm} \delta' \eta A z y = \delta A x,

with θ⇒∗z\theta \Rightarrow^* z, x=zyx = zy and δ=δ′η\delta = \delta'\eta. The item [B→η⋅Aθ,b][B \to \eta \cdot A\theta, b], with bb the first symbol of y$y\$, is valid for δ′η=γ\delta'\eta = \gamma through a derivation of S′⇒rm∗δ′ByS' \Rightarrow^*_{rm} \delta' B y with fewer than rr steps. By the induction hypothesis, it is in st(γ)\mathrm{st}(\gamma). Now aa is the first symbol of zy$zy\$. If z≠εz \ne \varepsilon, then aa begins a string derived from θ\theta; if z=εz = \varepsilon, then θ⇒∗ε\theta \Rightarrow^* \varepsilon and a=ba = b. In both cases a∈a \in FIRST(θb)(\theta b). So line L15 adds [A→⋅β,a][A \to \cdot\beta, a] for the production A→βA \to \beta to the closure that forms st(γ)\mathrm{st}(\gamma). □\square

Lemma 3 (invariant of the driver). At each test of line L20, let the stack hold the states s0s1⋯sms_0 s_1 \cdots s_m and let uu be the part of ww read so far. Then s0=0s_0 = 0, there are symbols X1,…,XmX_1, \ldots, X_m with sj=T[sj−1,Xj]s_j = T[s_{j-1}, X_j] for each jj, so that sj=st(X1⋯Xj)s_j = \mathrm{st}(X_1 \cdots X_j), and the reductions output so far, applied in reverse order as rewriting steps, derive uu from X1⋯XmX_1 \cdots X_m. In any form of this derivation followed by the rest vv of ww, each step rewrites the rightmost nonterminal.

Proof. By induction on the number of steps. At the start, m=0m = 0, u=εu = \varepsilon, and there are no reductions. A shift on the terminal aa pushes T[sm,a]T[s_m, a] (line L10 and line L21), so Xm+1=aX_{m+1} = a and uu grows by aa; the derivation is unchanged. A reduce by A→βA \to \beta is in the table because some item [A→β⋅,a][A \to \beta \cdot, a] is in sms_m (line L11). By Lemma 1, β=Xm−∣β∣+1⋯Xm\beta = X_{m-|\beta|+1} \cdots X_m, and sm−∣β∣s_{m-|\beta|} holds [A→⋅β,a][A \to \cdot \beta, a], so T[sm−∣β∣,A]T[s_{m-|\beta|}, A] is defined and line L22 pushes it. The new symbols are X1⋯Xm−∣β∣AX_1 \cdots X_{m-|\beta|} A, and the new first step rewrites this AA to β\beta. Every symbol right of this AA, in the form followed by vv, is a terminal of vv, so the step is rightmost. The old derivation follows it. □\square

Theorem 1 (soundness). If LR-PARSE(w)(w) returns an output, the output, read backwards, is a rightmost derivation S⇒rm∗wS \Rightarrow^*_{rm} w. This holds for every grammar, also when conflicts were resolved in any way.

Proof. Accept happens at line L23, so sms_m holds [S′→S⋅,$][S' \to S \cdot, \$] and the next symbol is $\$, so u=wu = w. By Lemma 1, Xm=SX_m = S and sm−1s_{m-1} holds [S′→⋅S,$][S' \to \cdot S, \$]. This item is the kernel of I0I_0, it is not added by any closure because S′S' is on no right side, and it is not the kernel of any GOTO, whose kernels have the dot after a symbol. So sm−1=0s_{m-1} = 0, which happens only at the bottom of the stack, because every pushed state is a GOTO and does not hold this item. Hence m=1m = 1, and Lemma 3 says that the output, backwards, derives ww from SS by rightmost steps. □\square

Theorem 2 (completeness). Assume that no entry of ACTION got two actions. If w∈L(G)w \in L(G) and TwT_w is a parse tree of ww with root SS, then LR-PARSE(w)(w) accepts, and the reductions it outputs are the inner nodes of TwT_w in postorder. In particular ww has only one parse tree, so GG is unambiguous.

Proof. Add a root S′S' above TwT_w. The events of the tree are its terminal leaves and its inner nodes other than S′S', in postorder. Make a shift event for each terminal leaf and a reduce event for each inner node, and a final accept event. We show by induction that the tt-th step of the parser is the tt-th event.

Before an event ee, call a node done if it comes before ee in postorder. Let PP be the set of nodes that are not done but have a done descendant or are on the path from the root to ee. These are exactly the proper ancestors of ee, together with ee itself if ee is an inner node. For each node N∈PN \in P with production A→αβA \to \alpha\beta, let α\alpha be its children that are done, which come before its children that are not done. Let γ\gamma be the concatenation of these α\alpha, from the root down. The induction hypothesis is that the stack symbols are X1⋯Xm=γX_1 \cdots X_m = \gamma and that the input read is the yield of the done nodes, which is a prefix uu of ww.

The tree gives, for each N∈PN \in P with A→α⋅βA \to \alpha \cdot \beta as above, a rightmost derivation S′⇒rm∗δAx⇒rmδαβxS' \Rightarrow^*_{rm} \delta A x \Rightarrow_{rm} \delta\alpha\beta x. Expand the nodes of the path from the root to NN, and before each of them expand fully all the subtrees to the right of the path. Then δ\delta is the concatenation of the done children of the ancestors of NN, xx is the yield of the tree to the right of NN, and δα\delta\alpha is a prefix of γ\gamma. So the item [A→α⋅β,a][A \to \alpha \cdot \beta, a], with aa the first symbol of x$x\$, is valid for δα\delta\alpha.

  • If ee is a leaf with terminal aa, its parent NN is the lowest node of PP, and it has A→α⋅aβ′A \to \alpha \cdot a \beta' with δα=γ\delta\alpha = \gamma. The next input symbol is aa, because the done leaves are exactly the leaves before ee. The item is valid for γ\gamma, so by Lemma 2 it is in st(γ)\mathrm{st}(\gamma), and line L10 put a shift into ACTION[st(γ),a][\mathrm{st}(\gamma), a]. With no conflict this is the only action, so the parser shifts aa, and the hypothesis holds before the next event.
  • If ee is an inner node with production A→βA \to \beta, all its children are done, so ee is the lowest node of PP with the item [A→β⋅,a][A \to \beta \cdot, a], valid for γ=δβ\gamma = \delta\beta. Here aa is the first symbol after the yield of ee, which is the next input symbol. By Lemma 2 and line L11, ACTION[st(γ),a][\mathrm{st}(\gamma), a] is reduce A→βA \to \beta, and it is the only action. The parser pops the ∣β∣|\beta| symbols of β\beta and pushes AA, which is the stack of the next event, where ee is done.
  • If all nodes but S′S' are done, then γ=S\gamma = S and the input read is ww, and [S′→S⋅,$][S' \to S \cdot, \$] is valid for SS. By Lemma 2 and line L12, the action on $\$ is accept.

So the parser accepts after the events of TwT_w, and outputs its inner nodes in postorder. The parser is deterministic and its run depends only on ww. Two different parse trees of ww would give two different postorders, so they would give two different runs, which is impossible. □\square

Lemma 4 (state items are valid). If GG has no useless symbols, every item of st(γ)\mathrm{st}(\gamma) is valid for γ\gamma.

Proof. When every nonterminal derives a terminal string, the computed FIRST(θ)(\theta) is exactly the set of terminals that begin a terminal string derived from θ\theta: each terminal that the fixpoint adds begins a sentential form derived from θ\theta, and the rest of that form derives a terminal string. We use induction on the order in which the construction adds items. The item [S′→⋅S,$][S' \to \cdot S, \$] is valid for ε\varepsilon. A GOTO item [A→αX⋅β,a][A \to \alpha X \cdot \beta, a] of st(γX)\mathrm{st}(\gamma X) comes from [A→α⋅Xβ,a][A \to \alpha \cdot X\beta, a] of st(γ)\mathrm{st}(\gamma), which is valid for γ\gamma; the same derivation makes the new item valid for γX\gamma X. A closure item [B→⋅η,b][B \to \cdot\eta, b] comes from [A→α⋅Bβ,a][A \to \alpha \cdot B \beta, a], valid for γ\gamma through S′⇒rm∗δAx⇒rmδαBβxS' \Rightarrow^*_{rm} \delta A x \Rightarrow_{rm} \delta \alpha B \beta x, and b∈b \in FIRST(βa)(\beta a). Take a terminal string yy with β⇒∗y\beta \Rightarrow^* y such that bb is the first symbol of yx$yx\$; it exists by the exactness of FIRST. Then

S′⇒rm∗δAx⇒rmδαBβx⇒rm∗δαByx⇒rmδαηyxS' \Rightarrow^*_{rm} \delta A x \Rightarrow_{rm} \delta\alpha B \beta x \Rightarrow^*_{rm} \delta\alpha B y x \Rightarrow_{rm} \delta\alpha\eta y x

is rightmost, because β\beta lies right of BB. So [B→⋅η,b][B \to \cdot\eta, b] is valid for δα=γ\delta\alpha = \gamma. □\square

Theorem 3 (rejection). Assume that no entry of ACTION got two actions and that GG has no useless symbols. If w∉L(G)w \notin L(G), LR-PARSE(w)(w) returns error after finitely many steps.

Proof. By Theorem 1 the parser never accepts ww. The theorem of the complexity proof, which uses only Lemmas 1 to 4 and Theorem 2, shows that on every input the run stops after O(n)O(n) steps. A run that stops without accepting ends at line L24. ■\blacksquare

Theorems 1, 2 and 3 together say: with a table free of conflicts, for a grammar without useless symbols, LR-PARSE(w)(w) returns a rightmost derivation of ww when w∈L(G)w \in L(G) and error otherwise. Theorem 2 alone shows that a grammar with such a table is unambiguous.

Back to Canonical LR(1) parsing