Control Flow:条件分支、逻辑短路与循环
Crafting Interpreters:Control Flow
本章为 Lox 加入 conditional execution、logical operators、while 和 for loops,让程序能够根据状态改变执行路径。
TL;DR
- Control flow 让程序不再只是从上到下执行,而是根据条件选择、重复或跳过代码。
- if statement 只执行一个分支;else 解决二路选择,但需要明确 dangling else 的绑定规则。
- logical operators 使用 short-circuit evaluation:右侧 expression 只在必要时求值。
- while 是最基本的 loop;for 可以通过 desugaring 转换成 initializer、while 和 increment。
- syntactic sugar 不增加语言的表达能力,却能以更贴近用户意图的形式降低常见代码的书写成本。
目录
| 章节 | 内容 |
|---|---|
| Turing machines | 为什么需要 control flow |
| Conditional execution | if/else 与 dangling else |
| Logical operators | truthiness 与短路 |
| While loops | 重复执行 |
| For loops | desugaring |
| Challenges | 扩展练习 |
| Design Note:Spoonfuls of Syntactic Sugar | 语法糖的取舍 |
Turing machines
目前的 Lox 程序只有两种行为:依次执行 statements,或者在 expression 中计算值。没有 control flow,程序无法根据输入改变下一步做什么,也无法重复执行同一段逻辑。
理论上,一门语言只要能表达足够强的 computation,就可以通过组合少数原语完成复杂任务。Turing machine 用极少的机械部件展示了这一点:

但“能表达”不等于“容易写”。实践中的语言会提供 conditional 和 loop,让常见控制结构直接出现在 source code 中。
Conditional execution
if statement 计算 condition。如果结果为 truthy,就执行 then branch;否则执行 else branch(如果存在)。statement AST 需要保存 condition、thenBranch 和 elseBranch。
if (condition) thenBranch
else elseBranch
else 与最近的、尚未匹配 else 的 if 绑定,这就是 dangling else 规则:

Parser 在 if 后先解析 then statement;如果下一个 token 是 else,就消费它并解析 else statement。Interpreter 只执行选中的 branch,因此未执行的分支不会产生副作用,也不会访问其中的非法运行时操作。
Logical operators
Lox 的 logical and/or 不是普通 binary operator。它们需要 short-circuit:
- false and anything 直接返回 false;
- true or anything 直接返回 true;
- 只有无法由左侧确定结果时,才 evaluate 右侧。
因此 logical operator 的 visitor 不能先把左右 operand 都求出来,而要先计算左侧,再按 operator 和 truthiness 决定是否继续。返回值是 operand 本身,而不一定是 Boolean;这使它可以用于默认值表达式。
While loops
while statement 重复执行 body,只要 condition 仍然 truthy:
while (condition) body
Interpreter 每次循环开始重新 evaluate condition。condition 变为 falsey 后退出。由于 body 可能改变变量,不能把 condition 的结果缓存起来。
while 是实现其他 loop 的基础。它也为后续 break、continue 等控制转移提供了自然的扩展位置。
For loops
for statement 把循环常见的三部分放在一起:
for (initializer; condition; increment) body
initializer 最多执行一次;每轮开始前检查 condition;body 执行完成后执行 increment。
Desugaring
Lox 不必为 for 建立新的 runtime machinery。Parser 可以把 for 转换成已有的 AST:
- initializer 放在 block 的开头;
- condition 成为 while 的 condition;省略时使用 true;
- body 后追加 increment;
- 如果存在 initializer,用 block 包住整个 while,使 initializer 的变量只在 loop 内可见。

