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

Lecture reference: Lexical Analysis · slides 19–22 Lecture reference: Lexical Analysis III · slide 6

An alphabet Σ is a finite set of symbols. A language over Σ is a set of strings of symbols drawn from Σ.

ConceptWrittenExample
AlphabetΣΣ = { 0, 1 }
Stringdouble quotes"if", "1110"
Empty string"" in a set; ε in an RE or on an edgeL(ε) = { "" }
Empty languageɸ in an RE; { } as a setL(ɸ) = { }
RE literalsingle quotes'if', '\t', ' '
Language of an REL(R)L('1' '0'*)
Language of a machineL(M)L(M) = { "1" }

Sets of strings are written with spaces inside the braces, and … marks a set that goes on:

Regular expressions

Lecture reference: Lexical Analysis · slides 23–27

Each clause of the inductive definition, with the language it denotes. A and B stand for any regular expressions.

ClauseRELanguage
Basis
Atomic'c'L('c') = { "c" } for any c ∈ Σ
EmptyɸL(ɸ) = { }
EpsilonεL(ε) = { "" }
Inductive
ConcatenationABL(AB) = { ab | a ∈ L(A) and b ∈ L(B) }
Choice/AlternationA | BL(A | B) = { s | s ∈ L(A) or s ∈ L(B) }
Iteration (Kleene closure)A*L(A*) = { "" } ∪ L(A) ∪ L(AA) ∪ L(AAA) ∪ …
Positive closureA+L(A+) = L(A A*)
Fixed iterationAnL(An) = L(A A … A) A repeated n times
Also accepted
OptionalA?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. 1* + ? nPostfix operators bind tightest
  2. 2ABthen concatenation
  3. 3A | Bthen choice

Parentheses group. Some expressions with the grouping made explicit:

WrittenMeans
ab*a (b*)
ab | c(a b) | c
a | b*ca | ((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

Lecture reference: Lexical Analysis · slide 27 Lecture reference: Lexical Analysis · slide 31

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*
Lecture reference: Lexical Analysis · slide 27
area     = digit3
exchange = digit3
phone    = digit4
number   = '(' area ')' exchange '-' phone
Lecture reference: Lexical Analysis · slide 31

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.

SymbolMeaningTypeAlso accepted
εEmpty string\eϵ
ɸEmpty language\pφ ϕ ∅
ΣAny one symbol of the alphabet\S
A+Positive closureA+A⁺
A3Fixed iterationA^3A³
…Range...…

Flex patterns

Lecture reference: Lexical Analysis III (cont’d) · slides 6–7 Lecture reference: Lexical Analysis III (cont’d) · slide 10

Tools that read flex specifications use flex's own pattern syntax, where most characters stand for themselves and literals need no quotes.

PatternMatches
xthe 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
r1r2r1 then r2 (concatenation)
r1|r2r1 or r2 (choice)
(r)grouping
r1/r2r1 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})*
Lecture reference: Lexical Analysis III (cont’d) · slide 10

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

Lecture reference: Lexical Analysis III · slides 3–13

A deterministic finite automaton (DFA) M consists of

  1. an input alphabet Σ,
  2. a set of states S,
  3. a start state s0,
  4. a set of accepting states F ⊆ S, and
  5. 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 inputOutcome
in an accepting state (for an NFA: able to reach one)accept
in any other statereject
no transition was possible along the wayreject

“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

Lecture reference: Lexical Analysis III · slide 5 Lecture reference: Lexical Analysis III · slide 10

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

Lecture reference: Lexical Analysis IV · slide 6 Lecture reference: Lexical Analysis IV · slide 10 Lecture reference: Lexical Analysis IV · slide 16
MachineStates are namedExample
Thompson NFALetters 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 DFAThe 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 DFAThe name of the first state in each merged group; the merged states are listed.S for {S, T}
Hand-builtWhatever you type. New states take the next free letter.S, T, U
Relational operatorsNumbers, as on the slide.0 … 8

