Notation
The symbols and conventions the tools use. They follow the lecture slides; each section cites the slides it comes from.
On this page
Lexical analysis
Sets, strings, and languages
An alphabet Σ is a finite set of symbols. A language over Σ is a set of strings of symbols drawn from Σ.
| Concept | Written | Example |
|---|---|---|
| Alphabet | Σ | Σ = { 0, 1 } |
| String | double quotes | "if", "1110" |
| Empty string | "" in a set; ε in an RE or on an edge | L(ε) = { "" } |
| Empty language | ɸ in an RE; { } as a set | L(ɸ) = { } |
| RE literal | single quotes | 'if', '\t', ' ' |
| Language of an RE | L(R) | L('1' '0'*) |
| Language of a machine | L(M) | L(M) = { "1" } |
Sets of strings are written with spaces inside the braces, and … marks a set that goes on:
Regular expressions
Each clause of the inductive definition, with the language it denotes. A and B stand for any regular expressions.
| Clause | RE | Language |
|---|---|---|
| Basis | ||
| Atomic | 'c' | L('c') = { "c" } for any c ∈ Σ |
| Empty | ɸ | L(ɸ) = { } |
| Epsilon | ε | L(ε) = { "" } |
| Inductive | ||
| Concatenation | AB | L(AB) = { ab | a ∈ L(A) and b ∈ L(B) } |
| Choice/Alternation | A | B | L(A | B) = { s | s ∈ L(A) or s ∈ L(B) } |
| Iteration (Kleene closure) | A* | L(A*) = { "" } ∪ L(A) ∪ L(AA) ∪ L(AAA) ∪ … |
| Positive closure | A+ | L(A+) = L(A A*) |
| Fixed iteration | An | L(An) = L(A A … A) A repeated n times |
| Also accepted | ||
| Optional | A? | L(A?) = L(A | ε) |
| Any symbol | Σ | L(Σ) = { "c" | c ∈ Σ } |
Writing expressions
- Literals
- 'c', or several characters at once: 'if' abbreviates 'i' 'f', so L('if') = { "if" }. A quoted literal is one unit: 'ab'* means ('a' 'b')*. Inside quotes, \t \n \r \\ \' \" are escapes. Curly quotes ‘ ’ work like '; a double-quoted "if" is read as a literal, with a note.
- Bare symbols
- Any character that is not an operator, a quote, or a space is a symbol by itself, as in (0 | 1)*00. Digits and punctuation are symbols. Spaces only separate; (0|1)*00 is the same expression.
- Names
- A word such as digit refers to a regular definition with that name. A word that names no definition is read as single symbols: abb is a b b, with a note.
- Ranges
- 'A' | … | 'Z' (with … or ...) between single characters is the whole range. Classes such as [a-z] also work.
Operator precedence
- 1* + ? nPostfix operators bind tightest
- 2ABthen concatenation
- 3A | Bthen choice
Parentheses group. Some expressions with the grouping made explicit:
| Written | Means |
|---|---|
| ab* | a (b*) |
| ab | c | (a b) | c |
| a | b*c | a | ((b*) c) |
| 'ab'* | ('a' 'b')* |
| (0 | 1)*00 | ((0 | 1)*) 0 0 |
| digit3+ | ((digit3)+) |
Constructions that follow the two-operand definitions group longer chains from the left: A B C is (A B) C and A | B | C is (A | B) | C.
Regular definitions
A regular definition names an expression so other expressions can use it. Write one per line as name = RE. Lines starting with // are comments. Definitions may come in any order, but a definition may not use itself, directly or through others.
// a non-empty string of digits digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' number = digit digit*
area = digit3 exchange = digit3 phone = digit4 number = '(' area ')' exchange '-' phone
Typing the symbols
Expression fields turn \e, \p, and \S into their symbols as you type, and the buttons under a field insert a symbol at the cursor.
| Symbol | Meaning | Type | Also accepted |
|---|---|---|---|
| ε | Empty string | \e | ϵ |
| ɸ | Empty language | \p | φ ϕ ∅ |
| Σ | Any one symbol of the alphabet | \S | |
| A+ | Positive closure | A+ | A⁺ |
| A3 | Fixed iteration | A^3 | A³ |
| … | Range | ... | … |
Flex patterns
Tools that read flex specifications use flex's own pattern syntax, where most characters stand for themselves and literals need no quotes.
| Pattern | Matches |
|---|---|
| x | the character x |
| \. | the character . (a backslash makes an operator literal) |
| "string" | the characters of string, literally |
| . | any character except newline |
| ^ | the beginning of a line |
| $ | the end of a line |
| [xyz] | one character: x, y, or z (escape - as \-) |
| [^xyz] | any character except x, y, and z |
| [a-z] | one character from a to z |
| r* | Kleene closure |
| r+ | positive closure |
| r? | optional |
| r1r2 | r1 then r2 (concatenation) |
| r1|r2 | r1 or r2 (choice) |
| (r) | grouping |
| r1/r2 | r1 when followed by r2 (trailing context) |
| {d} | the expression defined by d |
| Also accepted | |
| r{n} | exactly n copies of r |
| r{n,} | n or more copies |
| r{n,m} | n to m copies |
Trailing context
The slide prints trailing context as r1 \ r2. Flex, and this site, write it with a slash: r1/r2.
Definitions go in the definitions section, one per line as NAME pattern, and are used in braces:
DIGIT [0-9] LETTER [A-Za-z] ID {LETTER}({LETTER}|{DIGIT})*
Flex takes the longest match, breaks ties in favor of the rule listed first, and copies characters no rule matches to the output. There are no back-references.
Finite automata
A deterministic finite automaton (DFA) M consists of
- an input alphabet Σ,
- a set of states S,
- a start state s0,
- a set of accepting states F ⊆ S, and
- a transition function T : S × Σ → S.
M = (Σ, S, s0, F, T)
T is total: every state has exactly one transition on every symbol. A transition is written s1 →a s2: in state s1, on input 'a', go to state s2.
A nondeterministic automaton (NFA) may have several transitions on one symbol and ε-moves, which change state without reading input. Its states are Q and its transition function returns a set of states:
Δ : Q × (Σ ∪ { ε }) → P(Q)
| At the end of the input | Outcome |
|---|---|
| in an accepting state (for an NFA: able to reach one) | accept |
| in any other state | reject |
| no transition was possible along the way | reject |
“Accepting” and “final” are synonyms. When a drawn DFA has no transition for a symbol, the machine moves to a trap state (or crashes); tools can draw the trap state explicitly.
Diagram legend
Machines read from left to right.
-
State
A circle.
-
Long state name
An ellipse, e.g. a subset-construction state.
-
Start state
An arrow in from nowhere.
-
Accepting state
A double outline. “Final” means the same.
-
Transition
On input a, go from A to B.
-
Several symbols
One edge; its symbols are joined by commas.
-
Self-loop
Drawn above the state.
-
ε-move
Moves without reading input; drawn in violet.
-
Trap state
A dashed outline. Missing transitions lead here; it never accepts.
-
Current state
During a run: filled in amber, with the transition just taken.
State names
| Machine | States are named | Example |
|---|---|---|
| Thompson NFA | Letters A, B, C, … by column from left to right, then top to bottom. After Z come AA, AB, … | (1 | 0)*1 gives A … J |
| Subset-construction DFA | The NFA states it contains, written together in the order they were found. If an NFA name has more than one letter, set notation is used instead: {AA, B}. Tools can also show sorted sets or D0, D1, … | ABCDHI, FGABCDHI, EJGABCDHI |
| Empty subset | ∅. Left out by default (it is the trap state); tools can show it. | ∅ |
| Minimized DFA | The name of the first state in each merged group; the merged states are listed. | S for {S, T} |
| Hand-built | Whatever you type. New states take the next free letter. | S, T, U |
| Relational operators | Numbers, as on the slide. | 0 … 8 |
Transition tables
Rows are states, columns are input symbols in ascending order, and each cell is the next state. Row markers:
- → start state
- ◎ accepting state
- * retract: push back one character (the relational-operator slide). It never means “accepting”.
| State | 0 | 1 |
|---|---|---|
| →S | T | U |
| T | T | U |
| ◎U | T | U |
| State | 0 | 1 | ε |
|---|---|---|---|
| →A | ∅ | {A, B} | ∅ |
| ◎B | ∅ | ∅ | ∅ |
Tokens and lexemes
A token is a syntactic category, such as Identifier or Keyword. A lexeme is the string a token matched. The slides write token–lexeme pairs in two ways, and tools can show either:
| Format | Lexeme | From |
|---|---|---|
| (Identifier, "f") | a string, in double quotes | Lecture reference: Lexical Analysis II |
| <ID,'A'> | in single quotes | Lecture reference: Intro (cont’d): Compiler architecture |
Scanning "f+3 +g" (two spaces) with R = Whitespace | Integer | Identifier | '+'. Pointing at a pair highlights its lexeme. The slide lists the whitespace token as (Whitespace, " "); under maximal munch it matches both spaces.
In inputs, whitespace is drawn visibly: · space, ⇥ tab, ↵ newline, ␍ carriage return. Skipped tokens such as Whitespace are matched and then dropped; tools can show them struck through.
- Maximal munch
- Each token is the longest prefix of the remaining input that matches some rule.
- Ties
- When rules Rj and Rk match the same longest prefix, the earlier one wins: min(j, k).
- Errors
- An optional Error rule, listed last, matches any one character.
Conventions beyond the slides
Where the slides leave a choice open, every tool makes the same one. These choices fix state names and the order of steps.
- Thompson’s construction
- A* adds a new start s and final f with s →ε A.start, A.final →ε s, and s →ε f, as drawn on the slide. AB links A.final →ε B.start without merging states. A+ builds A A* with a fresh copy of A, An builds n copies, A? builds A | ε, and ɸ is a start and a final state with no edge. Each use of a definition gets its own copy.
- ε-closure
- Lists the starting states first, then the states reached through ε-moves, depth first, following edges in the order they were created.
- Subset construction
- Unmarked DFA states are processed first in, first out; symbols in ascending order. A DFA state accepts when it contains an accepting NFA state; in a scanner it reports the token of the earliest rule among them.
- Minimization
- Starts from two groups, accepting and non-accepting states (accepting states are also split by token), and splits groups until no symbol separates their members. Each split comes with a string that tells the states apart.
Grammars and parsing
Productions and alternatives
A grammar is written as a list of productions. A production has one non-terminal on the left of → and, on the right, the symbols that may replace it.
| Written | Meaning | Example |
|---|---|---|
| → | Production: the left-hand side may be replaced by the right-hand side | E → E + E |
| | | Separates the alternatives of one non-terminal: S → 0 | 1 stands for S → 0 and S → 1 | E → T | T + E |
| ε | The empty right-hand side | S → ε | ( S ) |
E → T | T + E T → int | int * T | ( E )
E → if E then E | if E then E else E | OTHER
- Non-terminals
- A symbol is a non-terminal exactly when it has a production, that is, when it appears on a left-hand side. By convention non-terminals are written with a capital letter: E, EXPR, NounPhrase.
- Terminals
- Every other symbol. By convention terminals are lower-case names or punctuation: int, id, +, (. The spelling does not decide: OTHER in the grammar above has no production, so it is a terminal.
- Start symbol
- The left-hand side of the first production.
- Spacing
- Symbols are separated by spaces. Each punctuation character is a symbol by itself, so E+E is read as E + E.
- Quoted terminals
- A terminal of several characters or several words is quoted: "the cat", '=='.
- Primes
- A non-terminal added by a rewrite is named with a prime: S’ next to S.
- Comments
- Lines starting with // and text between /* and */ are ignored.
Typing the symbols
Grammar fields turn -> into → as you type, and the buttons above a field insert a symbol at the cursor. Inside quotes and comments -> stays as typed, so a terminal spelled that way is written '->'.
| Symbol | Meaning | Type |
|---|---|---|
| → | Production arrow | -> |
| ε | Empty right-hand side | epsilon |
| S’ | Primed name | S' |
Derivations
A derivation begins with the start symbol and replaces one non-terminal at a time by a right-hand side of one of its productions, until only terminals remain. The strings along the way are sentential forms.
A step is written with the same arrow as a production. In this chain the underlined non-terminal is the one the next step replaces, and the tinted symbols are what the step before put in.
- E
- E * E
- ( E ) * E
- ( E + E ) * E
- ( int + E ) * E
- ( int + int ) * E
- ( int + int ) * int
| Written | Meaning |
|---|---|
| → | One step: one non-terminal is replaced |
| →* | 0 or more steps |
| →+ | 1 or more steps |
One step replaces a single non-terminal Xi and leaves the rest of the string as it is:
X1 … Xi-1 Xi Xi+1 … Xn → X1 … Xi-1 Y1 … Ym Xi+1 … Xn
if there is a production Xi → Y1 … Ym. The language of a grammar G with start symbol S is the set of strings of terminals that S derives:
L(G) = { a1a2 … an | S →* a1a2 … an and ai ∈ T }
A leftmost derivation replaces the leftmost non-terminal in every step, and a rightmost derivation the rightmost one. Both are named in words; the arrow stays the same.
Context-free grammars
A context-free grammar (CFG) G is a four-tuple. It consists of
- a set of non-terminals N,
- a set of terminals T,
- a start symbol S, which is a non-terminal, and
- a set of productions P.
G = (N, T, S, P)
For a non-terminal E ∈ N, a production is either E → ε or E → Y1 Y2 … Yn where each Yi ∈ N ∪ T.
| Grammar | N | T | S |
|---|---|---|---|
| E → int E → E + E E → E * E E → ( E ) | { E } | { int, +, *, (, ) } | E |
Chomsky hierarchy
| Type | Language | Form | Recognizer |
|---|---|---|---|
| 0 | Unrestricted or recursively enumerable | αXβ → αδβ X ∈ N ∪ T α, β, δ ∈ (N ∪ T)* | Turing machine |
| 1 | Context Sensitive | αVβ → αδβ V ∈ N δ ≠ ε | Linear Bounded Automaton (ND) |
| 2 | Context Free | V → α V ∈ N α ∈ (N ∪ T)* | Push-down Automaton (ND) |
| 3 | Regular | V → w | wU w ∈ T*; U, V ∈ N | NFA or DFA |
(ND) marks a nondeterministic recognizer. The four classes are nested: each one contains the classes below it in the table. Lecture reference: Introduction to Parsing
EBNF
Extended BNF adds two pairs of brackets to right-hand sides. They are written with spaces inside.
| Written | Meaning | Example |
|---|---|---|
| { α } | Zero or more α | E → T { + T } |
| [ α ] | Optional α | E → T [ + E ] |
Grammars from the slides, without and with the brackets:
S → 1 | S 0
becomesS → 1 { 0 }
Lecture reference: Top-Down ParsingE → E + T | T T → T * F | F F → ( E ) | int
becomesE → T { + T } T → F { * F } F → ( E ) | int
Lecture reference: Top-Down ParsingE → T + E | T T → ( E ) | int | int * T
becomesE → T [ + E ] T → ( E ) | int [ * T ]
Lecture reference: Top-Down ParsingA → X op A | X
becomesA → X [ op A ]
Lecture reference: Top-Down Parsing
Left recursion turns into a repetition and a shared beginning into an option. In an EBNF grammar { } [ ] are metasymbols, and a bracket that is a terminal is quoted: '['. In a plain grammar they are ordinary terminals.
Parse trees
A parse tree has the start symbol at its root. The children of a non-terminal are the symbols of the right-hand side that replaced it, and the leaves, read from left to right, spell the string.
- The root is at the top; children are drawn left to right.
- Plain straight lines fan out from a point under the parent. Labels have no boxes.
- A single child sits directly below its parent.
- Operators such as + are children, like any other symbol.
- A leaf sits one level below its own parent; the leaves do not share a baseline.
- Two trees for one string are drawn in two colors.
- A tree that is ruled out is crossed out with an X.
- An ε-production is drawn with an ε leaf.
Recursive descent
A recursive-descent parser builds the parse tree from the top and from left to right. It tries the productions of a non-terminal in the order they are written.
Input pointer
An ↑ stands under the next token, and after the last token at the end of the input. Tokens that are already matched are muted.
A predictive parser ends its input with $, which is then the last token the pointer reaches.
Status messages
Instances and functions
Occurrences of a non-terminal in a tree are numbered to tell them apart, starting from 0 at the root: E0 → T1 + E2.
The function that checks the i-th production of a non-terminal carries that number, counted from 1 in the order the productions are written. The function without a number tries them in that order. The slides number the functions for the grammar below, which has the same productions as the grammar of the tree above in another order:
E → T | T + E T → int | int * T | ( E )
| Function | Checks |
|---|---|
| E1 () | E → T |
| E2 () | E → T + E |
| T1 () | T → int |
| T2 () | T → int * T |
| T3 () | T → ( E ) |
| E (), T () | any production of the non-terminal |
Parser code is C, written as on the slides with a space before the parentheses of a call:
bool E2 () { return T () && match (PLUS) && E (); } Disambiguating declarations
An ambiguous grammar can be kept as it is and given declarations that pick one tree for each string. They are written in bison syntax, one per line.
%left + %left *
- %left
- Makes the operator left-associative: int + int + int groups as ( int + int ) + int.
- Order of the lines
- Lowest precedence first: an operator declared on a later line binds tighter. Here * binds tighter than +, so int + int * int groups as int + ( int * int ).
LL(1) and bottom-up parsing
First and Follow
A predictive parser chooses a production by the next token. Two sets of terminals decide the choice. First of a string of symbols holds the terminals that can begin what it derives, and ε when it derives ε. Follow of a non-terminal holds the terminals that can come right after it in a sentential form.
First(X) = { b | X →* bα } ∪ { ε | X →* ε }
Follow(X) = { b | S →* β X b ω }
Here b is a terminal and α, β, ω are strings of grammar symbols. $ is the end marker: the end of the input, the bottom of the parser’s stack, and a member of Follow(S) for the start symbol S.
Computing First
- First(b) = { b } for a terminal b.
- For every production X → A1 … An: add First(A1) – { ε } to First(X) and stop if ε ∉ First(A1); then the same for A2, …, An. If no step stops, add ε to First(X). Ignore Ai if it is X.
Computing Follow
- Compute the First sets of all non-terminals.
- Add $ to Follow(S).
- For every production Y → … X A1 … An: add First(A1) – { ε } to Follow(X) and stop if ε ∉ First(A1); then the same for A2, …, An. If no step stops, add Follow(Y) to Follow(X).
The rules are applied until no set changes.
E → T X X → + E | ε T → ( E ) | int Y Y → * T | ε
| X | First(X) | Follow(X) |
|---|---|---|
| E | { (, int } | { ), $ } |
| T | { (, int } | { +, ), $ } |
| X | { +, ε } | { ), $ } |
| Y | { *, ε } | { +, ), $ } |
LL(1) parsing tables
An LL(1) parser reads the input from Left to right, builds a Leftmost derivation, and predicts each production from 1 token of lookahead, without backtracking. Its choices form a two-dimensional table:
- Rows are non-terminals; columns are terminals, then $.
- A cell holds the right-hand side to expand the row’s non-terminal by (int Y, ε), not the whole production.
- A blank cell is an error.
- A cell is named by its row and column, [E, int]; the parser looks up T[N, a].
| Non-terminal | int | * | + | ( | ) | $ |
|---|---|---|---|---|---|---|
| T | int Y | ( E ) | ||||
| E | T X | T X | ||||
| X | + E | ε | ε | |||
| Y | * T | ε | ε | ε |
Filling the table
For each production A → α:
- for each terminal b ∈ First(α), set T[A, b] = α;
- if α →* ε, for each b ∈ Follow(A), set T[A, b] = α (b may be $).
- Y → * T
- goes in the columns of First( *T ) = { * }.
- Y → ε
- goes in the columns of Follow( Y ) = { +, ), $ }.
A grammar is LL(1) when no cell is multiply defined. An ambiguous, left-recursive, or not left-factored grammar is not LL(1), and neither are most programming-language grammars.
LL(1) parse traces
The parser keeps the symbols it still has to match on a stack, which starts as < S $ >. It looks at the top of the stack and the next token:
- Non-terminal on top
- It is replaced by the right-hand side in its cell for the next token. A blank cell is an error.
- Terminal on top
- It must be the next token: it is popped and the input advances. Otherwise it is an error.
- Accept
- At the end of the input, with the stack empty.
// Assume table already created
initialize stack = < S $ > and next
repeat
case stack of
<N, rest> : if T[N,*next] == Y1 … Yn
then stack ← < Y1 … Yn rest >;
else error ();
<t, rest> : if t == *next ++
then stack ← < rest >;
else error ();
until stack == < > A trace has three columns. Stack has its top on the left and $ at the bottom. Input is the rest of the input, ending with $. Action is what is done to the row’s stack and input: the right-hand side pushed (T X), terminal when the top matches the next token, ε when an ε-production pops the top, and ACCEPT when both are down to $.
| Stack | Input | Action |
|---|---|---|
| E $ | int * int $ | T X |
| T X $ | int * int $ | int Y |
| int Y X $ | int * int $ | terminal |
| Y X $ | * int $ | * T |
| * T X $ | * int $ | terminal |
| T X $ | int $ | int Y |
| int Y X $ | int $ | terminal |
| Y X $ | $ | ε |
| X $ | $ | ε |
| $ | $ | ACCEPT |
Handles
A bottom-up parser builds the parse tree from the leaves up. Its most common form is LR parsing: the tokens are read from Left to right, and the parser builds a Rightmost derivation, in reverse.
It reduces the input to the start symbol by inverting productions. Each step takes the current sentential form sent and the first β in it such that
A → β and S →* α A γ → α β γ = sent
and replaces β by A, so that α A γ is the next form. Such a β is a handle. Right of a handle there are only terminals (γ), because α A γ → α β γ is a step of a rightmost derivation.
- handle: int, end of handle + (int)
- E + (handle: int, end of handle)
- handle: E + (E), end of handle
- E
Bottom-up trees are drawn differently from top-down ones:
- The tokens sit on one bottom row, in input order, evenly spaced.
- Each reduction adds a node above its children, centered over them, so the tree grows upward.
- A node with a single child sits directly above it.
- A node is raised further when a line to one of its children would pass through another child’s subtree.
The bottom-up decks write sentential forms with each parenthesis next to what it encloses: E + (int).
Shift-reduce parsing
A shift-reduce parser splits the string in two at a divider, drawn as a red divider. Left of it are terminals and non-terminals; right of it are the tokens not examined yet. The divider marks the end of the next potential handle. At the start the whole input is right of it: divider x1 x2 … xn.
- Shift
- Move divider one place to the right: E + ( divider int ) ⇒ E + ( int divider )
- Reduce
- Apply an inverse production at the handle, just left of the divider: E + ( handle: E + ( E ), end of handle divider ) ⇒ E + ( handle reduced to E divider )
Here ⇒ is one move of the parser, not a derivation step. The left part is a stack: a shift pushes a terminal, and a reduce by A → α pops the symbols of α (zero or more) and pushes A.
Traces
One configuration per row, with its action on the right: shift, shift 3 times (shifts in a row on one line), red. E → int (reduce by E → int), and accept. The symbols an action works on are colored: the handle left of the divider before a reduce, the tokens right of it before a shift. The input ends with $.
| Configuration | Action |
|---|---|
| divider to shift: int, end of shift + (int) + (int)$ | shift |
| handle: int, end of handle divider + (int) + (int)$ | red. E → int |
| E divider to shift: + (int, end of shift) + (int)$ | shift 3 times |
| E + (handle: int, end of handle divider ) + (int)$ | red. E → int |
| E + (E divider to shift: ), end of shift + (int)$ | shift |
| handle: E + (E), end of handle divider + (int)$ | red. E → E + (E) |
| E divider to shift: + (int, end of shift)$ | shift 3 times |
| E + (handle: int, end of handle divider )$ | red. E → int |
| E + (E divider to shift: ), end of shift$ | shift |
| handle: E + (E), end of handle divider $ | red. E → E + (E) |
| E divider $ | accept |
Beside a trace, the tree grows over the tokens: a subtree for each symbol on the stack, the tokens still to come as bare leaves, and ↑ under the divider.
LR(1) items
An LR(1) item is a production with a dot in its right-hand side and one lookahead terminal:
[X → α•β, a]
X → αβ is a production and a is a terminal. The item says that the parser is trying to find an X followed by an a, has α on top of the stack, and next needs to see a prefix of something derived from βa. The dot, in red, does the job of the divider divider: in both, the stack is on the left.
| Form | Used | Example |
|---|---|---|
| Bracketed | definitions, algorithms and conflicts | [E → E + • ( E ), +] |
| Spaced | running text | E → E + • ( E ), + |
| Compact | inside a state box | E → E+•(E), + |
| Merged lookaheads | items that differ only in their lookahead, on one line | E → •int, $/+ stands for E → •int, $ and E → •int, + |
The parsing DFA
The grammar gets a new start symbol S and the production S → E (not needed when E has only one production); when the grammar’s own start symbol is S, the new one is S’. The start state is Closure({ S → •E, $ }). A state is a closed set of items, and Transition(state, y) is the state after the symbol y, a terminal or a non-terminal.
Closure(Items) =
repeat
for each [X → α•Yβ, a] in Items
for each production Y → γ
for each b ∈ First(βa)
add [Y → •γ, b] to Items
until Items is unchanged Transition (state, y) Items ← ∅ for each [X → α•yβ, b] ∈ state add [X → αy•β, b] to Items return Closure(Items)
A state with an item [X → α•, b] is labeled “reduce with X → α on b”, written beside the state as E → int on $, +. The state with [S → E•, $] is labeled accept on $. The start state is state 0.
LR parsing tables
The parser chooses between shift and reduce with the DFA. It runs the DFA on the stack and looks at the state X it ends in and the token tok after the divider: if X has a transition on tok, it shifts; if X is labeled A → β on tok, it reduces by A → β; in a state labeled accept on $ with $ next, it accepts.
The DFA is stored as a table. Rows are states and columns are grammar symbols: the terminals and $ make up the action table, and the non-terminals, after a vertical rule, the goto table.
| Entry | Meaning |
|---|---|
| s4 | shift, and go to state 4 |
| g6 | in a non-terminal column: go to state 6 |
| rE→int | reduce by the production written under the r |
| accept | accept |
| blank | error |
| State | int | + | ( | ) | $ | E |
|---|---|---|---|---|---|---|
| … | ||||||
| 3 | s4 | |||||
| 4 | s5 | g6 | ||||
| 5 | rE→int | rE→int | ||||
| 6 | s8 | s7 | ||||
| 7 | rE→E+(E) | rE→E+(E) | ||||
| … |
The LR stack
Running the DFA over the whole stack after every move repeats work. Instead each stack element remembers the state it brings the DFA to: the stack holds pairs < sym1, state1 > … < symn, staten >, where statek is the state of the DFA after sym1 … symk. It starts as < dummy, 0 >, state 0 being the start state.
Let I = w $
Let j = 0
Let DFA state 0 be the start state
Let stack = < dummy, 0 >
repeat
case action[top_state(stack), I[j]] of
shift k: push < I[j++], k >
reduce X → α:
pop |α| pairs,
push < X, Goto[top_state(stack), X] >
accept: halt normally
error: halt and report error Conflicts
A parser generator reports a grammar it cannot build a table for in terms of the items of a state. Two kinds of conflict:
- Shift/reduce
- The state contains [X → α•aβ, b] and [Y → γ•, a]. On a, the parser could shift into [X → αa•β, b] or reduce with Y → γ.
- Reduce/reduce
- The state contains [X → α•, a] and [Y → β•, a].
Shift/reduce conflicts usually come from an ambiguous grammar, such as the dangling else, where a state contains [S → if E then S •, else] and [S → if E then S • else S, x]. Reduce/reduce conflicts come from gross ambiguity. The slides show part of a state and part of the state its transition on a symbol leads to, joined by ⇒ with the symbol on top; … stands for items left out.
- [E → E * • E, +]
- [E → • E + E, +]
- …
- [E → E * E •, +]
- [E → E • + E, +]
- …
- [S’ → • S, $]
- [S → •, $]
- [S → • id, $]
- [S → • id S, $]
- [S → id •, $]
- [S → id • S, $]
- [S → •, $]
- [S → • id, $]
- [S → • id S, $]
S → ε | id | id S has two parse trees for id. Rewritten as S → ε | id S, it has none of these conflicts.
Open the ambiguous expression grammar in Conflicts & Precedence
Precedence in bison
Bison settles shift/reduce conflicts with declarations of precedence and associativity:
%left '+' %left '*'
- Order of the lines
- A later line binds tighter: here * over +. Bison quotes a character terminal, so %left '+' is the declaration %left + of Disambiguating declarations.
- Precedence of a rule
- That of its last terminal: E → E * E has the precedence of *.
- Shift if
- no precedence declared for either rule or terminal
- input terminal has higher precedence than the rule
- the precedences are the same and right associative
In the state with [E → E * E •, +] and [E → E • + E, +], the rule E → E * E has a higher precedence than the terminal +, so the parser reduces. The dangling-else conflict goes away when else is declared with a higher precedence than then, or by the default shift.
Grammar classes
Every LL(k) grammar is LR(k), every LL(1) grammar LR(1), and every LL(0) grammar LR(0). No ambiguous grammar is in any of these classes.
Open the left-factored expression grammar in Conflicts & Precedence