目录
正在加载目录…
正在阅读专栏 Crafting Interpreters:手写解释器 第 11 篇 · 共 35 篇 · 31%

Control Flow:条件分支、逻辑短路与循环

发布于 2026-09-16 19:04 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 3,433 · 预计阅读 7 分钟 👁 10 次阅读

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 executionif/else 与 dangling else
Logical operatorstruthiness 与短路
While loops重复执行
For loopsdesugaring
Challenges扩展练习
Design Note:Spoonfuls of Syntactic Sugar语法糖的取舍

Turing machines

目前的 Lox 程序只有两种行为:依次执行 statements,或者在 expression 中计算值。没有 control flow,程序无法根据输入改变下一步做什么,也无法重复执行同一段逻辑。

理论上,一门语言只要能表达足够强的 computation,就可以通过组合少数原语完成复杂任务。Turing machine 用极少的机械部件展示了这一点:

turing machine

但“能表达”不等于“容易写”。实践中的语言会提供 conditional 和 loop,让常见控制结构直接出现在 source code 中。

Conditional execution

if statement 计算 condition。如果结果为 truthy,就执行 then branch;否则执行 else branch(如果存在)。statement AST 需要保存 condition、thenBranch 和 elseBranch。

text
if (condition) thenBranch
else elseBranch

else 与最近的、尚未匹配 else 的 if 绑定,这就是 dangling else 规则:

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:

text
while (condition) body

Interpreter 每次循环开始重新 evaluate condition。condition 变为 falsey 后退出。由于 body 可能改变变量,不能把 condition 的结果缓存起来。

while 是实现其他 loop 的基础。它也为后续 break、continue 等控制转移提供了自然的扩展位置。

For loops

for statement 把循环常见的三部分放在一起:

text
for (initializer; condition; increment) body

initializer 最多执行一次;每轮开始前检查 condition;body 执行完成后执行 increment。

Desugaring

Lox 不必为 for 建立新的 runtime machinery。Parser 可以把 for 转换成已有的 AST:

  1. initializer 放在 block 的开头;
  2. condition 成为 while 的 condition;省略时使用 true;
  3. body 后追加 increment;
  4. 如果存在 initializer,用 block 包住整个 while,使 initializer 的变量只在 loop 内可见。

sugar

这种转换叫 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

java
statement      → exprStmt
               | ifStmt
               | printStmt
               | block ;

ifStmt         → "if" "(" expression ")" statement
               ( "else" statement )? ;

Code block 2

java
      "Expression : Expr expression",

Code block 3

java
      "If         : Expr condition, Stmt thenBranch," +
                  " Stmt elseBranch",

Code block 4

java
      "Print      : Expr expression",

Code block 5

java
  private Stmt statement() {

Code block 6

java
    if (match(IF)) return ifStatement();

Code block 7

java
    if (match(PRINT)) return printStatement();

Code block 8

java
  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

java
if (first) if (second) whenTrue(); else whenFalse();

Code block 10

java
  @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

text
false and sideEffect();

Code block 12

text
expression     → assignment ;
assignment     → IDENTIFIER "=" assignment
               | logic_or ;
logic_or       → logic_and ( "or" logic_and )* ;
logic_and      → equality ( "and" equality )* ;

Code block 13

java
      "Literal  : Object value",

Code block 14

java
      "Logical  : Expr left, Token operator, Expr right",

Code block 15

java
      "Unary    : Token operator, Expr right",

Code block 16

java
  private Expr assignment() {

Code block 17

java
    Expr expr = or();

Code block 18

java
    if (match(EQUAL)) {

Code block 19

java
  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

java
  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

java
  @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

text
print "hi" or 2; // "hi".
print nil or "yes"; // "yes".

Code block 23

java
statement      → exprStmt
               | ifStmt
               | printStmt
               | whileStmt
               | block ;

whileStmt      → "while" "(" expression ")" statement ;

Code block 24

java
      "Print      : Expr expression",

Code block 25

java
      "Var        : Token name, Expr initializer",

Code block 26

java
      "While      : Expr condition, Stmt body"

Code block 27

text
    ));

Code block 28

java
    if (match(PRINT)) return printStatement();

Code block 29

java
    if (match(WHILE)) return whileStatement();

Code block 30

java
    if (match(LEFT_BRACE)) return new Stmt.Block(block());

Code block 31

java
  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

java
  @Override
  public Void visitWhileStmt(Stmt.While stmt) {
    while (isTruthy(evaluate(stmt.condition))) {
      execute(stmt.body);
    }
    return null;
  }

Code block 33

text
for (var i = 0; i < 10; i = i + 1) print i;

Code block 34

java
statement      → exprStmt
               | forStmt
               | ifStmt
               | printStmt
               | whileStmt
               | block ;

forStmt        → "for" "(" ( varDecl | exprStmt | ";" )
                 expression? ";"
                 expression? ")" statement ;

Code block 35

java
{
  var i = 0;
  while (i < 10) {
    print i;
    i = i + 1;
  }
}

Code block 36

java
import java.util.ArrayList;

Code block 37

java
import java.util.Arrays;

Code block 38

java
import java.util.List;

Code block 39

java
  private Stmt statement() {

Code block 40

java
    if (match(FOR)) return forStatement();

Code block 41

java
    if (match(IF)) return ifStatement();

Code block 42

java
  private Stmt forStatement() {
    consume(LEFT_PAREN, "Expect '(' after 'for'.");

    // More here...
  }

Code block 43

text
    consume(LEFT_PAREN, "Expect '(' after 'for'.");

Code block 44

java
    Stmt initializer;
    if (match(SEMICOLON)) {
      initializer = null;
    } else if (match(VAR)) {
      initializer = varDeclaration();
    } else {
      initializer = expressionStatement();
    }

Code block 45

text
  }

Code block 46

text
      initializer = expressionStatement();
    }

Code block 47

java
    Expr condition = null;
    if (!check(SEMICOLON)) {
      condition = expression();
    }
    consume(SEMICOLON, "Expect ';' after loop condition.");

Code block 48

text
  }

Code block 49

text
    consume(SEMICOLON, "Expect ';' after loop condition.");

Code block 50

java
    Expr increment = null;
    if (!check(RIGHT_PAREN)) {
      increment = expression();
    }
    consume(RIGHT_PAREN, "Expect ')' after for clauses.");

Code block 51

text
  }

Code block 52

text
    consume(RIGHT_PAREN, "Expect ')' after for clauses.");

Code block 53

java
    Stmt body = statement();

    return body;

Code block 54

text
  }

Code block 55

java
    Stmt body = statement();

Code block 56

java
    if (increment != null) {
      body = new Stmt.Block(
          Arrays.asList(
              body,
              new Stmt.Expression(increment)));
    }

Code block 57

java
    return body;

Code block 58

text
    }

Code block 59

java
    if (condition == null) condition = new Expr.Literal(true);
    body = new Stmt.While(condition, body);

Code block 60

java
    return body;

Code block 61

text
    body = new Stmt.While(condition, body);

Code block 62

java
    if (initializer != null) {
      body = new Stmt.Block(Arrays.asList(initializer, body));
    }

Code block 63

java
    return body;

Code block 64

text
var a = 0;
var temp;

for (var b = 1; a < 10000; b = temp + b) {
  print a;
  temp = a;
  a = b;
}

参考资料

← 返回列表
← 上一篇 Statements and State:变量、环境与 lexical scope 下一篇 → Functions:调用、返回与 closure

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论