这种转换叫 desugaring:用户看到的是便捷语法,interpreter 执行的仍是 if、block 和 while。只要转换保持语义等价,language implementation 就不需要为每一种表面语法增加一套执行逻辑。
Challenges
1. Break
添加 break statement,在最近的 loop 中止执行。需要处理嵌套 loop,并决定 break 出现在非 loop 位置时的错误信息。
2. Continue
添加 continue,使循环跳到下一轮。注意 for loop 中 increment 的执行时机:continue 应在 increment 之后进入下一轮。
3. Switch
设计 switch statement,并说明 fall-through、default、case expression 是否只计算一次以及局部 scope 的规则。
Design Note:Spoonfuls of Syntactic Sugar
Syntactic sugar 是对已有语义的更方便包装。for loop 可以 desugar 成 while;compound assignment、postfix increment 等也常常属于这一类。
语法糖的好处是把用户意图直接映射为熟悉结构。例如 for 的 initializer、condition、increment 位于同一处,读者无需在 body 和外部变量之间来回寻找循环控制逻辑。
代价是 grammar、parser、错误位置和调试展示都可能变复杂。糖越多,用户需要学习的表面语法越多;不同糖之间若组合不一致,也会产生 edge cases。合理的规则是:高频、语义清晰且可稳定 desugar 的模式值得加入;只有为了炫技而增加的语法则会扩大语言负担。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、Java 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
statement → exprStmt
| ifStmt
| printStmt
| block ;
ifStmt → "if" "(" expression ")" statement
( "else" statement )? ;
Code block 2
"Expression : Expr expression",
Code block 3
"If : Expr condition, Stmt thenBranch," +
" Stmt elseBranch",
Code block 4
"Print : Expr expression",
Code block 5
private Stmt statement() {
Code block 6
if (match(IF)) return ifStatement();
Code block 7
if (match(PRINT)) return printStatement();
Code block 8
private Stmt ifStatement() {
consume(LEFT_PAREN, "Expect '(' after 'if'.");
Expr condition = expression();
consume(RIGHT_PAREN, "Expect ')' after if condition.");
Stmt thenBranch = statement();
Stmt elseBranch = null;
if (match(ELSE)) {
elseBranch = statement();
}
return new Stmt.If(condition, thenBranch, elseBranch);
}
Code block 9
if (first) if (second) whenTrue(); else whenFalse();
Code block 10
@Override
public Void visitIfStmt(Stmt.If stmt) {
if (isTruthy(evaluate(stmt.condition))) {
execute(stmt.thenBranch);
} else if (stmt.elseBranch != null) {
execute(stmt.elseBranch);
}
return null;
}
Code block 11
false and sideEffect();
Code block 12
expression → assignment ;
assignment → IDENTIFIER "=" assignment
| logic_or ;
logic_or → logic_and ( "or" logic_and )* ;
logic_and → equality ( "and" equality )* ;
Code block 13
"Literal : Object value",
Code block 14
"Logical : Expr left, Token operator, Expr right",
Code block 15
"Unary : Token operator, Expr right",
Code block 16
private Expr assignment() {
Code block 17
Expr expr = or();
Code block 18
if (match(EQUAL)) {
Code block 19
private Expr or() {
Expr expr = and();
while (match(OR)) {
Token operator = previous();
Expr right = and();
expr = new Expr.Logical(expr, operator, right);
}
return expr;
}
Code block 20
private Expr and() {
Expr expr = equality();
while (match(AND)) {
Token operator = previous();
Expr right = equality();
expr = new Expr.Logical(expr, operator, right);
}
return expr;
}
Code block 21
@Override
public Object visitLogicalExpr(Expr.Logical expr) {
Object left = evaluate(expr.left);
if (expr.operator.type == TokenType.OR) {
if (isTruthy(left)) return left;
} else {
if (!isTruthy(left)) return left;
}
return evaluate(expr.right);
}
Code block 22
print "hi" or 2; // "hi".
print nil or "yes"; // "yes".
Code block 23
statement → exprStmt
| ifStmt
| printStmt
| whileStmt
| block ;
whileStmt → "while" "(" expression ")" statement ;
Code block 24
"Print : Expr expression",
Code block 25
"Var : Token name, Expr initializer",
Code block 26
"While : Expr condition, Stmt body"
Code block 27
));
Code block 28
if (match(PRINT)) return printStatement();
Code block 29
if (match(WHILE)) return whileStatement();
Code block 30
if (match(LEFT_BRACE)) return new Stmt.Block(block());
Code block 31
private Stmt whileStatement() {
consume(LEFT_PAREN, "Expect '(' after 'while'.");
Expr condition = expression();
consume(RIGHT_PAREN, "Expect ')' after condition.");
Stmt body = statement();
return new Stmt.While(condition, body);
}
Code block 32
@Override
public Void visitWhileStmt(Stmt.While stmt) {
while (isTruthy(evaluate(stmt.condition))) {
execute(stmt.body);
}
return null;
}
Code block 33
for (var i = 0; i < 10; i = i + 1) print i;
Code block 34
statement → exprStmt
| forStmt
| ifStmt
| printStmt
| whileStmt
| block ;
forStmt → "for" "(" ( varDecl | exprStmt | ";" )
expression? ";"
expression? ")" statement ;
Code block 35
{
var i = 0;
while (i < 10) {
print i;
i = i + 1;
}
}
Code block 36
import java.util.ArrayList;
Code block 37
import java.util.Arrays;
Code block 38
import java.util.List;
Code block 39
private Stmt statement() {
Code block 40
if (match(FOR)) return forStatement();
Code block 41
if (match(IF)) return ifStatement();
Code block 42
private Stmt forStatement() {
consume(LEFT_PAREN, "Expect '(' after 'for'.");
// More here...
}
Code block 43
consume(LEFT_PAREN, "Expect '(' after 'for'.");
Code block 44
Stmt initializer;
if (match(SEMICOLON)) {
initializer = null;
} else if (match(VAR)) {
initializer = varDeclaration();
} else {
initializer = expressionStatement();
}
Code block 45
}
Code block 46
initializer = expressionStatement();
}
Code block 47
Expr condition = null;
if (!check(SEMICOLON)) {
condition = expression();
}
consume(SEMICOLON, "Expect ';' after loop condition.");
Code block 48
}
Code block 49
consume(SEMICOLON, "Expect ';' after loop condition.");
Code block 50
Expr increment = null;
if (!check(RIGHT_PAREN)) {
increment = expression();
}
consume(RIGHT_PAREN, "Expect ')' after for clauses.");
Code block 51
}
Code block 52
consume(RIGHT_PAREN, "Expect ')' after for clauses.");
Code block 53
Stmt body = statement();
return body;
Code block 54
}
Code block 55
Stmt body = statement();
Code block 56
if (increment != null) {
body = new Stmt.Block(
Arrays.asList(
body,
new Stmt.Expression(increment)));
}
Code block 57
return body;
Code block 58
}
Code block 59
if (condition == null) condition = new Expr.Literal(true);
body = new Stmt.While(condition, body);
Code block 60
return body;
Code block 61
body = new Stmt.While(condition, body);
Code block 62
if (initializer != null) {
body = new Stmt.Block(Arrays.asList(initializer, body));
}
Code block 63
return body;
Code block 64
var a = 0;
var temp;
for (var b = 1; a < 10000; b = temp + b) {
print a;
temp = a;
a = b;
}
参考资料
- 原文:Control Flow
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)