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

Scanning on Demand:clox 的按需词法扫描

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

Crafting Interpreters:Scanning on Demand

本章把 clox 的 scanner 接入 compilation pipeline,并逐个 token 扫描 source,让 compiler 可以按需取得词法单元。

TL;DR

  • clox 的 pipeline 是 source → scanner → tokens → compiler → bytecode chunk → VM。
  • scanner 不再一次性构造 token list,而是维护 start/current/line,在 compiler 请求时返回下一个 token。
  • lexical grammar 把 whitespace、comments、literals、identifiers 和 keywords 分成可预测的扫描规则。
  • C 的 pointer arithmetic 与 switch 让 scanner 可以高效地在 source buffer 上前进。
  • scanner 遇到非法字符时应返回 error token 并继续扫描,保证 compiler 能获得后续错误信息。

目录

章节内容
Spinning up the interpreter启动 compilation pipeline
A token at a timescanner 状态与 token
A lexical grammar for Lox空白、注释和 literals
Identifiers and keywordskeyword recognition
Challenges扩展练习

Spinning up the interpreter

clox 的编译管线把 source 逐步转换为 bytecode:

pipeline

Opening the compilation pipeline

VM 需要知道当前正在执行的 chunk;compiler 则需要从 source 获取 token。scanner 是两者之间的第一层。初始化时把 source 指针交给 scanner,再让 compiler 反复调用 scanToken()。

The scanner scans

scanner 维护 start 指向当前 token 的开头,current 指向尚未读取的位置,line 保存 source 行号:

fields

每次 scanToken() 先跳过前一个 token 的尾部,再设置 start,读取首字符并分派到对应扫描函数。token 不需要复制 lexeme;它只保存指向 source 的起点、长度、类型和行号。

A token at a time

scanner 逐 token 工作,而不是预先生成完整数组。这样 compiler 可以按需读取,也能在看到足够的 token 后决定下一步 grammar 分支。

token 的类型包括单字符 punctuation、双字符 operators、identifier、string、number、EOF 和 TOKEN_ERROR。error token 的 lexeme 保存诊断信息,compiler 可以据此报告非法字符或未结束 string。

Scanning tokens

scanner 的基本操作是 advance、peek、peekNext、match。advance 返回 current 字符并向前移动;peek 只查看当前字符;match 在字符匹配时消费它。这些小操作把 pointer movement 集中起来,减少 off-by-one bug。

A lexical grammar for Lox

Lox lexical grammar 的规则优先级从特殊情况到通用情况排列。先处理 whitespace 和 comments,再识别 punctuation、literals、identifier;未知字符最后成为 error token。

Whitespace

空格、制表符和回车直接跳过;换行需要递增 line。源代码中的 whitespace 通常不进入 bytecode,但行号必须保留用于 diagnostics。

Comments

Lox 使用 // 到行尾的 comment。scanner 看到两个 slash 后不断读取,直到换行或 EOF,然后回到外层循环继续扫描下一个 token。

Literal tokens

number 先读取连续 digits;若遇到 dot 且 dot 后仍是 digit,就继续读取 fractional part。否则 dot 属于下一个 token:

numbers

string 从 opening quote 扫描到 closing quote,允许内部换行并同步 line。到 EOF 仍未找到 closing quote 时返回 unterminated-string error。

axolotl

Identifiers and keywords

identifier 以 letter 或 underscore 开头,后续可以包含 digits。读取完整 lexeme 后,需要判断它是不是保留 keyword;是则返回对应 token type,否则返回 TOKEN_IDENTIFIER。

Tries and state machines

最简单的 keyword recognition 是把 lexeme 与所有 keyword 逐一比较;更高效的方式是根据前几个字符构造 trie 或手写 state machine:

keywords

clox 采用按 lexeme 长度和关键字符分支的方式,在不分配临时 string 的情况下识别 keyword。关键是保持 recognition 逻辑与 scanner 的字符边界一致,避免把 forx 错认成 for。

Challenges

1. Nested comments

设计 nested comment 语法,并处理未闭合 comment、行号与注释中的 delimiters。

2. Unicode identifiers

允许 Unicode identifier,说明 UTF-8 的 code point 与 C byte pointer 的关系,以及 identifier 长度的计算方式。

3. Scanner diagnostics

让 error token 携带 source range,并一次报告多个相邻词法错误。

原文代码片段

本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。

参考资料

Code block 1

c
int main(int argc, const char* argv[]) {
  initVM();

Code block 2

c
  if (argc == 1) {
    repl();
  } else if (argc == 2) {
    runFile(argv[1]);
  } else {
    fprintf(stderr, "Usage: clox [path]\n");
    exit(64);
  }

  freeVM();

Code block 3

c
  return 0;
}

