Crafting Interpreters:The Lox Language
Crafting Interpreters:The Lox Language
作者:Robert Nystrom
原文章节:3 The Lox Language

TL;DR
本章定义 Lox 的语义:它是一门动态类型、自动内存管理、面向对象的 scripting language;后续两套 interpreter 都将实现这套 language。
目录
| 章节 | 说明 |
|---|---|
| Hello, Lox | 第一个 Lox program |
| A High-Level Language | Lox 的设计取舍 |
| Data Types | Lox 的基本类型 |
| Expressions | expression 与 operator |
| Statements | statement |
| Variables | variable 与 scope |
| Control Flow | 条件与循环 |
| Functions | function 与 closure |
| Classes | class、instance 与 inheritance |
| The Standard Library | 标准库边界 |
| Challenges | 练习 |
| Design Note:Expressions and Statements | syntax 设计 |
Hello, Lox
Lox 是一门为本书设计的 language。先从一个最小 program 开始:
print "Hello, world!";
后面的章节会逐步定义这行 code 中的每个部分,以及 Lox 如何执行它。
A High-Level Language
Lox 是 high-level language:它隐藏 machine 的细节,提供更接近 programmer 意图的 abstraction。设计一门 language 时,不可能只列 feature;还需要决定哪些 feature 不加入,以及不同 feature 如何组合。
Dynamic typing
Lox 是 dynamically typed。Variable 没有固定 type,value 才有 type;同一个 variable 可以在不同时间保存不同类型的 value。这样能减少声明负担并适合 scripting,但错误会推迟到 runtime。
Automatic memory management
Lox 使用 automatic memory management。Programmer 不需要显式释放 object;runtime 负责跟踪 object 的可达性,并在 object 不再使用时回收它。后面的 clox 会实现 garbage collector。
Data Types
Lox 提供 nil、Boolean、number、string、function、class instance 等 value。Nil 表示没有 value;Boolean 只有 true 和 false;number 使用 double precision floating point;string 是字符序列。
Function 是 first-class value,可以保存到 variable、作为参数传递或从其他 function 返回。Class 描述 instance 的行为,instance 保存 fields 并可以调用 methods。
Expressions
Expression 会计算出一个 value。Lox 支持 literal、grouping、unary operator、binary operator、variable access、assignment 和 function call。
Arithmetic
number 支持加、减、乘、除。加法也可以连接 string;其他不兼容的 operand 会产生 runtime error。
Comparison and equality
比较 operator 产生 Boolean value。Equality 对相同类型 value 做相等判断;nil 只与 nil 相等,不同类型的 value 不相等。
Logical operators
and 与 or 使用 short-circuit evaluation:如果左侧已经足以确定结果,右侧不会执行。not 将 truthiness 反转。Lox 的 truthiness 规则很简单:只有 false 和 nil 为 false,其他 value 都为 true。
Precedence and grouping
Operator precedence 决定没有显式 parentheses 时的组合方式;parentheses 可以覆盖默认 precedence。Parser 必须把这些规则编码成 syntax tree 的结构。
Statements
Statement 产生 effect,而不是必须产生 value。Lox 包含 expression statement、print statement、variable declaration 和 block statement。
Block 用大括号包围一组 statement,并创建一个 scope。语句按顺序执行,runtime error 会中断当前执行路径。
Variables
Variable declaration 绑定一个 name 与 value。Assignment 修改已有 binding;读取未定义的 name 是 error。Scope 决定 name 在 source code 的哪些区域可见。
Lox 支持 lexical scope:嵌套 block 可以访问外层 scope 的 variable,外层不能访问内层声明。后续 resolver 会把 name 使用绑定到正确 declaration。
Control Flow
Lox 提供 if/else、while 和 for。If 根据 condition 的 truthiness 选择 branch;while 重复执行 body;for 是更方便的循环 syntax,语义上可以展开成 initializer、condition、increment 与 body。
Functions
Function 是可调用的 value。声明 function 时保存 name、parameter list 和 body;调用时创建新的 environment,把 argument 绑定到 parameter,再执行 body。
Function 可以 return value。Return 会从嵌套执行中跳出;没有显式 return 时,function 返回 nil。参数数量必须与声明匹配。
Closures
Function 可以捕获声明位置外层 scope 中的 variable,这就是 closure。Closure 让 function 即使离开原来的 scope 后,仍能访问它捕获的 binding。
Classes
Lox 是 object-oriented language。Class 包含 methods;instance 保存 fields。访问 property 时,先在 instance fields 中查找,再在 class methods 中查找。

Why might any language want to be object oriented?
Object-oriented language 把 data 与操作 data 的 code 组织在一起。它可以用 abstraction、encapsulation 和 polymorphism 管理复杂 program,但也不是所有问题都需要 class。
Why is Lox object oriented?
Lox 采用 class-based object model,因为它足以表达常见的 object-oriented pattern,同时比更复杂的 object system 容易实现和解释。
Classes or prototypes
另一种常见模型是 prototype-based object system:object 从另一个 object 继承 behavior,而不是从 class 实例化。两种模型都能支持复用与动态 dispatch。