Transition tables

Lecture reference: Lexical Analysis IV · slide 14 Lecture reference: Lexical Analysis IV · slide 16

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”.
State01
→STU
TTU
◎UTU
DFA Lecture reference: Lexical Analysis IV · slide 14
State01ε
→A∅{A, B}∅
◎B∅∅∅
NFA: cells are sets; an extra ε column Lecture reference: Lexical Analysis III · slide 9

Tokens and lexemes

Lecture reference: Lexical Analysis II · slide 7 Lecture reference: Intro (cont’d): Compiler architecture · slide 4 Lecture reference: Lexical Analysis II · slides 10–12

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:

FormatLexemeFrom
(Identifier, "f")a string, in double quotes Lecture reference: Lexical Analysis II · slide 7
<ID,'A'>in single quotes Lecture reference: Intro (cont’d): Compiler architecture · slide 4

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

Lecture reference: Lexical Analysis IV · slides 3–5

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

Lecture reference: Introduction to Parsing · slides 12–14 Lecture reference: Introduction to Parsing · slide 26 Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 11

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.

WrittenMeaningExample
→Production: the left-hand side may be replaced by the right-hand sideE → E + E
|Separates the alternatives of one non-terminal: S → 0 | 1 stands for S → 0 and S → 1E → T | T + E
εThe empty right-hand sideS → ε | ( S )
E → T | T + E
T → int | int * T | ( E )
One line per non-terminal Lecture reference: Top-Down Parsing · slide 4
E → if E then E
  | if E then E else E
  | OTHER
Continuation lines start with | Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 11
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 '->'.

SymbolMeaningType
→Production arrow->
εEmpty right-hand sideepsilon
S’Primed nameS'

Derivations

Lecture reference: Introduction to Parsing · slide 12 Lecture reference: Introduction to Parsing · slides 17–20 Lecture reference: Introduction to Parsing · slide 22

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.

  1. E
  2. E * E
  3. ( E ) * E
  4. ( E + E ) * E
  5. ( int + E ) * E
  6. ( int + int ) * E
  7. ( int + int ) * int
The slide writes the last three steps as … Lecture reference: Introduction to Parsing · slide 12
WrittenMeaning
→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

Lecture reference: Introduction to Parsing · slides 14–15

A context-free grammar (CFG) G is a four-tuple. It consists of

  1. a set of non-terminals N,
  2. a set of terminals T,
  3. a start symbol S, which is a non-terminal, and
  4. 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.

GrammarNTS
E → int
E → E + E
E → E * E
E → ( E )
{ E }{ int, +, *, (, ) }E

Chomsky hierarchy

Lecture reference: Introduction to Parsing · slide 23
TypeLanguageFormRecognizer
0Unrestricted or recursively enumerableαXβ → αδβ
X ∈ N ∪ T
α, β, δ ∈ (N ∪ T)*
Turing machine
1Context SensitiveαVβ → αδβ
V ∈ N
δ ≠ ε
Linear Bounded Automaton (ND)
2Context FreeV → α
V ∈ N
α ∈ (N ∪ T)*
Push-down Automaton (ND)
3RegularV → 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 · slide 24

EBNF

Lecture reference: Top-Down Parsing · slides 24–25 Lecture reference: Top-Down Parsing · slides 36–39

Extended BNF adds two pairs of brackets to right-hand sides. They are written with spaces inside.

WrittenMeaningExample
{ α }Zero or more αE → T { + T }
[ α ]Optional αE → T [ + E ]