Code block 4

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Code block 5

c
#include "common.h"

Code block 6

c
#include "vm.h"

Code block 7

c
static void repl() {
  char line[1024];
  for (;;) {
    printf("> ");

    if (!fgets(line, sizeof(line), stdin)) {
      printf("\n");
      break;
    }

    interpret(line);
  }
}

Code block 8

c
static void runFile(const char* path) {
  char* source = readFile(path);
  InterpretResult result = interpret(source);
  free(source); 

  if (result == INTERPRET_COMPILE_ERROR) exit(65);
  if (result == INTERPRET_RUNTIME_ERROR) exit(70);
}

Code block 9

c
static char* readFile(const char* path) {
  FILE* file = fopen(path, "rb");

  fseek(file, 0L, SEEK_END);
  size_t fileSize = ftell(file);
  rewind(file);

  char* buffer = (char*)malloc(fileSize + 1);
  size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
  buffer[bytesRead] = '\0';

  fclose(file);
  return buffer;
}

Code block 10

text
  FILE* file = fopen(path, "rb");

Code block 11

c
  if (file == NULL) {
    fprintf(stderr, "Could not open file \"%s\".\n", path);
    exit(74);
  }

Code block 12

text
  fseek(file, 0L, SEEK_END);

Code block 13

text
  char* buffer = (char*)malloc(fileSize + 1);

Code block 14

c
  if (buffer == NULL) {
    fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
    exit(74);
  }

Code block 15

text
  size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);

Code block 16

text
  size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);

Code block 17

c
  if (bytesRead < fileSize) {
    fprintf(stderr, "Could not read file \"%s\".\n", path);
    exit(74);
  }

Code block 18

text
  buffer[bytesRead] = '\0';

Code block 19

c
void freeVM();

Code block 20

text
InterpretResult interpret(const char* source);

Code block 21

c
void push(Value value);

Code block 22

c
InterpretResult interpret(const char* source) {
  compile(source);
  return INTERPRET_OK;

Code block 23

text
}

Code block 24

c
#include "common.h"

Code block 25

c
#include "compiler.h"

Code block 26

c
#include "debug.h"

Code block 27

c
#ifndef clox_compiler_h
#define clox_compiler_h

void compile(const char* source);

#endif

Code block 28

c
#include <stdio.h>

#include "common.h"
#include "compiler.h"
#include "scanner.h"

void compile(const char* source) {
  initScanner(source);
}

Code block 29

c
#ifndef clox_scanner_h
#define clox_scanner_h

void initScanner(const char* source);

#endif

Code block 30

c
#include <stdio.h>
#include <string.h>

#include "common.h"
#include "scanner.h"

typedef struct {
  const char* start;
  const char* current;
  int line;
} Scanner;

Scanner scanner;

Code block 31

c
void initScanner(const char* source) {
  scanner.start = source;
  scanner.current = source;
  scanner.line = 1;
}

Code block 32

c
  initScanner(source);

Code block 33

c
  int line = -1;
  for (;;) {
    Token token = scanToken();
    if (token.line != line) {
      printf("%4d ", token.line);
      line = token.line;
    } else {
      printf("   | ");
    }
    printf("%2d '%.*s'\n", token.type, token.length, token.start); 

    if (token.type == TOKEN_EOF) break;
  }

Code block 34

text
}

Code block 35

c
print 1 + 2;

Code block 36

text
   1 31 'print'
   | 21 '1'
   |  7 '+'
   | 21 '2'
   |  8 ';'
   2 39 ''

Code block 37

c
void initScanner(const char* source);

Code block 38

c
Token scanToken();

Code block 39

text
#endif

Code block 40

c
#define clox_scanner_h

Code block 41

c
typedef struct {
  TokenType type;
  const char* start;
  int length;
  int line;
} Token;

Code block 42

c
void initScanner(const char* source);

Code block 43

c
#ifndef clox_scanner_h
#define clox_scanner_h

Code block 44