Classes in Lox
Class declaration 创建 class value;method declaration 放入 class 的 method table。调用 instance method 时,method 会绑定 receiver,使 this 指向当前 instance。
Instantiation and initialization
调用 class 会创建 instance。如果 class 有 init method,它会被用作 initializer。Initializer 总是返回 instance 本身,即使 body 中没有显式 return value。
Inheritance
Subclass 可以继承 superclass 的 methods,并通过 super 访问父类实现。继承关系在 class declaration 时建立,method lookup 会沿着 superclass chain 查找。
The Standard Library
Language core 只提供最基本的 built-in function 和 class。Standard library 是 language 实用性的重要部分,但本书的重点是 interpreter architecture,因此只加入少量必要功能,例如 clock。
Challenges
本章的练习要求你修改 Lox 的 semantics、增加 operator、思考 truthiness 和 equality,或比较 class 与 prototype。建议在主实现的副本上完成。
Design Note:Expressions and Statements
Expression 与 statement 的区分会影响 syntax、value flow 和 parser 结构。Expression 通常嵌套并产生 value;statement 通常按顺序执行并产生 effect。不同 language 对二者的边界有不同选择,没有唯一正确答案。
Lox 选择一套相对简单、适合递归下降 parser 的 grammar,让 expression 可以出现在 statement 中,同时用明确的 statement keyword 标识控制结构。
原文代码
下面保留本章原文中的全部 code block;源码内容不翻译,仅翻译 surrounding prose。 +### Code block 1
// Your first Lox program!
print
"Hello, world!"
;
Code block 2
true
;
// Not false.
false
;
// Not *not* false.
Code block 3
1234
;
// An integer.
12.34
;
// A decimal number.
Code block 4
"I am a string"
;
""
;
// The empty string.
"123"
;
// This is a string, not a number.
Code block 5
add
+
me
;
subtract
-
me
;
multiply
*
me
;
divide
/
me
;
Code block 6
condition
?
thenArm
:
elseArm
;
Code block 7
-
negateMe
;
Code block 8
less
<
than
;
lessThan
<=
orEqual
;
greater
>
than
;
greaterThan
>=
orEqual
;
Code block 9
1
==
2
;
// false.
"cat"
!=
"dog"
;
// true.
Code block 10
314
==
"pi"
;
// false.
Code block 11
123
==
"123"
;
// false.
Code block 12
!
true
;
// false.
!
false
;
// true.
Code block 13
true
and
false
;
// false.
true
and
true
;
// true.
Code block 14
false
or
false
;
// false.
true
or
false
;
// true.
Code block 15
var
average
= (
min
+
max
) /
2
;
Code block 16
print
"Hello, world!"
;
Code block 17
"some expression"
;
Code block 18
{
print
"One statement."
;
print
"Two statements."
;
}
Code block 19
var
imAVariable
=
"here is my value"
;
var
iAmNil
;
Code block 20
var
breakfast
=
"bagels"
;
print
breakfast
;
// "bagels".
breakfast
=
"beignets"
;
print
breakfast
;
// "beignets".
Code block 21
if
(
condition
) {
print
"yes"
;
}
else
{
print
"no"
;
}
Code block 22
var
a
=
1
;
while
(
a
<
10
) {
print
a
;
a
=
a
+
1
;
}
Code block 23
for
(
var
a
=
1
;
a
<
10
;
a
=
a
+
1
) {
print
a
;
}
Code block 24
makeBreakfast
(
bacon
,
eggs
,
toast
);
Code block 25
makeBreakfast
();
Code block 26
fun
printSum
(
a
,
b
) {
print
a
+
b
;
}
Code block 27
fun
returnSum
(
a
,
b
) {
return
a
+
b
;
}
Code block 28
fun
addPair
(
a
,
b
) {
return
a
+
b
;
}
fun
identity
(
a
) {
return
a
;
}
print
identity
(
addPair
)(
1
,
2
);
// Prints "3".
Code block 29
fun
outerFunction
() {
fun
localFunction
() {
print
"I'm local!"
;
}
localFunction
();
}
Code block 30
fun
returnFunction
() {
var
outside
=
"outside"
;
fun
inner
() {
print
outside
;
}
return
inner
;
}
var
fn
=
returnFunction
();
fn
();
Code block 31
class
Breakfast
{
cook
() {
print
"Eggs a-fryin'!"
;
}
serve
(
who
) {
print
"Enjoy your breakfast, "
+
who
+
"."
;
}
}
Code block 32
// Store it in variables.
var
someVariable
=
Breakfast
;
// Pass it to functions.
someFunction
(
Breakfast
);
Code block 33
var
breakfast
=
Breakfast
();
print
breakfast
;
// "Breakfast instance".
Code block 34
breakfast
.
meat
=
"sausage"
;
breakfast
.
bread
=
"sourdough"
;
Code block 35
class
Breakfast
{
serve
(
who
) {
print
"Enjoy your "
+
this
.
meat
+
" and "
+
this
.
bread
+
", "
+
who
+
"."
;
}
// ...
}
Code block 36
class
Breakfast
{
init
(
meat
,
bread
) {
this
.
meat
=
meat
;
this
.
bread
=
bread
;
}
// ...
}
var
baconAndToast
=
Breakfast
(
"bacon"
,
"toast"
);
baconAndToast
.
serve
(
"Dear Reader"
);
// "Enjoy your bacon and toast, Dear Reader."
Code block 37
class
Brunch
<
Breakfast
{
drink
() {
print
"How about a Bloody Mary?"
;
}
}
Code block 38
var
benedict
=
Brunch
(
"ham"
,
"English muffin"
);
benedict
.
serve
(
"Noble Reader"
);
Code block 39
class
Brunch
<
Breakfast
{
init
(
meat
,
bread
,
drink
) {
super
.
init
(
meat
,
bread
);
this
.
drink
=
drink
;
}
}
Code block 40
puts
1
+
if
true
then
2
else
3
end
+
4
~~~+
## 参考资料
- [原文:The Lox Language](https://craftinginterpreters.com/the-lox-language.html)
- [Crafting Interpreters 系列索引](00%20系列索引.md)
> 版权说明:官方页面标注 © 2015–2021。原作版权归 Robert Nystrom 及相关权利人所有。本笔记为个人学习用途的中文翻译。
评论 (0)