Essentials of Compilation:预备知识
Essentials of Compilation:预备知识
本章回顾实现 compiler 所需的基本工具:AST、grammar、pattern matching、recursive function、interpreter,以及一个 partial evaluator 示例。
TL;DR
- 程序在 compiler 内部应表示为 AST:concrete syntax 便于人书写,AST 便于 compiler 访问和变换。
- Grammar 同时定义语言的边界和 AST 的形状;每个 non-terminal 的每个 alternative 都应在结构处理中得到对应处理。
- Structural recursion 是处理 AST 的自然方式:对当前 node 做判断,再递归处理它的 children。
- Definitional interpreter 为语言赋予可执行语义;compiler 的正确性要求编译前后的程序在相同输入下产生相同输出。
- Partial evaluation 可以在编译期计算不依赖输入的部分,但必须保留依赖运行时输入的计算。
名词解释
| 名词 | 含义 | 本章对应物 |
|---|---|---|
| concrete syntax | 程序员实际输入的字符序列 | Racket 源代码,例如 (+ (read) (- 8)) |
| abstract syntax tree(AST) | 去除表面书写细节、保留程序结构的树 | Int、Prim、Program 组成的树 |
| grammar | 构造合法程序的一组规则 | \LangInt{} 的 Exp 规则 |
| terminal | 必须按字面出现在程序中的符号 | read、+、- 等 |
| non-terminal | grammar 定义的抽象类别 | Exp、Int、LangInt |
| definitional interpreter | 作为语言定义的 interpreter | interp_Lint |
| partial evaluation | 提前计算静态部分的过程 | pe_Lint |
目录
| 章节 | 说明 |
|---|---|
| Abstract Syntax Trees | 用 AST 表示程序,并在 Racket 中定义 node |
| Grammars | 用 BNF 描述 LangInt 的 concrete / abstract syntax |
| Pattern Matching | 按 AST 结构访问 node 的各个部分 |
| Recursive Functions | 用 structural recursion 处理整棵 AST |
| Interpreters | 为语言定义执行语义 |
| Example Compiler:a Partial Evaluator | 实现并验证一个 partial evaluator |
Preliminaries
本章回顾实现 compiler 所需的基本工具。程序通常由程序员以文本形式输入,也就是一个字符序列。程序的这种“文本形式”称为 concrete syntax。我们使用 concrete syntax 简洁地书写和讨论程序。
在 compiler 内部,我们使用 abstract syntax tree(AST) 表示程序,因为这种表示能够高效支持 compiler 需要执行的各种操作。从 concrete syntax 到 abstract syntax 的转换过程称为 parsing。本书不讨论 parsing 的理论和实现;支持代码已经提供了把 concrete syntax 转换为 abstract syntax 的 parser。
AST 在 compiler 内部有很多种表示方式,取决于实现 compiler 所使用的 programming language。我们使用 Racket 的 struct feature 表示 AST(见 Abstract Syntax Trees)。
我们使用 grammar 定义 programming language 的 abstract syntax(见 Grammars),使用 pattern matching 检查 AST 中的单个 node(见 Pattern Matching),并使用 recursive function 构造和拆解 AST(见 Recursive Functions)。本章会简要介绍这些概念。
Abstract Syntax Trees
Compiler 使用 AST 表示程序,是因为它们经常需要提出这样的疑问:程序的某个部分对应哪一种 language feature?它有哪些 sub-part?考虑下面左侧的程序和右侧的 AST。这个程序是一个 addition operation,包含两个 sub-part:一个 read operation 和一个 negation。negation 还包含另一个 sub-part,即整数常量 8。用 tree 表示程序之后,我们就能沿着链接从程序的一部分方便地走到它的 sub-parts。
(+ (read) (- 8))
flowchart TD
plus["+"] --> read["read"]
plus --> minus["-"]
minus --> eight["8"]
我们使用描述 tree 的标准术语来描述 AST:上图中的每个矩形称为一个 node。箭头把一个 node 连接到它的 children(它们同样也是 node)。最上面的 node 是 root。除 root 之外,每个 node 都有一个 parent,也就是把它作为 child 的 node。没有 children 的 node 称为 leaf node;否则称为 internal node。
在 compiler 中,我们为每一种 node 定义一个 Racket struct。本章只需要两种 node:一种表示整数常量,另一种表示 primitive operation。下面是整数常量的 struct 定义。所有 AST structure 都定义在支持代码的 utilities.rkt 中。
(struct Int (value))
一个 integer node 只包含一个东西:整数值。要创建表示整数 8 的 AST node,可以写:
(define eight (Int 8))
我们称由 (Int 8) 创建的值为 Int structure 的一个 instance。
下面是 primitive operation 的 struct 定义:
(struct Prim (op args))
一个 primitive operation node 包含一个 operator symbol op,以及一个 child args 列表。例如,要创建一个把数字 8 negate 的 AST,可以写:
(define neg-eight (Prim '- (list eight)))
Primitive operation 可以有零个或多个 children。read operator 没有 child:
(define rd (Prim 'read '()))
Addition operator 有两个 children:
(define ast1_1 (Prim '+ (list rd neg-eight)))
我们对 Prim structure 做了一个设计选择。我们没有为每个 operation(read、+、-)分别定义 structure,而是使用一个 structure 表示多种 operation。当然,也可以这样定义:
(struct Read ())
(struct Add (left right))
(struct Neg (value))
之所以只使用一个 structure,是因为 compiler 的许多部分对不同 primitive operator 的处理代码是相同的;既然如此,使用单一 structure 就可以把这段代码只写一次。
编译类似上面程序的 program 时,我们需要知道 root node 关联的 operation 是 addition,并且能够访问它的两个 children。Racket 提供了 pattern matching 来支持这类查询,下一节会看到具体用法。
即使我们真正想到的是 AST,也经常写出程序的 concrete syntax,因为 concrete syntax 更简洁。我们建议:在脑中始终把 program 想成 abstract syntax tree。
Grammars
可以把一个 programming language 看成一组 program。这组 program 通常是无限的——总能构造出更大的 program——因此不可能通过列出所有 program 来描述一门语言。我们会写下一组用于构造 program 的规则,也就是 grammar。
Grammar 经常用于定义语言的 concrete syntax,但也可以用于描述 abstract syntax。我们使用 Backus-Naur Form(BNF)的一个变体来书写规则。作为例子,我们描述一门名为 LangInt 的小型语言,它由整数和 arithmetic operation 组成。
LangInt 的 abstract syntax 的第一条 grammar rule 表示:一个 Int structure 的 instance 是一个 expression:
$$ \mathrm{Exp} ::= \mathrm{Int}(\mathrm{Int}) $$
每条 rule 都有 left-hand side 和 right-hand side。如果你有一个 AST node 与 right-hand side 匹配,就可以根据 left-hand side 对它进行分类。
等宽字体中的 symbol 是 terminal symbol,只有当它们按字面出现在 program 中时,这条 rule 才适用。我们的 grammar 不提及 white-space,也就是用于分隔的字符,例如空格、tab 和换行。为了消除歧义并提高可读性,可以在 symbol 之间插入 white-space。
像 Exp 这样的名称由 grammar rule 定义,称为 non-terminal。Int 也是一个 non-terminal,不过我们不通过 grammar rule 定义它,而用下面的说明定义:一个 Int 是由 decimal digit(0 到 9)组成的序列,可以选择以 - 开头(表示负整数),并且这些 decimal digit 表示的整数落在 -2^62 到 2^62 - 1 的范围内。这样可以用 63 bit 表示整数,从而简化 compiler 的若干方面。在 64-bit machine 上,这些整数对应 Racket 的 fixnum datatype。
第二条 grammar rule 是 read operation,它从 program 的用户处接收一个 input integer:
$$ \mathrm{Exp} ::= \mathrm{read} $$
第三条 rule 把一个 Exp node 的 negation 归类为 Exp:
$$ \mathrm{Exp} ::= -(\mathrm{Exp}) $$
我们可以应用这些 rule,把属于 LangInt 的 AST 进行分类。例如,根据第一条 rule,(Int 8) 是一个 Exp;再根据 negation rule,下面的 AST 也是一个 Exp:
Neg(Int(8))
flowchart TD
minus(("-")) --> eight(("8"))
接下来的 grammar rule 用于 addition 和 subtraction expression:
$$ \begin{aligned} \mathrm{Exp} &::= +(\mathrm{Exp},\mathrm{Exp})\ \mathrm{Exp} &::= -(\mathrm{Exp},\mathrm{Exp}) \end{aligned} $$
现在可以证明前面的 AST 是 LangInt 中的一个 Exp。根据 read rule,read 是一个 Exp;我们已经把 Neg(Int(8)) 分类为 Exp,因此应用 addition rule,可以证明:
$$ +(\mathrm{read},\mathrm{Neg}(\mathrm{Int}(8))) $$
是 LangInt 中的一个 Exp。
如果某个 AST 不适用于上述 rule,那么它就不属于 LangInt。例如,(* (read) 8) 不属于 LangInt,因为没有针对 * operator 的 rule。每当我们用 grammar 定义一门语言时,这门语言只包含那些能够由 grammar rule 证明为合法的 program。
LangInt 的最后一条 grammar rule 说明,存在一个 Program node 用来标记整个 program 的顶层:
$$ \mathrm{LangInt} ::= \mathrm{Program}(\texttt{'()},\mathrm{Exp}) $$
Program structure 定义如下:
(struct Program (info body))
其中 body 是一个 expression。在后面的章节中,info 部分会用于存储辅助信息;但现在它只是 empty list。
多个 grammar rule 可能拥有相同的 left-hand side、不同的 right-hand side,例如 LangInt grammar 中关于 Exp 的 rule。作为简写,可以使用 vertical bar 把多个 right-hand side 合并到一条 rule 中。
下面两张图分别汇总 LangInt 的 concrete syntax 和 abstract syntax。这里的框体对应原书中的排版图;其中的 Racket 版规则保留如下。
LangInt 的 concrete syntax
Type ::= Integer
Exp ::= Int | (read) | (- Exp) | (+ Exp Exp) | (- Exp Exp)
LangInt ::= Exp
LangInt 的 abstract syntax
Type ::= Integer
Exp ::= Int(Int) | Read()
| Neg(Exp) | Add(Exp, Exp) | Sub(Exp, Exp)
LangInt ::= Program('(), Exp)
支持代码中的 read-program function 从文件读入一个 program(也就是 Racket concrete syntax 中的字符序列),再把它 parse 成 abstract syntax tree。关于 read-program 的更多信息,请参见 Appendix 中对 utilities 的描述。
Pattern Matching
如 Abstract Syntax Trees 一节所述,compiler 经常需要访问 AST node 的各个部分。Racket 提供了 match feature,用于访问一个 value 的组成部分。考虑下面的例子:
(match ast1_1
[(Prim op (list child1 child2))
(print op)])
上面的 match form 检查 AST 是否为一个 binary operator,并把它的各个部分绑定到三个 pattern variable:op、child1 和 child2。通常,一个 match clause 由一个 pattern 和一个 body 组成。Pattern 以递归方式定义为以下几种形式之一:pattern variable;structure name 后面跟着针对该 structure 每个 argument 的 pattern;或者 S-expression(symbol、list 等)。完整的 match 说明请参考 Racket Guide 的 match 章节 和 Racket Reference 的 match 章节。
Match clause 的 body 可以包含任意 Racket code。Pattern variable 在 body 的 scope 内可用,例如 (print op) 中的 op。
一个 match form 可以包含多个 clause。下面的 leaf function 用于识别一个 LangInt node 是否为 AST 中的 leaf。match 按顺序处理 clause,检查 pattern 是否能够匹配输入 AST;第一个匹配成功的 clause 的 body 会被执行。右侧展示了它对几个 AST 的输出。
(define (leaf arith)
(match arith
[(Int n) #t]
[(Prim 'read '()) #t]
[(Prim '- (list e1)) #f]
[(Prim '+ (list e1 e2)) #f]
[(Prim '- (list e1 e2)) #f]))
(leaf (Prim 'read '()))
(leaf (Prim '- (list (Int 8))))
(leaf (Int 8))
#t
#f
#t
构造 match expression 时,我们先参考 grammar definition,确定希望匹配的是哪个 non-terminal;然后确保:1)对于这个 non-terminal 的每个 alternative 都有一个 clause;2)每个 clause 中的 pattern 都对应 grammar rule 的相应 right-hand side。
在 leaf function 的 match 中,我们参考 LangInt 的 abstract syntax grammar。Exp non-terminal 有 5 个 alternatives,所以 match 有 5 个 clauses。每个 pattern 对应一条 grammar rule 的 right-hand side。例如,(Prim '+ (list e1 e2)) 对应 +(Exp, Exp)。从 grammar 转换到 pattern 时,把 Exp 这样的 non-terminal 替换成任意你选择的 pattern variable,例如 e1 和 e2。
Recursive Functions
Program 天生具有递归结构。例如,一个 expression 通常由更小的 expression 组成。因此,处理整个 program 的自然方式是使用 recursive function。
作为这种 recursive function 的第一个例子,我们在下面定义 is_exp function。它接收任意 value,并判断该 value 是否是 LangInt 中的 expression。
当一个 function 使用一组与 grammar 对应的 match clauses 定义,并且每个 clause 的 body 都对每个 child node 进行 recursive call 时,我们称这个 function 使用了 structural recursion。这种根据 data definition 组织 code 的原则,在 Felleisen 等人的《How to Design Programs》中有专门倡导。
本章还定义了 is_Lint,它判断一个 AST 是否为 LangInt 中的 program。通常,我们可以针对 grammar 中的每个 non-terminal 各写一个 recursive function。下面示例的两个 program 中,第一个属于 LangInt,第二个不属于。
(define (is_exp ast)
(match ast
[(Int n) #t]
[(Prim 'read '()) #t]
[(Prim '- (list e)) (is_exp e)]
[(Prim '+ (list e1 e2))
(and (is_exp e1) (is_exp e2))]
[(Prim '- (list e1 e2))
(and (is_exp e1) (is_exp e2))]
[else #f]))
(define (is_Lint ast)
(match ast
[(Program '() e) (is_exp e)]
[else #f]))
(is_Lint (Program '() ast1_1))
(is_Lint (Program '()
(Prim '* (list (Prim 'read '())
(Prim '+ (list (Int 8)))))))
flowchart TD
A["is_Lint(program)"] --> B["匹配 Program"]
B --> C["is_exp(body)"]
C --> D["匹配当前 Exp"]
D --> E["递归检查每个 child"]
Interpreters
Program 的 behavior 由 programming language 的 specification 定义。例如,Scheme language 由相关报告定义,Racket language 由其 reference manual 定义。在本书中,我们使用 interpreter 为每一门要研究的语言指定语义。被指定为一门语言定义的 interpreter 称为 definitional interpreter。
我们先为 LangInt 创建一个 definitional interpreter。这个 interpreter 也是 structural recursion 的第二个例子。interp_Lint function 的定义如下:它对输入 program 执行一次 match,然后调用辅助 function interp_exp;后者针对 LangInt expression 的每条 grammar rule 各包含一个 match clause。
(define (interp_exp e)
(match e
[(Int n) n]
[(Prim 'read '())
(define r (read))
(cond [(fixnum? r) r]
[else (error 'interp_exp "read expected an integer" r)])]
[(Prim '- (list e))
(define v (interp_exp e))
(fx- 0 v)]
[(Prim '+ (list e1 e2))
(define v1 (interp_exp e1))
(define v2 (interp_exp e2))
(fx+ v1 v2)]
[(Prim '- (list e1 e2))
(define v1 ((interp-exp env) e1))
(define v2 ((interp-exp env) e2))
(fx- v1 v2)]))
(define (interp_Lint p)
(match p
[(Program '() e) (interp_exp e)]))
[!note] 源文代码注记 上面 subtraction case 中的
((interp-exp env) ...)按源材料原样保留;本章的LangIntinterpreter 实际不需要 environment,若将代码直接运行,应与前面的 case 一样调用interp_exp。这属于源代码片段中的命名不一致,不是语义规则的一部分。
下面考虑几个 LangInt program 的 interpretation 结果。第一个 program 把两个 integer 相加:
(+ 10 32)
结果是 42,也就是“生命、宇宙以及一切的答案”——42!上面写的是 concrete syntax;parse 后的 abstract syntax 是:
(Program '() (Prim '+ (list (Int 10) (Int 32))))
下一个例子展示 expression 可以彼此嵌套;这里嵌套了多个 addition 和 negation:
(+ 10 (- (+ 12 20)))
这个 program 的结果是什么?
LangInt 不支持任意大的 integer,而只支持 63-bit integer,因此我们在 Racket 中使用 fixnum arithmetic 解释 LangInt 的 arithmetic operation。假设:
$$n = 999999999999999999$$
这个数确实能放入 63 bit。运行下面的 program 会发生什么?
(+ (+ (+ n n) (+ n n)) (+ (+ n n) (+ n n))))
它会产生错误:
fx+: result is not a fixnum
我们约定:如果在 definitional interpreter 中运行一个 program 产生 error,那么这个 program 的含义就是 unspecified,除非该 error 是 trapped-error。Compiler 对具有 unspecified behavior 的 program 没有任何义务:它不必产生 executable;即使产生了,那个 executable 也可以执行任意行为。
另一方面,如果 error 是 trapped-error,compiler 就必须产生 executable,并且该 executable 必须报告发生了 error。要 signal 一个 error,应以 return code 255 退出。第 Dynamic Typing 和 Gradual Typing 章节中的 interpreter 会使用 trapped-error。
LangInt 的最后一个 feature 是 read operation,它会提示 program 用户输入一个 integer。回想前面的 program:它请求一个 integer input,然后减去 8。如果运行:
(interp_Lint (Program '() ast1_1))
并输入 50,结果就是 42。
我们把 read operation 加入 LangInt,是为了防止聪明的学生实现出这样一种 compiler:编译期间直接运行 interpreter 得到 output,然后生成一段只负责产生这个 output 的 trivial code。(确实有学生在这门课第一次开课时这样做过!)
Compiler 的工作,是把一种语言中的 program 转换为另一种语言中的 program,使 output program 的行为与 input program 相同。假设有两门语言 L₁ 和 L₂,并且每门语言都有一个 definitional interpreter。给定一个把 L₁ 转换到 L₂ 的 compiler,以及任意一个 L₁ 中的 program P₁,compiler 必须把它转换成某个 P₂,使得在各自 interpreter 上、使用相同 input i 解释 P₁ 和 P₂ 时,得到相同的 output o。
flowchart LR
P1["P₁"] -->|compile| P2["P₂"]
P1 -->|interp_L₁(i)| O["o"]
P2 -->|interp_L₂(i)| O
下一节将看到我们的第一个 compiler 示例。
Example Compiler:a Partial Evaluator
本节考虑一个 compiler:它把 LangInt program 转换为可能更高效的 LangInt program。这个 compiler 会 eager 地计算 program 中不依赖任何 input 的部分,这个过程称为 partial evaluation。
例如,给定下面的 program:
(+ (read) (- (+ 5 3)))
compiler 会把它转换为:
(+ (read) -8)
下面的 code 给出了一个针对 LangInt 的简单 partial evaluator。partial evaluator 的 output 仍然是 LangInt 中的 program。对 Exp 的 structural recursion 被封装在 pe_exp function 中;而 negation、addition 和 subtraction 的 partial evaluation code 则被拆分到三个辅助 function:pe_neg、pe_add 和 pe_sub。
这些 function 的 input 是 children 完成 partial evaluation 后的 output。pe_neg、pe_add 和 pe_sub 检查它们的 arguments 是否为 integer;如果是,就执行相应的 arithmetic;否则就创建表示该 arithmetic operation 的 AST node。
(define (pe_neg r)
(match r
[(Int n) (Int (fx- 0 n))]
[else (Prim '- (list r))]))
(define (pe_add r1 r2)
(match* (r1 r2)
[((Int n1) (Int n2)) (Int (fx+ n1 n2))]
[(_ _) (Prim '+ (list r1 r2))]))
(define (pe_sub r1 r2)
(match* (r1 r2)
[((Int n1) (Int n2)) (Int (fx- n1 n2))]
[(_ _) (Prim '- (list r1 r2))]))
(define (pe_exp e)
(match e
[(Int n) (Int n)]
[(Prim 'read '()) (Prim 'read '())]
[(Prim '- (list e1)) (pe_neg (pe_exp e1))]
[(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
[(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
(define (pe_Lint p)
(match p
[(Program '() e) (Program '() (pe_exp e))]))
为了增强对 partial evaluator 正确性的信心,可以测试它是否产生与 input program 相同结果的 program,也就是测试它是否满足前面的 compiler correctness diagram。
下面的 code 对几个 example 运行 partial evaluator,再测试 output program。parse-program 和 assert function 定义在 Appendix 的 utilities 中。
(define (test_pe p)
(assert "testing pe_Lint"
(equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
(test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
(test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
(test_pe (parse-program `(program () (- (+ 3 (- 5))))))
练习
在 LangInt language 中创建三个 program,测试:先使用 pe_Lint 对它们做 partial evaluation,再使用 interp_Lint 解释,所得结果是否与直接使用 interp_Lint 解释的结果相同。
边界与实践
- AST 不等于 concrete syntax:concrete syntax 中的括号、空白和书写习惯服务于人;compiler 的后续 pass 应围绕 AST 的结构工作。
- Grammar 与 pattern matching 必须同步:增加一个 AST constructor 却不增加对应 match clause,会让结构处理遗漏合法输入。
- Interpreter 是语义基准,不是 compiler 的替代品:
read之所以存在,正是为了让编译期计算不能伪装成运行期执行。 - 整数溢出边界必须明确:在 Racket 版中,超出 fixnum 范围的 arithmetic 会进入 unspecified behavior;后续语言若要求报告错误,则需要
trapped-error约定。 - Partial evaluation 只能计算静态部分:
read的结果在编译时未知,因此必须原样保留;5 + 3则可以折叠为8。
参考资料
评论 (0)