Act III · Speaking to the Machine
Part 12 of 61Languages and Automata
What kind of machine can read a sentence, and why can six characters of regex stall a website?
The pattern (a+)+b, matched against a row of a's with no b, takes Python about four times longer for every two a's added, and in July 2019 a firewall rule of the same kind exhausted Cloudflare's processors for 27 minutes. The part builds the theory that explains it and that a compiler needs first. A language is a set of strings. Regular expressions and finite automata describe the same languages: Thompson's construction turns an expression into an NFA simulated on sets of states in time O(mn), the subset construction makes it deterministic at a price of up to 2 to the n states, and state elimination closes Kleene's triangle. The pumping lemma shows what no finite memory can do: match a to the n with b to the n. The part turns there. A stack supplies the missing memory, grammars turn a flat list of tokens into a tree, and the Chomsky hierarchy orders languages by the memory they need. Seven parsing algorithms follow, from CYK and Earley to LL(1), Pratt and the LR family checked against bison, and the Pebble language gets its lexer, a 79-rule grammar with a conflict-free 146-state LALR table, and a parser that reads the Job. The frontier asks how fast matching and parsing can be at all.
What you need. Sets, functions and proof by contradiction, as in Part 2. No formal-language background is assumed.
- Mathematics, ideas and history
- regex, NFA/DFA, Thompson, subset construction, pumping, CFGs, the Chomsky hierarchy, CYK/Earley, LL and LR
- What we build or compute
- a regex engine; the Pebble language's parser
What you will be able to do
Degree
- Write a regular expression and a DFA for a simple language, and convert an NFA to a DFA by the subset construction.
- Use the pumping lemma to prove a language such as a^n b^n is not regular.
- Write a context-free grammar for nested structure, draw parse trees, and show that a grammar is ambiguous.
Graduate
- Build Thompson's NFA for an expression, simulate it on sets of states, and minimize the resulting DFA.
- Compute FIRST and FOLLOW, build an LL(1) table, and construct the LR(0) items and an SLR or LALR table for a small grammar, locating any conflict.
- Fill a CYK table, and explain why the n-th-from-end language needs 2^n deterministic states.
Research
- State the conditional lower bounds for regular-expression matching and context-free recognition with their exact input models and hypotheses.
- Build a DFA by Brzozowski derivatives, and explain why the residual languages give the minimal machine only after expressions are normalized.
Industry
- Recognize a pattern with nested or overlapping repetition, and choose between an automaton engine and a backtracking one by features, guarantees and limits.
- Choose between a hand-written recursive-descent parser and a generated LR parser, and put input limits and timeouts around patterns that are not trusted.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 28 min · Graduate 46 min · Research 50 min · Industry 31 min.
- 0Reading text, and a regex that took down websitesDegree2 min
- 1Languages as sets of stringsDegree2 min
- 2Regular expressions and automataDegree2 min
- 3Thompson's constructionDegree2 min
- 4The subset construction and minimizationDegree4 min
- 5Kleene's theoremGraduate2 min
- 6What regular languages cannot doDegree3 min
- 7Backtracking enginesIndustry4 min
- 8Lexing the Pebble languageDegree3 min
- 9Context-free grammarsDegree3 min
- 10Stacks and the Chomsky hierarchyDegree4 min
- 11Parsing any grammar: CYK and EarleyGraduate2 min
- 12Top-down parsingGraduate4 min
- 13Bottom-up parsingGraduate4 min
- 14The Pebble language, parsedGraduate3 min
- 15Frontier: how fast can we parse?Research4 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Reading text, and a regex that took down websitesDegree2 min
Six characters expose an expensive way to say no. The pattern means one or more a's, repeated, followed by b. Match it against a string containing only a's. No match exists. On this failing family, the recorded Python timings grow roughly fourfold for every two added a's. Read the measured values on the graph; a timeout records a limit, not a completed duration. GNU grep handles a much longer input efficiently here. Its displayed estimate subtracts a separately measured process baseline and clamps negative differences to zero; it is a noisy timing proxy, not an exact engine-only cost. In July 2019, a new Cloudflare firewall rule with overlapping repetitions exhausted CPU across its network. The outage lasted twenty-seven minutes. We will separate that incident from our simplified experiment and explain how the search space grows.
And this part has a job of its own to do. Here is the Job again, written this time in a programming language: the Pebble language, which we design in this part and compile in the next. Before any compiler can translate it, something has to read it. First its characters are grouped into words, called tokens, and the rules for tokens are regular expressions. Then the tokens are fitted to a grammar, which turns a flat list into a tree. Both steps rest on one of the most beautiful theories in computer science: languages, and the machines that recognize them.
We will connect five views of reading a program. Regular expressions and finite automata describe the same languages, with explicit constructions between them. Engine strategy explains why this failing pattern is fast in grep and expensive in the measured Python engine. A proof shows why finite memory cannot handle arbitrary nesting; a stack supplies the missing memory. Grammars then turn tokens into trees, using several top-down and bottom-up parsing methods. Finally, the Pebble lexer and parser read the Job, ready for the compiler in the next part.
1Languages as sets of stringsDegree2 min
A formal language is a set of strings. First fix a finite alphabet, such as zero and one. A string is a finite sequence of symbols; epsilon is the empty string. A language may contain finitely or infinitely many strings. Examples include binary multiples of three, balanced parentheses, equal runs of a's and b's, and palindromes. A programming language also has a syntactic language: strings admitted by its grammar. The Job is such a Pebble program; a missing parenthesis may break its syntax. Type rules and other semantic checks impose additional conditions, beyond what this parser establishes.
There are two things we might want to do with a language. A recognizer answers a yes-or-no question: is this string in the language? A parser does more: it says how the string belongs, by building its structure. For this expression, the tree says that the multiplication happens first, and the addition last. A compiler needs the tree; but recognizing comes first, and it is already deep.
What must a recognizer remember? Divisibility by three needs only the current remainder: finitely many states suffice for inputs of any length. Arbitrarily nested parentheses require an unbounded count of opens. A stack is sufficient. Linear-bounded machines have workspace proportional to input length. A Turing machine has no fixed finite workspace bound, although any finite computation visits only finitely many cells. The Chomsky hierarchy connects language classes to these machine models. More permitted memory changes what can be recognized; it does not mean every computation finishes.
2Regular expressions and automataDegree2 min
Mathematical regular expressions build languages using three operations, developed by Kleene in his work on finite automata. Union chooses a string from either language. Concatenation joins a string from each. Star joins any finite number of strings from one language, including zero. Ordinary plus, question mark, finite character classes and dot are expressible with these operations over the chosen alphabet. Practical extensions such as backreferences require a separate discussion. The examples include suffixes, identifiers and binary divisibility by three. Our divisibility convention allows leading zeros and also accepts the empty word as representing zero; requiring at least one digit would change that language slightly.
And here is a machine. A finite automaton with three states, one for each possible remainder when a binary number read so far is divided by three. Reading one more bit doubles the number and adds the bit, so the remainder r becomes two r plus b, modulo three. That is the whole machine: a fixed memory of three states, however long the input. Feed it one, zero, zero, one. It moves to one, to two, to one, and back to zero, the accepting state: nine is divisible by three. Exactly the strings that the strange regular expression on the last slide describes. Is that a coincidence?
It is not. Kleene's theorem says that regular expressions and finite automata describe exactly the same languages, the regular languages. The next three chapters prove it by going round this triangle. Ken Thompson's construction turns any regular expression into a nondeterministic automaton. The subset construction, from Michael Rabin and Dana Scott, turns that into an ordinary deterministic one. And eliminating states one at a time turns any automaton back into a regular expression.
3Thompson's constructionDegree2 min
Thompson's 1968 construction builds an automaton from fragments. A fragment has one entrance and one exit; a symbol supplies a labeled transition. Concatenation connects an exit to the next entrance with epsilon: a transition consuming no input symbol. Union uses epsilon transitions to choose either fragment and then merge. Star allows both another repetition and an exit without a repetition. Nondeterminism means several paths may be possible for the same input. A simulator tracks all reachable states, including epsilon closure. Those transitions consume no input, but computing that closure still costs work.
Here is the construction for parenthesized a-or-b, starred, followed by a b b: any binary-alphabet prefix, then the suffix a b b. This implementation produces fourteen states, including the repetition and the three final symbol fragments. Its starting set contains the start state and every state reachable using only epsilon transitions. For each input character, follow matching transitions from the active set, then compute epsilon closure again. Duplicate paths reaching the same state are merged; the active set has at most fourteen states. After the entire input is consumed, accept exactly when the accepting state is active. This is whole-string membership, distinct from searching for a matching substring.
The construction gives a useful cost bound. For a Thompson NFA with m states and bounded outgoing degree, visit each active state and each state reached in epsilon closure only a bounded number of times per input character. With n characters, O m n time and O m active storage suffice. This is an upper bound; a particular input may visit fewer states. Thompson used generated IBM 7094 code in the QED editor. Later Unix text tools developed from this line of work; modern engines add their own optimizations and feature choices. The displayed host timings compare our Python simulator with the host backtracking engine on this failing pattern. Inspect their trend and units rather than treating a measured duration as a portable constant. State-work counts and elapsed time answer different questions.
4The subset construction and minimizationDegree4 min
The active-set simulation suggests a deterministic construction. Make each reachable NFA state set one DFA state. State A represents the epsilon closure of the NFA start. Reading a or b determines the next set uniquely. Continue exploring until no unseen sets remain. For parenthesized a-or-b, starred, followed by a b b, this construction reaches only five of the fourteen-state NFA's sixteen thousand three hundred and eighty-four possible subsets. A DFA state accepts precisely when its set contains the NFA accept state; here only E does. Rabin and Scott's subset construction establishes that nondeterminism adds no expressive power to finite automata, although it can make them much more compact.
Correct machines may contain redundant states. Two states are equivalent when every remaining input makes both accept or both reject. Begin Moore's refinement by separating accepting states from rejecting states. State D reaches the accepting group on b; A, B and C do not. Split D off. Now B reaches D on b, while A and C do not. Split again. Refinement stops when transitions always lead to the same groups. A and C remain equivalent and can merge. The result has four reachable states. Over a fixed alphabet, the minimal complete DFA is unique up to renaming states; the state names and drawing need not be identical.
Determinism has a price. Take the strings of zeros and ones whose n-th symbol from the end is a one. An NFA for it is tiny: it guesses when the last n symbols begin, and checks. It needs n plus one states. But the smallest deterministic machine has two to the n. We built them all here: for n equals twelve, the subset construction gives four thousand and ninety-seven states, and minimizing removes just one of them. The guess an NFA gets for free, a DFA has to pay for in memory.
A distinguishability argument proves the deterministic-state lower bound. Choose any two different strings of n bits. Number positions from zero at the left, and let i be a position where the strings differ. Append exactly i zeros. The differing bit is now the n-th bit from the end: the extended length is n plus i and that bit's zero-based index is i. One extension belongs to the language and the other does not. A deterministic machine must therefore be in different states after the two original strings. There are two to the n such prefixes, pairwise distinguishable, so at least two to the n states are necessary. The n equals three enumeration checks the implementation of these witnesses; the argument proves the result for every n.
Lazy determinization can trade time for memory. Cache an encountered NFA state set and its transitions. A repeated transition can then use a table lookup. Engines such as RE2 can use this strategy alongside other execution paths, subject to memory budgets. Our experiment reads the first three hundred thousand characters of Pride and Prejudice, asking whether the n-th character from the end is e. The table shows how many distinct sets this particular text reaches, compared with the exponential space of possible histories. Caching helps on this sample. It does not remove the exponential worst case or guarantee that a few thousand states suffice for other patterns and texts. Real engines need cache limits and fallback strategies.
5Kleene's theoremGraduate2 min
Now the last side of the triangle: from any automaton, a regular expression. Take the divisible-by-three machine, and add a new start state and a new accepting state, joined by epsilon arrows. Let arrows carry whole regular expressions, not just symbols. Now remove the original states one at a time. To remove a state q, every path that went through it, from p into q and out to r, is replaced by one arrow from p to r, labelled: the way in, then q's loop any number of times, then the way out. Remove state two: the trip from one to two and back becomes a loop on one, zero, one star, zero. Remove state one: the trip from zero to one and back becomes one, then that loop starred, then one. Remove state zero: its loop becomes a star, and what is left is a single arrow carrying a single expression. That is where the strange expression of chapter two came from, and we checked it against the machine on every number up to four thousand and ninety-five.
Automata make closure properties constructive. Union, concatenation and star preserve regularity. For complement, first use a complete deterministic machine over the chosen alphabet, including a rejecting sink when necessary, then exchange accepting and rejecting states. For intersection, track a pair of machine states over a common alphabet and accept only when both components accept. The corresponding expression can be awkward to write by hand, even though the automaton construction is straightforward. Equivalence is decidable too: compare acceptance throughout the reachable product, or minimize complete DFAs and compare them up to renaming. A finite set of test strings alone would not decide equivalence.
6What regular languages cannot doDegree3 min
Is every language regular? No, and the proof is a counting argument. Suppose a deterministic machine with p states reads a string of length p or more. After p symbols it has visited p plus one states, so by the pigeonhole principle it has been in some state twice. Call the part of the string read before the first visit x, the part between the two visits y, and the rest z. Reading y takes the machine round a loop, back to where it was. So it cannot tell the difference if we go round that loop twice, or ten times, or not at all: x y y z, and x z, end in the same state as x y z. That is the pumping lemma, from Yehoshua Bar-Hillel, Micha Perles and Eli Shamir in 1961: in a regular language, every long enough string has a short, non-empty piece near its start that can be pumped.
Now use the lemma to rule out a language. Suppose a DFA with p states recognizes a to the n followed by b to the n. Choose p a's followed by p b's; the picture illustrates p equals five. Every allowed split has x y of length at most p and a nonempty y, so y contains only a's. Pumping y twice adds at least one a and no b. All fifteen splits in this picture fail, and the same argument works for every p, without enumerating its splits. The assumed DFA would accept a string outside the language. That contradiction rules out every finite number of states; the finite picture illustrates the general proof.
The distinction matters when reading programs. If balanced parentheses were regular, intersecting them with the regular pattern opening-brackets-star then closing-brackets-star would leave equal numbers of opens and closes, a language the same pumping argument rules out. Ordinary finite automata therefore cannot validate arbitrary nesting. A fixed depth limit changes the language, and engines with recursion or other extensions go beyond mathematical regular expressions. Myhill and Nerode give another proof for a to the n b to the n: different counts of initial a's require different states, since a suitable suffix of b's distinguishes each pair. Regular expressions are useful for this language's token forms; recognizing its unbounded nested syntax needs more memory. A stack supplies that memory in chapter ten.
7Backtracking enginesIndustry4 min
Many familiar regex engines use backtracking, with optimizations that vary by engine and pattern. Our deliberately simple matcher tries ways of partitioning four a's among the repeated groups of parenthesized a-plus, followed by b. With no b, each completed partition fails. For n positive a's there are two to the n minus one partitions into nonempty consecutive groups: choose a cut or no cut at each gap. A naive backtracker can revisit these possibilities one by one. This explains an exponential failure mode; it does not say every real engine explores every partition for every expression. Thompson's simulation instead merges paths that reach the same state at the same input position. Many possible histories collapse into a bounded set of active states.
The counters and timings show different aspects of the same failing pattern. Our deliberately naive backtracker counts more than twenty-nine million steps at length twenty-two, while the NFA active-set counter grows linearly. That counter is a work proxy, not an instruction count. The displayed Python measurements also show rapid growth; their seconds belong to this host and engine version. Perl is fast on this case because its optimizations avoid much of the naive search. This observation gives no linear guarantee for every Perl pattern. GNU grep handles the million-character input efficiently here. Its baseline-subtracted estimate is noisy, especially near zero. Compare the trend and the execution strategy, rather than treating any one duration as a universal constant.
Polynomial search can also exhaust a service. Our simplified pattern is dot-star, dot-star, equals, dot-star, searched without anchoring in text lacking equals. A naive search explores starting positions and overlapping splits, giving cubic growth for this experiment. This is an illustration of the outage mechanism, not a claim that every engine executes the original rule identically. Read the measured Python durations and any timeout limits in the table. The GNU grep column is a noisy baseline-subtracted comparison. Stack Overflow's 2016 whitespace-regex outage supplies another example of a small rule interacting badly with long input. Automata engines such as RE2 offer linear input-time guarantees for fixed supported patterns. Pattern size, compilation, memory limits and supported features still matter; backreferences are outside RE2's supported language.
Why retain backtracking engines? Their features and matching semantics can be useful, but some features go beyond regular languages. This whole-string matcher captures at least two ones and then repeats exactly that captured group. For unary strings of length k at least two, it matches precisely the composite lengths: k has at least two equal groups, each of size at least two. Handle zero and one separately before calling its negation a primality test. A backreference can require an arbitrarily long earlier substring to recur. General backreference patterns can therefore describe nonregular languages. With both the pattern and text supplied as inputs, matching standard backreference expressions is NP-complete. This combined-complexity statement is not a lower bound for every fixed pattern. Choose an engine by its supported features, semantics and resource guarantees. Backtracking is one implementation choice, not the definition of every extended regex language.
8Lexing the Pebble languageDegree3 min
The first stage of reading a program is lexing: grouping its characters into tokens, the words of the language. In the Pebble language there are seven kinds, and each is a regular expression. White space and comments, which are read and thrown away. Numbers, character literals and strings. Names. And operators and punctuation, from single characters up to the two-character operators like arrow and double equals. Keywords like while and return are read as names and then looked up in a table, which keeps the automaton small.
Token boundaries require a policy. This lexer uses maximal munch: choose the longest matching token. Greater-than followed by equals forms one token; so does arrow. For x minus minus greater-than y, no token begins with two minuses. The tokens are x, minus, arrow, y. Equal-length rule matches use rule priority. Separately, our lexer first reads an identifier and then checks the keyword table: while becomes a keyword, while whiles remains an identifier. The combined construction has ninety-six NFA states and thirty reachable DFA states over the sampled alphabet used here. Lexer generators apply this general construction with their own character-set and priority conventions.
Now apply the lexer to the Job. The lookup line becomes tokens with kinds, lexemes and source locations: names, keywords, operators and punctuation. The complete sample has two thousand two hundred and eighty-five characters on eighty-eight lines, producing six hundred and fifty-one non-end-marker tokens. More than half are operators or punctuation. The parser consumes these tokens. It still needs their spelling and locations for identifiers, literals and diagnostics; it no longer has to rediscover character-level token boundaries.
One famous language breaks the clean division of labour. In Python, blocks are marked by indentation, and indentation is nesting, which, as we saw, no finite automaton can track. So Python's lexer keeps a stack of indentation levels. When a line is indented further, it pushes the new level and emits an INDENT token; when a line is indented less, it pops, emitting one DEDENT for each level it leaves. Here is Python's own tokenizer, run on a small function: three INDENTs going in, three DEDENTs coming out. To the parser, INDENT and DEDENT are simply opening and closing braces.
9Context-free grammarsDegree3 min
Nesting needs a more powerful description: a grammar. Here is a grammar for arithmetic expressions. It has three rules, each with alternatives separated by a bar. E, T and F are nonterminals: names for kinds of phrase, an expression, a term and a factor. Plus, times, the brackets and id are terminals: the tokens the lexer produces. A rule says that wherever its left side appears, it may be replaced by its right side, whatever surrounds it; that is what context-free means. Notice the third rule: an expression in brackets is a factor, so the grammar can nest without limit. Noam Chomsky defined such grammars in 1956 as a model of human language. Four years later John Backus and Peter Naur used the same idea to define ALGOL 60, the first major programming language defined by a formal grammar, and nearly every language since has had one.
To show that a string is in the language, derive it. Start from E, and rewrite one nonterminal at a time, here always the leftmost. E becomes E plus T; that E becomes T, then F, then id. Then T becomes T times F, and so on, until only tokens are left: id plus id times id. The same derivation, drawn as a tree, is the parse tree: each nonterminal's children are what it was rewritten into. And the tree is the point. Because the multiplication was built inside a T, below the plus, it binds more tightly. The grammar has encoded the precedence of the operators in its shape.
A simpler grammar for the same expressions would say: an expression is two expressions joined by plus or times, or an id. But then id plus id times id has two parse trees. In one, the addition is done first; in the other, the multiplication. Two trees, two meanings, two different answers. The grammar is ambiguous. And it gets worse quickly. With more operands, the number of trees grows like the Catalan numbers: fourteen for five operands, and over fifty-eight thousand for twelve. We counted them with the CYK algorithm of chapter eleven. The layered grammar with expressions, terms and factors describes the same strings with exactly one tree each. Removing ambiguity is part of designing a language.
The dangling else illustrates a grammar choice. In if c then if c then x else x, the else could attach to the inner or outer if. This ambiguous grammar permits both trees; the finite enumeration displays the two choices. Many language specifications choose the nearest unmatched if. That convention can be expressed by a suitable grammar or by parser resolution rules; it is not supplied by this ambiguous grammar alone. Pebble avoids the choice by requiring braces around each branch. Finding two trees proves a particular grammar ambiguous. Deciding whether an arbitrary context-free grammar is ambiguous is undecidable. Failure to find a counterexample by finite testing would not prove unambiguity.
10Stacks and the Chomsky hierarchyDegree4 min
Give a finite automaton one extra thing, a stack: an unbounded pile it can push symbols onto and pop them from, but only at the top. That is a pushdown automaton. For a to the n b to the n, it needs only three states. In the first, it pushes a marker for every a. Then it moves to the second state and pops a marker for every b. If the stack is back to its bottom exactly when the input runs out, there were as many b's as a's. The stack is the unbounded counter that the pumping lemma said no finite machine could have.
Nondeterminism does not enlarge the regular languages, but it does enlarge what a single-stack automaton can recognize. Consider unmarked palindromes over a and b. A stack can store a first half and compare it with the reverse of the second, but the midpoint is not announced. A nondeterministic pushdown automaton can guess that midpoint; our simulator explores guesses and accepts when one succeeds. This unmarked two-symbol palindrome language is not deterministic context-free. A visible middle separator, or a unary alphabet, changes that claim. Nondeterministic pushdown automata recognize exactly the context-free languages. Deterministic pushdown automata recognize a proper subclass. With the usual end-marker conventions, LR methods characterize deterministic context-free languages, while a particular grammar may still have conflicts. Programming-language syntax often aims for a deterministic core.
The hierarchy relates grammar restrictions to machine resources. Regular languages correspond to finite automata. They describe the token forms used here. Context-free languages correspond to nondeterministic pushdown automata, including unbounded nested syntax. Context-sensitive languages correspond to linear-bounded machines, under the usual empty-word conventions. Equal runs of a's, b's and c's give a standard language in this class that is not context-free; the context-free pumping lemma supplies a proof. Recursively enumerable languages are recognized by Turing machines. Recognition may run forever on strings outside the language. No finite workspace limit is fixed in advance. Compiler design separates these responsibilities: tokenization, syntax, then name and type checks. Part thirteen implements a small compiler checker; Part fourteen studies types more deeply. The hierarchy guides this separation without assigning every production-language feature a simple grammar class.
Production languages often need information beyond a context-free syntax table. In C, a star b semicolon can declare a pointer when a is a typedef name, or form an expression otherwise. Parsers commonly consult a symbol table; one implementation technique is called the lexer hack. In C plus plus, template-dependent names can affect disambiguation. Unrestricted template computation makes some semantic decisions undecidable in an idealized unbounded model; this is more specific than saying every syntactic parsing task is undecidable. Real implementations impose resource limits. Perl can execute code during compilation, and declarations can change how later text is interpreted. Its unrestricted compilation model has analogous limits, beyond recognizing strings with a fixed grammar. The hierarchy remains useful for separating responsibilities. Pebble uses a deliberately simple context-free syntax, with a conflict-free LALR grammar; later passes check names, types and other semantic conditions.
11Parsing any grammar: CYK and EarleyGraduate2 min
General context-free recognition can be organized as dynamic programming. Convert the grammar to Chomsky normal form: rules producing two nonterminals or one terminal, with the empty-string case handled separately. Grammar conversion can change size and derivation multiplicities even while preserving the language. In the CYK table, a cell records which nonterminals derive a particular input span. Single-token spans supply the first row. For each larger span, try its split points and rules of the form A to B C. Combine the corresponding smaller cells. The start symbol in the full-span cell means acceptance. For a fixed grammar this gives an O n cubed worst-case upper bound; grammar size contributes when the grammar is also part of the input. The table can retain parse information, but enumerating every tree of an ambiguous grammar can cost much more.
Earley's method works directly with context-free grammar rules, including left recursion and ambiguity. At each input position it stores items: a rule, a dot marking progress, and the position where that rule began. Prediction adds rules for an expected nonterminal. Scanning advances a dot across a matching input token. Completion advances items waiting for a nonterminal that has just finished. Duplicate items must be merged, and nullable rules need careful handling. A completed start item spanning the entire input means acceptance. For fixed grammars, the standard worst-case bound is cubic, improving to quadratic for unambiguous grammars; suitable specialized implementations achieve linear bounds on important deterministic families. Those time bounds concern the complete algorithm, not just the number of stored items.
These curves count stored Earley items, separately from elapsed time. On sums of identifiers in our layered expression grammar, the sampled item counts grow approximately linearly with token count. On the ambiguous grammar, the counts grow faster: the sixty-five-token sample stores two thousand three hundred and seventy-seven items. More parse trees need not mean that every tree is explicitly enumerated. The side panel also records a CYK duration from this host. Restricted predictive and LR grammars let the next chapters use simpler, linear-time parsing strategies.
12Top-down parsingGraduate4 min
The simplest way to write a parser is by hand, top down. Write one function for each nonterminal, which reads exactly the tokens of that kind of phrase, calling the other functions for the phrases inside it. But try it on our grammar. E is E plus T, so the function for E first calls the function for E, which calls the function for E, forever, without reading a single token. The cure is to rewrite left recursion as right recursion: an expression is a term followed by a tail of plus-terms, which may be empty. Or, as hand-written parsers really do it, as a loop: parse a term, then as long as the next token is a plus, take it and parse another term.
To make the choices automatic, compute two sets. FIRST of a phrase is the set of tokens it can begin with: a term can begin with an id or an opening bracket. FOLLOW of a nonterminal is the set of tokens that can appear right after it: after an expression, a closing bracket or the end. From these, fill a table. In the row for each nonterminal and the column for each token, write the rule to use when that nonterminal is expected and that token is next. A rule that can produce nothing goes under the tokens that can follow. If every cell holds at most one rule, the parser never has to guess: the grammar is LL one, for Left to right, Leftmost derivation, one token of lookahead. The left-recursive grammar had four clashing cells.
Here is the predictive parser on this LL one grammar. Its stack records what remains to be recognized, beginning with the start nonterminal. A nonterminal expands using the table entry for the lookahead token; a terminal must match that token. For this fixed, conflict-free grammar, parsing takes linear time in input length. The table removes guessing; error handling and semantic checks are separate concerns. Hand-written recursive descent is also widely used in production compilers. C and C plus plus front ends such as GCC and Clang add semantic disambiguation, richer lookahead and other machinery. Calling them recursive descent does not make their full languages or implementations LL one.
Expressions with many precedence levels make long, tedious grammars: one nonterminal per level. Vaughan Pratt's method, from 1973, replaces them with numbers. Each operator gets a binding power: or binds weakest, then and, comparisons, plus and minus, times and divide, prefix operators, and strongest of all calls, indexing and field access. The whole expression parser is one loop. Parse a prefix; then, as long as the next operator binds more tightly than the caller's limit, take it and parse its right side with that operator's power as the new limit. On a plus b times c minus d, the times grabs b and c before the plus can, and the minus, at the same power as the plus, waits its turn, so subtraction groups to the left. This is the expression parser of the Pebble language, and of many real compilers.
13Bottom-up parsingGraduate4 min
A top-down parser must choose a rule before it has seen the phrase. A bottom-up parser waits until it has seen all of it. It has two moves. Shift: push the next token onto a stack. Reduce: when the top of the stack is the complete right side of a rule, replace it by the rule's left side. Watch id times id plus id. Shift id, and reduce it to F, then to T. Now the next token is times: shift it, and the second id, and reduce T times F to T. Then the plus comes: reduce T to E, shift, and reduce the last id all the way up, until the stack holds a single E and the input is empty. Read backwards, the reductions are a rightmost derivation; the parser built the tree from the leaves up. The hard part is knowing when to reduce, and by which rule. That is what the numbers on the stack are for.
LR items make the shift-or-reduce decision mechanical. An item is a production with a dot marking progress. Each state collects items that can be active together; this grammar has twelve such states. Read a viable stack prefix through the automaton. The connected example follows T, then star, then F; the state numbers under the item boxes are the corresponding stack path. The current state summarizes what prefixes can follow. In the two red states, a completed E-to-T item requests reduction, while another item permits shifting star. LR zero supplies no lookahead to distinguish those actions, so the table has conflicts.
Lookahead can resolve these conflicts. SLR allows a reduction only when the next token belongs to FOLLOW of the rule's left side. In this expression grammar, that removes the LR zero conflicts. Canonical LR one attaches lookahead to items. This example grows from twelve states to twenty-two. With standard end-marker conventions, LR grammars characterize deterministic context-free languages, but not every grammar describing such a language is already LR one. LALR merges canonical states with the same LR zero core and combines lookaheads. It returns this example to twelve states, and handles the assignment grammar that defeats SLR. Merging can introduce conflicts in other grammars that canonical LR one handles. Yacc popularized LALR. Bison supports LALR and other construction modes; the comparison here uses the selected LALR configuration rather than a claim about every Bison invocation.
Bison supplies an external cross-check on these grammar tables. In the selected configurations, its state counts are one above ours because of its extra end-of-input acceptance state. Agreement in counts is useful evidence, but does not by itself prove the transition tables are identical. On the dangling-else grammar, both tools report one shift-reduce conflict. With else as lookahead, reducing the inner if competes with shifting else. Bison's default shift resolution attaches it to the nearest unmatched if. A language can express that convention through grammar design, parser precedence or other specification rules; the ambiguous grammar alone allows both trees.
14The Pebble language, parsedGraduate3 min
Now we can design the Pebble language with all of this in mind. It has structs, pointers, arrays and functions, enough to write the Job. Declarations put the name first, then its type. C does it the other way round, and pays for it: in C, a star b semicolon is either a multiplication or the declaration of a pointer, depending on whether a names a type, so a C parser has to consult the symbol table while it parses. Every statement starts with a keyword or an expression, so one token of lookahead decides what comes next. And every branch of an if is a block in braces, so there is no dangling else.
Here is part of the grammar of the Pebble language, written as plain context-free rules. Seventy-nine rules in all, with the expression levels spelled out for the LR tables. Our LALR construction gives a table of a hundred and forty-six states, with no conflicts at all, and even the simpler SLR method has none. Bison, given the same rules, agrees: one more state, as always, and no conflicts. And both parsers we built, the table-driven LR parser and the hand-written recursive descent parser with Pratt's method for expressions, accept all six hundred and fifty-one tokens of the Job. Two independent parsers agreeing on the same grammar is the kind of check this series relies on.
This is what all the machinery produces. The loop at the heart of lookup, as an abstract syntax tree. The brackets, braces and semicolons are gone; they were only there to show the structure, and now the structure itself is explicit. The loop has a condition and a body; the body is an if and an assignment; the condition of the if is an and of a comparison and a call. The whole Job becomes three hundred and seventy-one nodes like these. In Part 13, the compiler walks this tree and writes Pebble machine code, replacing the assembly we have written by hand since Part 6.
A parser must also handle invalid input. These four fragments omit an expression, semicolon, name or colon, and our parser reports a token position and an expectation. A conflict-free predictive or LR parser can detect when the input prefix can no longer extend to a sentence of its grammar, under its parsing conventions. That detection point need not be where the programmer made the original mistake. Good diagnostics explain likely causes. Recovery must then choose how to continue without flooding the user with errors caused by the first one. Our small parser demonstrates detection; production-quality recovery requires additional design.
15Frontier: how fast can we parse?Research4 min
For ordinary regular expressions, Thompson simulation gives an O m n upper bound, with pattern size m and text length n. This grid sums active-state counts after input steps on one pattern family: a work proxy, rather than a count of every internal operation. Here doubling either dimension roughly doubles the count. Four-Russians and word-parallel algorithms improve logarithmic factors under their computational-model and preprocessing assumptions. The important question is whether a polynomial improvement is possible. Backurs and Indyk proved conditional hardness for specified pattern types and matching problems. In balanced hard instances, a truly subquadratic algorithm would refute the strong exponential time hypothesis. Easy pattern families still have much faster algorithms. SETH says that for every positive epsilon, some fixed clause width k rules out a k-SAT algorithm taking two to the one-minus-epsilon times the variable count, up to polynomial factors. It remains a conjecture. Bringmann, Gronlund and Larsen later completed a classification for bounded-depth homogeneous membership types, including an intermediate Word Break case. Distinguish that precise result from a blanket classification of all practical regex features.
For a fixed grammar, standard CYK has a cubic worst-case upper bound in input length. These are timings from our implementation. The labeled log-log plot describes this finite measurement range; its fitted slope is an observation, not a complexity proof. Valiant related general context-free recognition to Boolean matrix multiplication. For a fixed grammar, the algebraic approach gives an upper bound governed by the matrix multiplication exponent, with the usual exponent convention. Known bounds put that exponent below two point three seven two; that is a convenient loose bound, not a claim to today's exact record. Asymptotic improvement also need not make an implementation practical. Lee's converse reduction includes grammar size and a retrieval-efficient parsing model. A suitable O g times n to the three-minus-epsilon parser would yield a subcubic Boolean matrix multiplication algorithm; it is not an unrestricted equivalence of every parsing task. Abboud, Backurs and Williams give further conditional evidence, even for constant-size grammars, by reductions from clique problems. Combinatorial is a model distinction here, not a synonym for simple. These results explain tradeoffs and conditional barriers. They do not prove that every grammar needs cubic time, or rule out useful algorithms for restricted grammars.
A derivative asks what can follow a character already read. Brzozowski defined this operation in 1964. For the expression any string of a's and b's followed by a b b, deriving by a leaves two possibilities: that a belonged to the arbitrary prefix, or it began the final a b b. The displayed union captures both. A regular language has finitely many distinct left quotients. These residual languages form its minimal DFA. Raw expression syntax can produce redundant forms, so a derivative implementation needs normalization or equivalence reasoning. Our examples agree with independently minimized machines. Derivative-based lexers and parsers renewed the idea's practical use. Microsoft's nonbacktracking engine uses this family of methods and guarantees linear processing in input length for a supported fixed pattern. It excludes features such as backreferences and lookarounds; the pattern and initialization costs still matter.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Languages as sets of strings, and the machines that recognize them. Regular expressions and finite automata, joined by Thompson's construction, the subset construction and state elimination, with minimization and its two-to-the-n price. The pumping lemma, and why backtracking engines can take exponential time where an automaton takes linear. A lexer for the Pebble language. Context-free grammars, ambiguity and pushdown automata; CYK and Earley; LL one and Pratt from the top down, and LR, SLR and LALR from the bottom up, checked against bison. And the Pebble language's own grammar and parser, run on the Job.
Where this comes back. Part 13 compiles the tree that the parser builds. Part 14 handles what a grammar cannot, such as types and declarations. CYK returns in Part 19 as dynamic programming, and finite automata in Part 21's string algorithms. Part 25 proves that ambiguity is undecidable, and Part 26 explains the NP-completeness of back-references and the hypothesis behind the frontier chapter. And every search engine of Part 47 begins by tokenizing.
In practice, choose an engine by its supported features, complexity guarantees and resource limits. Automata engines such as RE2 provide linear input-time behavior for fixed supported patterns. Backtracking engines include optimizations, but some patterns still create very large searches; use input limits and effective cancellation or time limits when accepting untrusted patterns. Parser generators and handwritten parsers make different tradeoffs. Bison, ANTLR and tree-sitter serve different parsing and editing needs. Production front ends often combine recursive descent with semantic disambiguation. Parsers for data and protocols also need careful validation: a successful syntax parse is only one stage.
Six problems connect the constructions to practice. Pause on any one. The fifth extends Pebble with for loops and two operators, carrying the change through lexing, grammar and parsing. The starred investigation reproduces a regular-expression complexity result and checks its assumptions. The notes distinguish the completed bounded-depth classification from further questions, and separate measured simulator work from a mathematical lower bound.
Next time. The tree becomes a graph, the graph is optimized as a fixed point over lattices, registers are allocated by colouring, and out comes Pebble machine code: written by a program, for the first time in this series. Part 13, The Compiler.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 13 compiles the tree the parser builds; Part 14 handles what a grammar cannot, types and declarations; CYK returns as dynamic programming in Part 19 and finite automata in Part 21's string algorithms; Part 25 proves that ambiguity is undecidable, and Part 26 explains the NP-completeness of back-references and the hypothesis behind the frontier.
Key results
The part's results in one place, for revision.
Try it
Lab 12 · A regex that doubles, and an automaton that does not
Run the part's naive backtracking matcher and its Thompson simulation on (a+)+b against strings of a's with no b, and count their steps. Then determinize 'the n-th symbol from the end is 1' and compare the DFA's size with 2^n, and check every engine against Python's re on random strings.
python -m videos.cs.labs 12
needs numpy, scipy, matplotlib · download lab12.py ·
source on GitHub(a+)+b on 16 a's: backtracking steps 458,750 (7 x 2^16 - 2 = 458,750)
(a+)+b on 16 a's: state-set work 204 (13 x 16 - 4 = 204; the NFA has 16 states)
each two more a's multiply the backtracker by 4.00 (the film: about four)
n-th symbol from the end, n = 10 NFA 64 states subset DFA 1,025 minimal DFA 1,024 = 2^10
(a|b)*abb: NFA, DFA, minimal DFA 14, 5 and 4 states; all agree with Python's re on 400 random strings
Backtracking pays for every way of splitting the a's, 2^(n-1) of them; following all states at once merges them. A DFA never backtracks either, but it can need exponentially many states: here exactly 2^n.
The code (78 lines; it asserts its own result)
"""Lab 12: match (a+)+b two ways, by backtracking and by sets of states, and count what determinism costs."""
from videos.coursekit import labs
import re
import numpy as np
from explainer.cs.lang import automata as A
from explainer.cs.lang import regex as R
TITLE = "A regex that doubles, and an automaton that does not"
GOAL = ("Run the part's naive backtracking matcher and its Thompson simulation on (a+)+b against strings of a's with "
"no b, and count their steps. Then determinize 'the n-th symbol from the end is 1' and compare the DFA's "
"size with 2^n, and check every engine against Python's re on random strings.")
TASKS = [
"Try the pattern (a|aa)+b and then a+b on the same failing inputs. Which one still blows up, and how fast?",
"Build the DFA for 'the n-th symbol from the START is 1' ('(0|1)' * (n - 1) + '1(0|1)*'). How many states now, and why?",
"Count the steps of R.backtrack(R.parse('.*.*=.*'), 'x' * n, anchored=False) for n = 20, 40, 80. What power of n is it?",
]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
node = R.parse("(a+)+b")
nfa = R.thompson(node)
ns = list(range(2, 17, 2))
back, sets = [], []
for n in ns:
matched_b, steps = R.backtrack(node, "a" * n)
matched_n, work, _ = nfa.run("a" * n)
assert not matched_b and not matched_n
assert steps == 7 * 2 ** n - 2, "the naive backtracker tries every way to cut the a's into groups"
assert work == 13 * n - 4, "the set of active states does linear work"
back.append(steps)
sets.append(work)
lab.row("(a+)+b on 16 a's: backtracking steps", f"{back[-1]:,} (7 x 2^16 - 2 = {7 * 2 ** 16 - 2:,})")
lab.row("(a+)+b on 16 a's: state-set work", f"{sets[-1]} (13 x 16 - 4 = {13 * 16 - 4}; the NFA has {nfa.n} states)")
lab.row("each two more a's multiply the backtracker by", f"{back[-1] / back[-2]:.2f} (the film: about four)")
sizes = []
for n in range(1, 11):
dfa = A.from_regex(A.nth_from_end(n), alphabet="01")
sizes.append((R.compile(A.nth_from_end(n)).n, dfa.n, A.minimize(dfa).n))
assert sizes[-1][2] == 2 ** n and dfa.n == 2 ** n + 1, "the smallest DFA needs 2^n states"
lab.row("n-th symbol from the end, n = 10", f"NFA {sizes[-1][0]} states subset DFA {sizes[-1][1]:,} minimal DFA {sizes[-1][2]:,} = 2^10")
pattern = "(a|b)*abb"
engines = R.thompson(R.parse(pattern)), A.from_regex(pattern), A.minimize(A.from_regex(pattern))
agree = 0
for _ in range(400):
text = "".join(rng.choice(list("ab"), int(rng.integers(0, 12))))
want = re.fullmatch(pattern, text) is not None
got = [engines[0].run(text)[0], engines[1].run(text), engines[2].run(text), R.backtrack(R.parse(pattern), text)[0]]
assert got == [want] * 4, text
agree += 1
lab.row(f"{pattern}: NFA, DFA, minimal DFA", f"{engines[0].n}, {engines[1].n} and {engines[2].n} states; "
f"all agree with Python's re on {agree} random strings")
assert (engines[0].n, engines[1].n, engines[2].n) == (14, 5, 4), "the film's three machines"
lab.note = ("Backtracking pays for every way of splitting the a's, 2^(n-1) of them; following all states at once "
"merges them. A DFA never backtracks either, but it can need exponentially many states: here "
"exactly 2^n.")
fig, ax = labs.figure(2, size=(11, 4.2))
ax[0].plot(ns, back, "o-", color=labs.RED, label="backtracking: 7 x 2^n - 2 steps")
ax[0].plot(ns, sets, "o-", color=labs.GREEN, label="sets of states: 13 n - 4")
ax[0].set(yscale="log", title="(a+)+b against n a's and no b", xlabel="number of a's, n", ylabel="steps (log scale)")
ax[0].legend()
n_axis = np.arange(1, 11)
ax[1].plot(n_axis, [s[0] for s in sizes], "o-", color=labs.BLUE, label="Thompson NFA")
ax[1].plot(n_axis, [s[2] for s in sizes], "o-", color=labs.GOLD, label="minimal DFA")
ax[1].plot(n_axis, 2.0 ** n_axis, ls=":", color=labs.MUTED, label="2^n")
ax[1].set(yscale="log", title="The n-th symbol from the end is 1", xlabel="n", ylabel="states (log scale)")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Try the pattern (a|aa)+b and then a+b on the same failing inputs. Which one still blows up, and how fast?
- Build the DFA for 'the n-th symbol from the START is 1' ('(0|1)' * (n - 1) + '1(0|1)*'). How many states now, and why?
- Count the steps of R.backtrack(R.parse('.*.*=.*'), 'x' * n, anchored=False) for n = 20, 40, 80. What power of n is it?
Problems, with solutions
Try each problem before opening its solution.
-
Divisible by 5. Draw a DFA for binary numbers divisible by 5, and turn it into a regular expression by state elimination.
Solution
States 0–4 are remainders; reading bit b takes r to (2r + b) mod 5; start and accept at 0. Eliminating the states in the order 0, 1, 2, 3, 4 (as
automata.to_regexdoes) gives an expression of 275 characters, whichcompute-style checking confirms on every number up to 2,000. The length is the lesson: state elimination is correct but can produce expressions exponentially longer than the automaton, and the order of elimination matters a great deal. -
Equal counts. Use the pumping lemma to show that the strings over {a, b} with as many a's as b's are not regular.
Solution
Suppose a DFA with p states recognizes it. Take s = aᵖbᵖ, which is in the language and has length ≥ p. Any split s = xyz with |xy| ≤ p and |y| > 0 puts y inside the a's, so xy²z has more a's than b's and is not in the language: a contradiction. (Alternatively: intersect with the regular language ab; the result, aⁿbⁿ, would be regular, but chapter 6 showed it is not.)
-
Balanced parentheses. Show that S → S S | ( S ) | ε is ambiguous, and write an unambiguous grammar.
Solution
There are different binary groupings of the three pairs, already proving ambiguity. In fact the original grammar has infinitely many parse trees for every word it generates: insert
S → S Sand derive ε on one branch, arbitrarily often. A language-preserving CNF conversion need not preserve those tree multiplicities; a finite CYK count for the converted grammar is not a count for this original grammar. The grammarS → ( S ) S | εis unambiguous because a nonempty word's first opening parenthesis has a unique matching partner, fixing the recursive split. -
LL(1). Compute FIRST and FOLLOW for S → ( S ) S | ε, and decide whether it is LL(1).
Solution
S is nullable; FIRST(S) = { ( }, FOLLOW(S) = { ), $ }. The table has S, ( → ( S ) S and S, ) → ε, S, $ → ε: one rule per cell, so it is LL(1) (our
ll1_tablereports no conflicts). -
Build: for loops. Add
forloops and the operators+=and++to the Pebble language: lexer, grammar, parser. Does the grammar stay LALR(1)?Solution
Lexer: add
+=and++to the operator rule before+(maximal munch then does the rest) andforto the keywords. Grammar:Stmt → for Simple ; Expr ; Simple Block | … | Simple ;withSimple → Expr | Expr = Expr | Expr += Expr | Expr ++. Our LALR construction on the extended grammar finds 156 states and no conflicts (SLR has none either), so this particular extension is LALR(1). Parser: inParser.stmt, parse an expression and then look for=,+=or++; aforcan lower to initialization, condition and body/update control flow. Preserve loop scope, and makecontinueexecute the update before retesting; blindly replacing it with a while loop would skip that update. The expressions and assignments also need the language's later semantic checks. -
★ Investigate: which regex problem is hard? Reproduce one complexity result, stating its exact input model.
Where to start. Read Backurs–Indyk (2016) together with Bringmann–Grønlund–Larsen (2017). The latter completes a classification of bounded-depth homogeneous membership types, including an intermediate Word Break case; do not present that classification as still unfinished. (a) State the pattern type, whether the task is membership or substring matching, and whether pattern size is fixed or variable. (b) Reproduce a small reduction or implement the corresponding easy-case algorithm. (c) Compare predictions with the simulator grid, explaining why finite active-set counts establish neither a general lower bound nor an engine-runtime guarantee. Further research must identify a specific extension outside the completed classification and check current literature before calling it open.
Notes and sources
Glossary
字母表 alphabet · 串 string · 空串 empty string · 语言 language · 识别器 recognizer · 语法分析器 parser · 正则表达式 regular expression · 并 / 连接 / 星号 union / concatenation / star · 有限自动机 finite automaton · 确定性 / 非确定性 deterministic / nondeterministic · ε 边 ε-edge · 汤普森构造 Thompson's construction · 子集构造 subset construction · 最小化 minimization · 可区分 distinguishable · 状态消去 state elimination · 克莱尼定理 Kleene's theorem · 封闭性 closure property · 泵引理 pumping lemma · 回溯 backtracking · 回溯引用 back-reference · 词法分析 lexing · 记号 token · 最长匹配 maximal munch · 上下文无关文法 context-free grammar · 终结符 / 非终结符 terminal / nonterminal · 推导 derivation · 语法树 parse tree · 歧义 ambiguity · 悬空 else dangling else · 下推自动机 pushdown automaton · 乔姆斯基层级 Chomsky hierarchy · 乔姆斯基范式 Chomsky normal form · 自顶向下 / 自底向上 top-down / bottom-up · 递归下降 recursive descent · 左递归 left recursion · FIRST 集 / FOLLOW 集 FIRST / FOLLOW sets · 绑定力 binding power · 移进 / 归约 shift / reduce · 项 item · 冲突 conflict · 抽象语法树 abstract syntax tree · 导数 derivative
Sources
Canon. Books: Sipser, Introduction to the Theory of Computation, ch. 1–2; Hopcroft, Motwani & Ullman, Introduction to Automata Theory, Languages, and Computation; Aho, Lam, Sethi & Ullman, Compilers: Principles, Techniques, and Tools (the Dragon Book), ch. 2–4; Grune & Jacobs, Parsing Techniques: A Practical Guide; Nystrom, Crafting Interpreters.
Papers: Kleene, "Representation of events in nerve nets and finite automata" (1956); Chomsky, "Three models for the description of language" (1956); Moore, "Gedanken-experiments on sequential machines" (1956); Rabin & Scott, "Finite automata and their decision problems" (1959); Backus et al., "Report on the algorithmic language ALGOL 60" (1960); Bar-Hillel, Perles & Shamir, "On formal properties of simple phrase structure grammars" (1961); Brzozowski, "Derivatives of regular expressions" (1964); Knuth, "On the translation of languages from left to right" (1965); Younger, "Recognition and parsing of context-free languages in time n³" (1967); Thompson, "Regular expression search algorithm" (1968); Lewis & Stearns, "Syntax-directed transduction" (1968); DeRemer, "Practical translators for LR(k) languages" (1969) and "Simple LR(k) grammars" (1971); Earley, "An efficient context-free parsing algorithm" (1970); Pratt, "Top down operator precedence" (1973); Valiant, "General context-free recognition in less than cubic time" (1975); Johnson, "Yacc: yet another compiler-compiler" (1975); Lesk, "Lex: a lexical analyzer generator" (1975); Aho, "Algorithms for finding patterns in strings" (1990); Myers, "A four Russians algorithm for regular expression pattern matching" (1992).
Recent. Lee, "Fast context-free grammar parsing requires fast Boolean matrix multiplication" (2002); Cox, "Regular expression matching can be simple and fast" (2007); Owens, Reppy & Turon, "Regular-expression derivatives re-examined" (2009); Might, Darais & Spiewak, "Parsing with derivatives" (2011); Abboud, Backurs & Vassilevska Williams, "If the current clique algorithms are optimal, so is Valiant's parser" (2015); Backurs & Indyk, "Which regular expression patterns are hard to match?" (2016); Bringmann, Grønlund & Larsen, "A dichotomy for regular expression membership testing" (2017); Moseley et al., "Derivative based nonbacktracking real-world regex matching with backtracking semantics" (2023); Stack Overflow, outage postmortem, 20 July 2016; Cloudflare, "Details of the Cloudflare outage on July 2, 2019".
About this partfrom its README
Part 12 of a sixty-one-part course in computer science (see the series plan and
the syllabus), in Act III, Speaking to the Machine. To compile a program, something must first
read it. This part builds the theory of reading: languages as sets of strings, regular expressions and finite
automata, grammars and pushdown automata, and seven parsing algorithms, ending with the Pebble language's own lexer,
grammar and parser. The tools live in explainer/cs/lang/: regex.py (Thompson's construction, a backtracking
matcher, Brzozowski derivatives), automata.py (the subset construction, minimization, state elimination, pushdown
automata), grammar.py (FIRST/FOLLOW, LL(1), LR(0), SLR, LALR, LR(1), CYK, Earley) and pebble_lang.py (the
language: tokens, AST, recursive-descent and Pratt parser, its grammar, and the Job written in it), all tested in
tests/test_cs12_lang.py against Python's re, brute-force enumeration and textbook counts; the LR tables are also
checked against bison on this machine. Every number is computed in compute.py.
- Six characters and an expensive rejection.
(a+)+bon failing all-a inputs; recorded Python growth, a 30-second timeout, and a noisy process-baseline-subtracted grep comparison. Cloudflare's 2019 outage motivates a separately labeled simplified experiment. - 1. Languages. Finite alphabets, finite strings and possibly infinite languages; recognition versus parsing; syntax acceptance versus semantic checks; memory models without fixed workspace bounds.
- 2. Regular expressions. Union, concatenation and star over a chosen alphabet. Ordinary syntax is regular; practical backreferences require separate treatment. The binary-divisibility example accepts epsilon and leading zeros by convention.
- 3. Thompson. A 14-state NFA for
(a|b)*abb, its epsilon closure and active-set trace onbabbabb. Epsilon consumes no input but takes computation. A bounded-degree Thompson construction gives O(mn) time and O(m) active storage; measured counters are work proxies. - 4. Subsets and minimization. Five reachable DFA states reduce to four. Minimal complete DFAs are unique up to renaming over a fixed alphabet. The n-th-from-end lower bound uses pairwise distinguishability; the n=3 enumeration checks 28 witnesses. Lazy caching helps the chosen book sample without removing exponential worst cases.
- 5. Kleene. State elimination, complete-DFA complement, product intersection and decidable equivalence. A finite round-trip test checks an implementation; the construction supplies the general argument.
- 6. Pumping. An arbitrary-p contradiction for aⁿbⁿ, illustrated by all 15 splits at p=5. Balanced parentheses are ruled out using intersection with opens-then-closes; a nonregular subset alone would not suffice. Fixed nesting depth changes the language.
- 7. Engine strategies. Partition enumeration explains one naive exponential failure mode. Real engines optimize differently. The simplified unanchored Python
.*.*=.*experiment shows superlinear behavior, with censored measurements labeled. The unary composite matcher assumes length at least two. Backreference NP-completeness is a combined pattern-and-text statement. - 8. Lexing. Seven token rules, longest-match policy and identifier-to-keyword lookup. The combined 96-state NFA has 30 reachable DFA states on the sampled alphabet. The Job has 2,285 characters, 651 tokens and locations/lexemes retained for the parser. Literal code tokens stay exact in both languages. Python's indentation uses a stack.
- 9. Grammars. Derivations, parse trees, precedence, Catalan counts and dangling else. A nearest-else convention can be encoded through grammar design or parser resolution. Arbitrary CFG ambiguity is undecidable.
- 10. Hierarchy. A stack for aⁿbⁿ and nondeterministic midpoint guessing for unmarked binary palindromes. Marked or unary palindromes differ. Production-language semantic disambiguation and unrestricted compile-time computation exceed a fixed CFG recognizer; actual compilers impose resource limits.
- 11. General CFG parsing. CYK's triangle and Earley's items. Bounds assume a fixed grammar; empty-input CNF needs special handling. Item counts, elapsed time and worst-case bounds are distinct.
- 12. Top down. Recursive descent, FIRST/FOLLOW, a conflict-free LL(1) table and 17-step trace, plus Pratt binding powers. Production recursive-descent front ends need not be LL(1).
- 13. Bottom up. LR(0), SLR, LR(1) and LALR; merging equal LR(0) cores can introduce conflicts. Bison's selected tables agree in counts and conflicts, with its additional acceptance state. This is not a proof of table isomorphism.
- 14. Pebble. A 79-rule, 146-state conflict-free LALR grammar (Bison: 147), the Job's 371-node AST and four error examples. The detection token need not locate the original mistake; syntax does not establish type correctness.
- 15. Frontier. Honest log-millisecond timing axes and a fitted finite-sample slope. Specify regex pattern families, membership versus search, SETH quantifiers and computational models. The bounded-depth homogeneous membership classification was completed in 2017, with an intermediate Word Break case. Valiant, Lee and clique reductions have distinct model/grammar-size assumptions. Residual languages give the minimal derivative DFA; raw expression syntax needs normalization or equivalence reasoning. .NET's nonbacktracking guarantee concerns supported fixed patterns.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Languages as sets of strings; recognition against parsing; the ladder of memory.
- Regular expressions (Kleene 1951); the divisible-by-3 DFA (callback to Part 5); Kleene's theorem as a triangle.
- Thompson's construction (1968): regex to NFA, simulated on sets of states in O(mn), measured.
- The subset construction (Rabin and Scott 1959) and Moore's minimization; the n-th-from-end language needs 2ⁿ states (computed to n = 12; Myhill–Nerode checked); lazy determinization as grep and RE2 do it, on real text.
- Kleene's theorem: DFA to regex by state elimination; closure properties; decidable equivalence.
- The pumping lemma, with aⁿbⁿ not regular (every split enumerated); nesting is out of reach.
- Backtracking engines: (a+)+b measured in Python, Perl and grep; the 2019 Cloudflare and 2016 Stack Overflow outages; Cox's argument for RE2; back-references (a composite-number regex) and NP-hardness.
- Lexing: maximal munch; the lexer for the Pebble language; Python's INDENT/DEDENT stack.
- Context-free grammars (Chomsky 1956; BNF for ALGOL 60): derivations, parse trees, ambiguity (Catalan counts, dangling else), undecidability of ambiguity.
- Pushdown automata (aⁿbⁿ run; palindromes need nondeterminism); the Chomsky hierarchy; the CFL pumping lemma; real languages at the edges (C's lexer hack, C++ and Perl).
- CYK in O(n³) as dynamic programming (Part 19); Earley's algorithm; both measured.
- Top-down parsing: recursive descent; LL(1) with FIRST and FOLLOW; removing left recursion; Pratt parsing.
- Bottom-up parsing: shift–reduce; LR(0) items and the LR automaton (Knuth 1965); SLR, LALR (yacc), LR(1); conflicts; checked against bison.
- The Pebble language parsed: its grammar (79 rules, a conflict-free 146-state LALR table), its parser, its ASTs, its error messages.
- Frontier: how fast can we parse? Thompson's O(mn) measured; Myers; Backurs and Indyk (2016) under SETH; Valiant (1975), Lee (2002), Abboud–Backurs–Williams (2015); Brzozowski derivatives, which give the minimal DFA on every example, and their revival (Owens–Reppy–Turon 2009, parsing with derivatives 2011, .NET 2022).
- Outro. (Undecidable questions about grammars are previewed in chapter 9 and proved in Part 25.)
Computed: our Thompson regex engine against a backtracking one (timing blow-up); subset-construction sizes; CYK and Earley on ambiguous sentences; the LR tables for the Pebble grammar. Visuals: tokens multiplying along ε-edges; states merging in the subset construction; the pumping lemma cutting a string; parse trees growing top-down and bottom-up; the LR automaton. In practice: regex engines (RE2, PCRE), parser generators and incremental parsers (ANTLR, tree-sitter), configuration and query languages, protocol parsers. Reading: Sipser ch. 1–2; Hopcroft, Motwani & Ullman; Aho, Lam, Sethi & Ullman, Compilers (the Dragon Book) ch. 2–4; Grune & Jacobs, Parsing Techniques; Thompson 1968; Knuth 1965; Cox 2007; Pratt 1973; Nystrom, Crafting Interpreters.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
被 5 整除。 画出识别能被 5 整除的二进制数的 DFA,并用状态消去法把它变成正则表达式。
解答
状态 0–4 表示余数;读入位 b 时,r 变成 (2r + b) mod 5;起始状态和接受状态都是 0。按 0、1、2、3、4 的顺序 消去(
automata.to_regex就是这样做的),得到一个 275 个字符的表达式,对 2,000 以内的每个数都检验无误。长度本身就是 教训:状态消去是正确的,但得到的表达式可能比自动机长得多,而消去顺序影响很大。 -
个数相等。 用泵引理证明:{a, b} 上 a 和 b 一样多的串不是正则语言。
解答
设有一个 p 个状态的 DFA 识别它。取 s = aᵖbᵖ,它在语言中且长度不小于 p。任何满足 |xy| ≤ p、|y| > 0 的切分 s = xyz 都使 y 落在 a 里,于是 xy²z 的 a 比 b 多,不在语言中:矛盾。(也可以:与正则语言 ab 求交,得到 aⁿbⁿ,它会 是正则的,但第六章已证明它不是。)
-
括号匹配。 证明 S → S S | ( S ) | ε 是有歧义的,并写出一个无歧义的文法。
解答
三对括号可以有不同的二叉分组,这已经证明歧义。事实上,原文法生成的每个串都有无穷多棵语法树:反复插入
S → S S,并让一侧导出 ε。保持语言的 CNF 转换未必保持这些树的重数;转换后文法的有限 CYK 计数,不是原文法的计数。S → ( S ) S | ε无歧义,因为非空串的第一个左括号有唯一的配对右括号,唯一决定递归切分。 -
LL(1)。 计算 S → ( S ) S | ε 的 FIRST 和 FOLLOW,判断它是否 LL(1)。
解答
S 可空;FIRST(S) = { ( },FOLLOW(S) = { ), $ }。分析表中 S, ( → ( S ) S,S, ) → ε,S, $ → ε:每格一条 规则,所以是 LL(1)(我们的
ll1_table报告没有冲突)。 -
动手:for 循环。 给 Pebble 语言加上
for循环和运算符+=、++:词法、文法、语法分析器。文法还是 LALR(1) 吗?解答
词法:在运算符规则里把
+=和++放在+之前(其余交给最长匹配),把for加进关键字。文法:Stmt → for Simple ; Expr ; Simple Block | … | Simple ;,Simple → Expr | Expr = Expr | Expr += Expr | Expr ++。 我们的 LALR 构造在扩展后的文法上得到 156 个状态、没有冲突(SLR 也没有),所以是。语法分析器:在Parser.stmt里 先分析一个表达式,再看后面是=、+=还是++;for可以降低为初始化、条件与循环体及更新控制流,但必须保持作用域,并让continue先执行更新再检查条件;直接替换为 while 会跳过这一步。表达式和赋值还需后续语义检查。 -
★ 研究:哪一种正则问题困难? 重现一项复杂度结果,并明确输入模型。
从哪里开始。 对照阅读 Backurs–Indyk(2016)与 Bringmann–Grønlund–Larsen(2017)。后者完成了有界深度齐次模式的成员判定类型分类,其中包含处于中间复杂度的 Word Break;不能把这个分类说成尚未完成。(a)说明模式类型、整串成员判定还是子串匹配,以及模式大小固定还是随输入变化。(b)重现一个小型归约,或实现相应容易类别的算法。(c)与模拟器网格比较,解释为什么有限活跃集合计数既不能证明一般下界,也不能保证引擎耗时。进一步研究必须选定已经完成的分类以外的具体扩展,并检查当前文献后才称其为开放问题。
Build the film
python -m videos.cs.cs12.compute # the part's numbers, into .cache/cs12
python tools/build.py cs12 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs12 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs12. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs12.compute # every number in the part (a few minutes: it waits for Python's re)
python tools/build.py cs12 -q l # a 480p preview
python tools/build.py cs12 # 1080p
The timings (blowup, cloudflare, primes, cyk, frontier) belong to the computer that runs them; the
automata, grammars and tables are exact.