Grammars from the slides, without and with the brackets:

  • S → 1 | S 0
    becomes
    S → 1 { 0 }
    Lecture reference: Top-Down Parsing · slide 25
  • E → E + T | T
    T → T * F | F
    F → ( E ) | int
    becomes
    E → T { + T }
    T → F { * F }
    F → ( E ) | int
    Lecture reference: Top-Down Parsing · slide 38
  • E → T + E | T
    T → ( E ) | int | int * T
    becomes
    E → T [ + E ]
    T → ( E ) | int [ * T ]
    Lecture reference: Top-Down Parsing · slide 36
  • A → X op A | X
    becomes
    A → X [ op A ]
    Lecture reference: Top-Down Parsing · slide 39

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

Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slides 4–5 Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 10 Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 17

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.
The two parse trees of int + int + int under E → E + E | E * E | ( E ) | int Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 4
Ruled out by %left + under E → E + E | int Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 17
( ) under S → ε | ( S ): the inner S derives ε Lecture reference: Introduction to Parsing · slide 27

Recursive descent

Lecture reference: Top-Down Parsing · slides 5–20 Lecture reference: Top-Down Parsing · slides 29–34 Lecture reference: Top-Down Parsing · slide 37

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.

next token: int (2 of 3)
end of input

A predictive parser ends its input with $, which is then the last token the pointer reaches.

next token: $ (end of input)
Lecture reference: Top-Down Parsing · slide 37

Status messages

Mismatch: int is not (
The terminal at the current node (here int) is not the next token (here an opening parenthesis).
Backtrack …
Follows a mismatch: the children just added are removed and the next alternative is tried.
Match! Advance input.
The terminal at the current node is the next token; the pointer moves one token to the right.
End of input, accept
The tree is complete and the pointer is past the last token.

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.

int * int under E → T + E | T, T → ( E ) | int | int * T Lecture reference: Top-Down Parsing · slide 20

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 )
Lecture reference: Top-Down Parsing · slides 31–34
FunctionChecks
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 (); }
Lecture reference: Top-Down Parsing · slide 34

Disambiguating declarations

Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slides 16–18

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 *
Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 18
%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 ).
int + int * int under E → E + E | E * E | int with the two declarations Lecture reference: Ambiguity, Precedence, Associativity & Top-Down Parsing · slide 18

LL(1) and bottom-up parsing

First and Follow

Lecture reference: Table-based Predictive Parsing · slides 18–19 Lecture reference: Table-based Predictive Parsing · slides 20–23

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

  1. First(b) = { b } for a terminal b.
  2. 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

  1. Compute the First sets of all non-terminals.
  2. Add $ to Follow(S).
  3. 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 | ε
XFirst(X)Follow(X)
E{ (, int }{ ), $ }
T{ (, int }{ +, ), $ }
X{ +, ε }{ ), $ }
Y{ *, ε }{ +, ), $ }
First and Follow of the left-factored expression grammar Lecture reference: Table-based Predictive Parsing · slides 21–23

Open this grammar in LL(1) Parsing Table 

LL(1) parsing tables

Lecture reference: Table-based Predictive Parsing · slide 3 Lecture reference: Table-based Predictive Parsing · slides 7–9 Lecture reference: Table-based Predictive Parsing · slides 24–26

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-terminalint*+()$
Tint Y( E )
ET XT X
X+ Eεε
Y* Tεεε
The table of the grammar above, with the rows in the slide’s order Lecture reference: Table-based Predictive Parsing · slide 7

Filling the table

For each production A → α:

  1. for each terminal b ∈ First(α), set T[A, b] = α;
  2. 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.

Open this table’s grammar in LL(1) Parsing Table 

LL(1) parse traces

Lecture reference: Table-based Predictive Parsing · slides 10–12

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 == < >
Lecture reference: Table-based Predictive Parsing · slide 11

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 $.

StackInputAction
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
int * int $ with the table above Lecture reference: Table-based Predictive Parsing · slide 12

Open this trace in LL(1) Parsing Table 

Handles

Lecture reference: Bottom-Up Parsing · slide 2 Lecture reference: Bottom-Up Parsing · slide 4 Lecture reference: Bottom-Up Parsing · slides 5–11

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.

  1. handle: int, end of handle + (int)
  2. E + (handle: int, end of handle)
  3. handle: E + (E), end of handle
  4. E