c
typedef enum {
  // Single-character tokens.
  TOKEN_LEFT_PAREN, TOKEN_RIGHT_PAREN,
  TOKEN_LEFT_BRACE, TOKEN_RIGHT_BRACE,
  TOKEN_COMMA, TOKEN_DOT, TOKEN_MINUS, TOKEN_PLUS,
  TOKEN_SEMICOLON, TOKEN_SLASH, TOKEN_STAR,
  // One or two character tokens.
  TOKEN_BANG, TOKEN_BANG_EQUAL,
  TOKEN_EQUAL, TOKEN_EQUAL_EQUAL,
  TOKEN_GREATER, TOKEN_GREATER_EQUAL,
  TOKEN_LESS, TOKEN_LESS_EQUAL,
  // Literals.
  TOKEN_IDENTIFIER, TOKEN_STRING, TOKEN_NUMBER,
  // Keywords.
  TOKEN_AND, TOKEN_CLASS, TOKEN_ELSE, TOKEN_FALSE,
  TOKEN_FOR, TOKEN_FUN, TOKEN_IF, TOKEN_NIL, TOKEN_OR,
  TOKEN_PRINT, TOKEN_RETURN, TOKEN_SUPER, TOKEN_THIS,
  TOKEN_TRUE, TOKEN_VAR, TOKEN_WHILE,

  TOKEN_ERROR, TOKEN_EOF
} TokenType;

Code block 45

c
typedef struct {

Code block 46

c
Token scanToken() {
  scanner.start = scanner.current;

  if (isAtEnd()) return makeToken(TOKEN_EOF);

  return errorToken("Unexpected character.");
}

Code block 47

c
static bool isAtEnd() {
  return *scanner.current == '\0';
}

Code block 48

c
static Token makeToken(TokenType type) {
  Token token;
  token.type = type;
  token.start = scanner.start;
  token.length = (int)(scanner.current - scanner.start);
  token.line = scanner.line;
  return token;
}

Code block 49

c
static Token errorToken(const char* message) {
  Token token;
  token.type = TOKEN_ERROR;
  token.start = message;
  token.length = (int)strlen(message);
  token.line = scanner.line;
  return token;
}

Code block 50

c
  if (isAtEnd()) return makeToken(TOKEN_EOF);

Code block 51

c
  char c = advance();

  switch (c) {
    case '(': return makeToken(TOKEN_LEFT_PAREN);
    case ')': return makeToken(TOKEN_RIGHT_PAREN);
    case '{': return makeToken(TOKEN_LEFT_BRACE);
    case '}': return makeToken(TOKEN_RIGHT_BRACE);
    case ';': return makeToken(TOKEN_SEMICOLON);
    case ',': return makeToken(TOKEN_COMMA);
    case '.': return makeToken(TOKEN_DOT);
    case '-': return makeToken(TOKEN_MINUS);
    case '+': return makeToken(TOKEN_PLUS);
    case '/': return makeToken(TOKEN_SLASH);
    case '*': return makeToken(TOKEN_STAR);
  }

Code block 52

c
  return errorToken("Unexpected character.");

Code block 53

c
static char advance() {
  scanner.current++;
  return scanner.current[-1];
}

Code block 54

c
    case '*': return makeToken(TOKEN_STAR);

Code block 55

c
    case '!':
      return makeToken(
          match('=') ? TOKEN_BANG_EQUAL : TOKEN_BANG);
    case '=':
      return makeToken(
          match('=') ? TOKEN_EQUAL_EQUAL : TOKEN_EQUAL);
    case '<':
      return makeToken(
          match('=') ? TOKEN_LESS_EQUAL : TOKEN_LESS);
    case '>':
      return makeToken(
          match('=') ? TOKEN_GREATER_EQUAL : TOKEN_GREATER);

Code block 56

text
  }

Code block 57

c
static bool match(char expected) {
  if (isAtEnd()) return false;
  if (*scanner.current != expected) return false;
  scanner.current++;
  return true;
}

Code block 58

c
Token scanToken() {

Code block 59

text
  skipWhitespace();

Code block 60

text
  scanner.start = scanner.current;

Code block 61

c
static void skipWhitespace() {
  for (;;) {
    char c = peek();
    switch (c) {
      case ' ':
      case '\r':
      case '\t':
        advance();
        break;
      default:
        return;
    }
  }
}

Code block 62

c
static char peek() {
  return *scanner.current;
}

Code block 63

text
        break;

Code block 64

text
      case '\n':
        scanner.line++;
        advance();
        break;

Code block 65

text
      default:
        return;

Code block 66

text
        break;

Code block 67

c
      case '/':
        if (peekNext() == '/') {
          // A comment goes until the end of the line.
          while (peek() != '\n' && !isAtEnd()) advance();
        } else {
          return;
        }
        break;

Code block 68

text
      default:
        return;

Code block 69

c
static char peekNext() {
  if (isAtEnd()) return '\0';
  return scanner.current[1];
}

Code block 70

c
          match('=') ? TOKEN_GREATER_EQUAL : TOKEN_GREATER);

Code block 71

c
    case '"': return string();

Code block 72

