跳到主要内容

计算理论与编译器⟦number⟧

大学计算机科学知识点 11

本主题的视频课程 打开视频页面
5:58

计算理论与编译器⟦number⟧

这门课探讨机器能够判定什么,以及文本如何变成有意义的结构。前三个单元是理论:自动机与正则语言、上下文无关语言,以及可计算性。后三个单元是实践,也就是编译器的各个阶段:词法分析、语法分析,以及语义分析和代码生成。课程中的每条运行轨迹、每张表和每个词法单元的位置都经过测试套件检验。

英文讲解 · 可切换中英文字幕

讲义

English

What this course is, and how to use it

This is the eleventh course in University Computer Science: theory of computation and compilers 计算理论与编译器. It covers what machines can decide, and how one program, a compiler, turns text into meaning.

A limit, stated once: this is a study course, not a degree. One small original program is followed through every stage of the pipeline, and every automaton, grammar and table here was actually run, not just sketched.

  • Units 11.1–11.3 are the theory: automata, context-free languages 上下文无关语言 and computability.
  • Units 11.4–11.6 are the practice: lexing, parsing, and semantic analysis with code generation.

The habit to build: every stage is a statement about strings. Each stage either decides something or transforms something, and its output is its guarantee.

Automata and regular languages

Why it matters. Regular languages are exactly what machines with finite memory can decide. They are the upper limit of computation without memory, and the basis of every pattern matcher, including lexers.

The idea. A deterministic finite automaton 确定有限自动机 (DFA) is a set of states plus a transition table. It reads one symbol, moves to a new state, and at the end of the input it accepts or rejects. Our course DFA accepts strings over $\{a, b\}$ that end in $ab$.

State diagrams and acceptance trace
Three states; the trace of the input aabab walks q0-q1-q1-q2-q1-q2 and accepts