The handles in red. Read upward, the list is a rightmost derivation. Lecture reference: Bottom-Up Parsing · slide 10
int + (int) under E → E + ( E ) | int Lecture reference: Bottom-Up Parsing · slides 5–10

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).

Open int + (int) in Shift-Reduce Parsing 

Shift-reduce parsing

Lecture reference: Bottom-up Parsing II · slides 2–3 Lecture reference: Bottom-up Parsing II · slides 4–15

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 $.

ConfigurationAction
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
Under E → E + ( E ) | int Lecture reference: Bottom-up Parsing II · slide 14

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.

int + (int) at E + (handle: int, end of handle divider )$ Lecture reference: Bottom-up Parsing II · slides 4–14

Open this trace in Shift-Reduce Parsing 

LR(1) items

Lecture reference: Bottom-up Parsing III · slides 5–7 Lecture reference: Bottom-up Parsing III · slides 10–14

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.

FormUsedExample
Bracketeddefinitions, algorithms and conflicts[E → E + • ( E ), +]
Spacedrunning textE → E + • ( E ), +
Compactinside a state boxE → E+•(E), +
Merged lookaheadsitems that differ only in their lookahead, on one lineE → •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
Lecture reference: Bottom-up Parsing III · slide 10
Transition (state, y)
  Items ← ∅
  for each [X → α•yβ, b] ∈ state
    add [X → αy•β, b] to Items
  return Closure(Items)
Lecture reference: Bottom-up Parsing III · slide 13

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.

States 0–6 for S → E, E → E + ( E ) | int, with the edges 0 →int 1, 0 →E 2, 2 →+ 3, 3 →( 4, 4 →int 5, 4 →E 6 Lecture reference: Bottom-up Parsing III · slide 14

Open this grammar in LR(1) Parser Builder 

LR parsing tables

Lecture reference: Bottom-up Parsing II · slides 16–19 Lecture reference: Bottom-up Parsing II · slides 20–21

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.

EntryMeaning
s4shift, and go to state 4
g6in a non-terminal column: go to state 6
rE→intreduce by the production written under the r
acceptaccept
blankerror
Stateint+()$E
…
3s4
4s5g6
5rE→intrE→int
6s8s7
7rE→E+(E)rE→E+(E)
…
Rows 3–7 for E → E + ( E ) | int. The slide prints the two entries of row 6 one column to the left; by the DFA they are under + and ). Lecture reference: Bottom-up Parsing II · slide 19

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
Lecture reference: Bottom-up Parsing II · slide 21

Open this table’s grammar in LR(1) Parser Builder 

Conflicts

Lecture reference: Bottom-up Parsing III · slides 16–18 Lecture reference: Bottom-up Parsing III · slides 23–25

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 • + E, +]
  • …
E → E + E | E * E | int: shift/reduce on input + Lecture reference: Bottom-up Parsing III · slide 18
  • [S’ → • S, $]
  • [S → •, $]
  • [S → • id, $]
  • [S → • id S, $]
⇒id
  • [S → id •, $]
  • [S → id • S, $]
  • [S → •, $]
  • [S → • id, $]
  • [S → • id S, $]
S → ε | id | id S: reduce/reduce on input $ Lecture reference: Bottom-up Parsing III · slide 25

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

Lecture reference: Bottom-up Parsing III · slides 19–22

Bison settles shift/reduce conflicts with declarations of precedence and associativity:

%left '+'
%left '*'
Lecture reference: Bottom-up Parsing III · slide 19
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.

Open these declarations in Conflicts & Precedence 

Grammar classes

Lecture reference: Bottom-up Parsing III · slide 26

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.

Unambiguous GrammarsAmbiguousGrammarsLR(k)LR(1)LALR(1)SLRLR(0)LL(k)LL(1)LL(0)
Simple LR (SLR); Look-ahead LR (LALR) Lecture reference: Bottom-up Parsing III · slide 26

Open the left-factored expression grammar in Conflicts & Precedence