text
  }

Code block 73

c
static Token string() {
  while (peek() != '"' && !isAtEnd()) {
    if (peek() == '\n') scanner.line++;
    advance();
  }

  if (isAtEnd()) return errorToken("Unterminated string.");

  // The closing quote.
  advance();
  return makeToken(TOKEN_STRING);
}

Code block 74

text
  char c = advance();

Code block 75

c
  if (isDigit(c)) return number();

Code block 76

text
  switch (c) {

Code block 77

c
static bool isDigit(char c) {
  return c >= '0' && c <= '9';
}

Code block 78

c
static Token number() {
  while (isDigit(peek())) advance();

  // Look for a fractional part.
  if (peek() == '.' && isDigit(peekNext())) {
    // Consume the ".".
    advance();

    while (isDigit(peek())) advance();
  }

  return makeToken(TOKEN_NUMBER);
}

Code block 79

text
  char c = advance();

Code block 80

c
  if (isAlpha(c)) return identifier();

Code block 81

c
  if (isDigit(c)) return number();

Code block 82

c
static bool isAlpha(char c) {
  return (c >= 'a' && c <= 'z') ||
         (c >= 'A' && c <= 'Z') ||
          c == '_';
}

Code block 83

c
static Token identifier() {
  while (isAlpha(peek()) || isDigit(peek())) advance();
  return makeToken(identifierType());
}

Code block 84

c
static TokenType identifierType() {
  return TOKEN_IDENTIFIER;
}

Code block 85

c
static TokenType identifierType() {

Code block 86

c
  switch (scanner.start[0]) {
    case 'a': return checkKeyword(1, 2, "nd", TOKEN_AND);
    case 'c': return checkKeyword(1, 4, "lass", TOKEN_CLASS);
    case 'e': return checkKeyword(1, 3, "lse", TOKEN_ELSE);
    case 'i': return checkKeyword(1, 1, "f", TOKEN_IF);
    case 'n': return checkKeyword(1, 2, "il", TOKEN_NIL);
    case 'o': return checkKeyword(1, 1, "r", TOKEN_OR);
    case 'p': return checkKeyword(1, 4, "rint", TOKEN_PRINT);
    case 'r': return checkKeyword(1, 5, "eturn", TOKEN_RETURN);
    case 's': return checkKeyword(1, 4, "uper", TOKEN_SUPER);
    case 'v': return checkKeyword(1, 2, "ar", TOKEN_VAR);
    case 'w': return checkKeyword(1, 4, "hile", TOKEN_WHILE);
  }

Code block 87

c
  return TOKEN_IDENTIFIER;

Code block 88

c
static TokenType checkKeyword(int start, int length,
    const char* rest, TokenType type) {
  if (scanner.current - scanner.start == start + length &&
      memcmp(scanner.start + start, rest, length) == 0) {
    return type;
  }

  return TOKEN_IDENTIFIER;
}

Code block 89

c
    case 'e': return checkKeyword(1, 3, "lse", TOKEN_ELSE);

Code block 90

c
    case 'f':
      if (scanner.current - scanner.start > 1) {
        switch (scanner.start[1]) {
          case 'a': return checkKeyword(2, 3, "lse", TOKEN_FALSE);
          case 'o': return checkKeyword(2, 1, "r", TOKEN_FOR);
          case 'u': return checkKeyword(2, 1, "n", TOKEN_FUN);
        }
      }
      break;

Code block 91

c
    case 'i': return checkKeyword(1, 1, "f", TOKEN_IF);

Code block 92

c
    case 's': return checkKeyword(1, 4, "uper", TOKEN_SUPER);

Code block 93

c
    case 't':
      if (scanner.current - scanner.start > 1) {
        switch (scanner.start[1]) {
          case 'h': return checkKeyword(2, 2, "is", TOKEN_THIS);
          case 'r': return checkKeyword(2, 2, "ue", TOKEN_TRUE);
        }
      }
      break;

Code block 94

c
    case 'v': return checkKeyword(1, 2, "ar", TOKEN_VAR);

Code block 95

c
var drink = "Tea";
var steep = 4;
var cool = 2;
print "${drink} will be ready in ${steep + cool} minutes.";

Code block 96

text
Tea will be ready in 6 minutes.

Code block 97

text
"Nested ${"interpolation?! Are you ${"mad?!"}"}"

Code block 98

text
vector<vector<string>> nestedVectors;

参考资料

← 返回列表
← 上一篇 A Virtual Machine:stack、指令执行与算术 下一篇 → Compiling Expressions:Pratt parser 与 bytecode 生成

评论 (0)

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