The limit: the pumping lemma. Regular languages cannot count without limit. The pumping lemma 泵引理 says that any long enough accepted string can be split as $xyz$, with $|xy| \le p$ and $|y| \ge 1$, so that every $xy^iz$ is still accepted. So $L = \{a^n b^n : n \ge 0\}$ is not regular: if you pump $y$ (which contains only $a$'s), the numbers of $a$'s and $b$'s no longer match.

Worked example 1: the trace, exactly. The DFA for "ends in ab" has these transitions:

state on $a$ on $b$
$q_0$ $q_1$ $q_0$
$q_1$ $q_1$ $q_2$
$q_2$ (accepting) $q_1$ $q_0$
  • The input aabab goes q0 → q1 (a) → q1 (a) → q2 (b) → q1 (a) → q2 (b): it ends in $q_2$, so it is accepted.
  • The input aba goes q0 → q1 → q2 → q1: it ends in $q_1$, so it is rejected.

Worked example 2: from a regex to a DFA. For the pattern ab|ba over $\{a,b\}$, a nondeterministic automaton (NFA) "guesses" which branch to follow. The subset construction turns it into a DFA: after one symbol, the DFA is in the state $\{q_a\}$ or $\{q_b\}$, and it accepts after the matching second symbol. In the worst case, turning an NFA with $n$ states into a DFA needs up to $2^n$ states: that is the price of deciding without guessing.

Common mistakes.

  • Accepting in the middle of the input. A DFA accepts or rejects only at the end.
  • Forgetting the dead state in a table drawn by hand.
  • Claiming that $a^nb^n$ is regular because a regex seems to "nest".

Summary. DFA = states + a table. Regular = decidable with finite memory. The pumping lemma limits the family. NFAs guess, and turning them into DFAs can cost many states.

Context-free languages and parsing theory

Why it matters. Nested structure, such as brackets, expressions and sentences, is beyond regular languages. Context-free grammars 上下文无关语法 (CFGs) are exactly the tool for it.

The idea. A production $A \to \alpha$ rewrites a nonterminal $A$. Our expression grammar:

$$E \to E + T \mid T \qquad T \to T \times F \mid F \qquad F \to (E) \mid \mathbf{id}$$

A derivation 推导 applies productions one by one, and a parse tree 语法分析树 records them.

Parse trees
Two derivations of id + id x id: leftmost and rightmost — same tree iff the grammar is unambiguous

Ambiguity and precedence. With this layered grammar, id + id × id has only one parse tree: × sits under T, deeper than +, so it is done first. The unlayered grammar $E \to E + E \mid E \times E \mid \mathbf{id}$ gives two trees for the same string. This ambiguity 歧义 is cured by designing the grammar in layers, not by hoping.

Worked example 1: a leftmost derivation, written out. Always expand the leftmost nonterminal:

$$\begin{aligned} E &\Rightarrow E + T \Rightarrow T + T \Rightarrow F + T \Rightarrow \mathbf{id} + T \\ &\Rightarrow \mathbf{id} + T \times F \Rightarrow \mathbf{id} + F \times F \\ &\Rightarrow \mathbf{id} + \mathbf{id} \times F \Rightarrow \mathbf{id} + \mathbf{id} \times \mathbf{id} \end{aligned}$$

Eight steps give one tree.

Worked example 2: beyond context-free. The language $\{a^n b^n c^n\}$ needs two independent counts. This language is not context-free, so a more powerful kind of grammar (context-sensitive) or machine is needed. This is the next level of the Chomsky hierarchy, and one reason why checks such as "declared before use" are done after parsing.

Common mistakes.

  • Mixing up the derivation order (leftmost or rightmost) with the shape of the tree.
  • "Solving" ambiguity by choosing a derivation. The string itself must decide the tree.
  • Leaving out the bracket production $F \to (E)$, and then wondering why $(\mathbf{id} + \mathbf{id})$ fails.

Summary. CFGs describe nesting, and the tree is the meaning. Ambiguity is a property of the grammar: use layers to fix precedence. Two independent counts are beyond CFGs.

Computability

Why it matters. Some questions cannot be answered by any algorithm at all. They are not slow or unsolved: they are provably undecidable. The proof technique, diagonalisation, can be reused in many places.

The idea. The Turing machine 图灵机 (TM), with a tape, a head and states, is the formal definition of "algorithm". The halting problem 停机问题 asks: does machine $M$ halt on input $w$? Suppose some decider $H$ could answer this. Build a machine $D(M)$ that runs $H(M, M)$ and, if the answer is "halts", loops for ever. Now run $D$ on itself: if it halts, it loops, and if it loops, it halts. This is a contradiction, so $H$ cannot exist.

Machine model
The diagonal argument as a machine: D flips H's answer about itself — no H can exist

Diagonalisation, once. List all machines $M_1, M_2, \ldots$ and imagine an infinite table that records, for each machine and each input, "halts" or "does not halt". $D$ is built to disagree with the diagonal entry of every row, so $D$ is different from every machine in the list. But $D$ is a machine, so this is a contradiction. The same shape of argument, diagonalisation 对角化, proves that the real numbers cannot be listed, and proves Rice's theorem: every nontrivial property of what programs do is undecidable.

Worked example 1: a decidable relative. "Does DFA $D$ accept no strings at all?" is decidable. Mark every state that can be reached from $q_0$ (a graph search over finitely many states). The answer is yes if no accepting state is marked. Finiteness makes the search possible; the infinite tape of a Turing machine is exactly what breaks it.

Worked example 2: Rice's theorem, applied. "Does program $P$ ever print the word banana?" is a nontrivial property of what $P$ does, so by Rice's theorem it is undecidable. The proof reduces halting to it: wrap a computation so that it prints banana only if the wrapped computation halts. A decider for "prints banana" would then decide halting.

Common mistakes.

  • Reading "undecidable" as "no algorithm known yet".
  • Thinking more time or memory would help. The tape is already infinite.
  • Forgetting that Rice's theorem needs a nontrivial property. "Does $P$ halt on some input?" is nontrivial, so undecidable; a property that every program has, or that no program has, is trivially decidable.

Summary. Turing machines define algorithms. Diagonalisation proves that some questions cannot be answered by any machine; halting is the standard example. Rice's theorem extends this to properties of what programs do. Finiteness keeps DFA questions decidable.

Lexical analysis

Why it matters. The first stage of a compiler turns a stream of characters into tokens 记号, the words of the language. It uses regular expressions, because recognising a token needs no memory.

The idea. Each kind of token is a regular expression. The lexer's DFA runs over the source code, takes the longest possible match, and outputs (token type, text, position). Spaces and comments are thrown away; positions are kept for error messages.

Token pipeline
The course source count = a1 + b2; becomes six tokens with positions — identifier, assignment, operator, punctuation

Why the longest match. The patterns for if, identifiers and numbers overlap at the start (if is also a valid identifier). The longest-match rule reads ifx as one identifier, not as if followed by x. The lexer takes the longest text that any pattern allows, and breaks ties by priority. Get this wrong, and every variable that starts with if breaks.

Worked example 1: the course line, exactly. count = a1 + b2; becomes six tokens:

token text column
IDENT count 1
ASSIGN = 7
IDENT a1 9
PLUS + 12
IDENT b2 14
SEMI ; 16

Worked example 2: the error case. 12abc could be read as NUM(12) followed by IDENT(abc). Some languages allow this; others call it an error, and the lexer's specification must say which. Ours reports a lexical error, with the position: a number followed directly by an identifier, with nothing between them. The error policy is part of the lexer's specification, not an afterthought.

Common mistakes.

  • Deciding on a keyword before reading the whole word (the ifx bug).
  • Throwing away positions. Every later error message then becomes useless.
  • Letting a regex engine backtrack exponentially. DFAs do not backtrack, which is why lexers compile their regexes into DFAs.

Summary. Regexes → DFAs → tokens, using the longest match with priorities. Spaces are dropped, positions are kept, and the error policy is specified.

Parsing

Why it matters. Tokens go in and a tree comes out. The parser is where grammar meets algorithm. Its table-driven forms (LL and LR) turn the theory into a loop plus a stack.

The idea. LL(1) parsing uses one token of lookahead, a table that maps (nonterminal, next token) to a production, and a stack. The FIRST and FOLLOW sets fill in the table; if two productions compete for one cell (a conflict), the grammar is rejected.

Parse table and stack trace
The LL(1) table for the course grammar; the stack trace of parsing id + id — five table lookups, one tree

Why a stack is enough. A leftmost derivation works exactly like a stack: pushing the right side of a production and matching terminals against the input carries out "expand the leftmost nonterminal first". The table can choose when the selection sets of alternatives for each nonterminal do not overlap. A conflict means that one token of lookahead cannot choose the production, so the grammar is not LL(1). Left recursion is the classic cause: with $E \to E + T$, the parser expands $E$ into $E$ again for ever.

Worked example 1: the trace, exactly. The grammar is $E \to TE'$, $E' \to {+}TE' \mid \varepsilon$, $T \to \mathbf{id}$, and the input is id + id:

  1. Expand $E \to T E'$ (table cell $(E, \mathbf{id})$).
  2. Expand $T \to \mathbf{id}$.
  3. Match $\mathbf{id}$.
  4. Expand $E' \to {+} T E'$ (table cell $(E', +)$).
  5. Match $+$.
  6. Expand $T \to \mathbf{id}$.
  7. Match $\mathbf{id}$.
  8. At the end of the input, expand $E' \to \varepsilon$.

Then accept: eight moves, five of them table lookups.

Worked example 2: removing left recursion. $E \to E + T \mid T$ becomes $E \to TE'$, $E' \to {+}TE' \mid \varepsilon$: the loop on the left becomes a tail on the right. The change is mechanical and works for any grammar, but the tree no longer shows left associativity directly, so the compiler must put it back when it builds the abstract syntax tree (AST).

Common mistakes.

  • Using FIRST where FOLLOW belongs when building the table (the $\varepsilon$ rows).
  • Parsing with a left-recursive grammar: the stack grows for ever.
  • Thinking a successful parse means the program is correct. The tree gives the shape, not the meaning.

Summary. FIRST and FOLLOW fill the table, and the stack carries out the derivation. Conflicts reject the grammar. Remove left recursion with the tail trick.

Semantic analysis and code generation

Why it matters. The tree gives the shape; the meaning is in types, scopes and values. Semantic analysis adds to the tree what the grammar cannot express, and code generation turns the finished tree into a form that can run.

The phases of compilation: source code passes through lexical analysis (tokens), syntax analysis (AST), semantic analysis (checks), code generation and optimisation to produce an executable
The phases of compilation, from source code to an optimised executable

The idea.

  • The symbol table 符号表 maps each identifier to its type and scope.
  • Type rules walk the tree from the bottom up: $\mathbf{id} + \mathbf{id}$ needs two numbers.
  • The output is an intermediate representation 中间表示 (IR), such as three-address code: one operation per line.
Symbol table and IR
The course program count = a1 + b2 x 3: the symbol table binds a1, b2 as int; the IR is three three-address instructions with two temps

Why use an IR. Translating each source language straight to each machine needs $m \times n$ compilers for $m$ languages and $n$ machines. With a shared IR, it needs only $m + n$ parts. Optimisations are also written once, on the IR: register allocation, and constant folding (only for literals: $2 \times 3$ becomes $6$, but $b_2 \times 3$ stays as it is). Each optimisation must keep the meaning of the IR the same.

Worked example 1: the course program, exactly. count = a1 + b2 * 3, with a1, b2: int.

  1. Symbol table: (a1, int, global), (b2, int, global), (count, int, global).
  2. Type checks: $b_2 \times 3$ is int × int literal, then $a_1 + (\ldots)$ is int + int. Both are fine.
  3. IR:
t1 = b2 * 3
t2 = a1 + t1
count = t2

That is three instructions with two temporary variables.

Worked example 2: a semantic error. Change the type of b2 to str. The checker rejects b2 * 3 (str × int) and reports the position it got from the lexer. Positions pass from lexing through parsing into semantic errors, and this chain is what makes error messages useful. In the same way, count = a1 + b2 would be rejected for int + str, and the message would point to exactly that +.

Common mistakes.

  • Checking types before names are resolved. Work out the scopes first.
  • Producing IR before every check on the tree is complete.
  • Folding constants through variables: $b_2 \times 3$ is not $6 b_2$.
  • Losing positions at any stage. Every error message then gets worse.

Summary. The symbol table and type rules add meaning to the tree. The IR separates front ends from back ends. Every optimisation must keep the meaning the same. Positions carry the error messages through the whole pipeline.

词汇
English 中文 拼音
theory of computation and compilers/ˈθɪəri ɒv ˌkɒmpjuːˈteɪʃn ænd kəmˈpaɪləz/ 计算理论与编译器 jì suàn lǐ lùn yǔ biān yì qì
deterministic finite automaton/dɪˌtɜːmɪˈnɪstɪk ˈfaɪnaɪt ɔːˈtɒmətn/ 确定有限自动机 què dìng yǒu xiàn zì dòng jī
pumping lemma/ˈpʌmpɪŋ ˈlemə/ 泵引理 bèng yǐn lǐ
context-free grammars/ˈkɒntekst friː ˈɡræməz/ 上下文无关语法 shàng xià wén wú guān yǔ fǎ
derivation/ˌderɪˈveɪʃn/ 推导 tuī dǎo
parse tree/pɑːs triː/ 语法分析树 yǔ fǎ fēn xī shù
ambiguity/ˌæmbɪˈɡjuːɪti/ 歧义 qí yì
Turing machine/ˈtjʊərɪŋ məˈʃiːn/ 图灵机 tú líng jī
halting problem/ˈhɒltɪŋ ˈprɒbləm/ 停机问题 tíng jī wèn tí
diagonalisation/daɪˌæɡənəlaɪˈzeɪʃn/ 对角化 duì jiǎo huà
tokens/ˈtəʊkənz/ 记号 jì hào
context-free languages/ˈkɒntekst friː ˈlæŋɡwɪdʒɪz/ 上下文无关语言 shàng xià wén wú guān yǔ yán
symbol table/ˈsɪmbl ˈteɪbl/ 符号表 fú hào biǎo
intermediate representation/ˌɪntəˈmiːdɪət ˌreprɪˈzenteɪʃn/ 中间表示 zhōng jiān biǎo shì

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

IGCSE, A-Level & AP