Scanning on Demand:clox 的按需词法扫描
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 time | scanner 状态与 token |
| A lexical grammar for Lox | 空白、注释和 literals |
| Identifiers and keywords | keyword recognition |
| Challenges | 扩展练习 |
Spinning up the interpreter
clox 的编译管线把 source 逐步转换为 bytecode:

Opening the compilation pipeline
VM 需要知道当前正在执行的 chunk;compiler 则需要从 source 获取 token。scanner 是两者之间的第一层。初始化时把 source 指针交给 scanner,再让 compiler 反复调用 scanToken()。
The scanner scans
scanner 维护 start 指向当前 token 的开头,current 指向尚未读取的位置,line 保存 source 行号:

每次 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:

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

Identifiers and keywords
identifier 以 letter 或 underscore 开头,后续可以包含 digits。读取完整 lexeme 后,需要判断它是不是保留 keyword;是则返回对应 token type,否则返回 TOKEN_IDENTIFIER。
Tries and state machines
最简单的 keyword recognition 是把 lexeme 与所有 keyword 逐一比较;更高效的方式是根据前几个字符构造 trie 或手写 state machine:

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
int main(int argc, const char* argv[]) {
initVM();
Code block 2
if (argc == 1) {
repl();
} else if (argc == 2) {
runFile(argv[1]);
} else {
fprintf(stderr, "Usage: clox [path]\n");
exit(64);
}
freeVM();
Code block 3
return 0;
}
Code block 4
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Code block 5
#include "common.h"
Code block 6
#include "vm.h"
Code block 7
static void repl() {
char line[1024];
for (;;) {
printf("> ");
if (!fgets(line, sizeof(line), stdin)) {
printf("\n");
break;
}
interpret(line);
}
}
Code block 8
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
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
FILE* file = fopen(path, "rb");
Code block 11
if (file == NULL) {
fprintf(stderr, "Could not open file \"%s\".\n", path);
exit(74);
}
Code block 12
fseek(file, 0L, SEEK_END);
Code block 13
char* buffer = (char*)malloc(fileSize + 1);
Code block 14
if (buffer == NULL) {
fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
exit(74);
}
Code block 15
size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
Code block 16
size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
Code block 17
if (bytesRead < fileSize) {
fprintf(stderr, "Could not read file \"%s\".\n", path);
exit(74);
}
Code block 18
buffer[bytesRead] = '\0';
Code block 19
void freeVM();
Code block 20
InterpretResult interpret(const char* source);
Code block 21
void push(Value value);
Code block 22
InterpretResult interpret(const char* source) {
compile(source);
return INTERPRET_OK;
Code block 23
}
Code block 24
#include "common.h"
Code block 25
#include "compiler.h"
Code block 26
#include "debug.h"
Code block 27
#ifndef clox_compiler_h
#define clox_compiler_h
void compile(const char* source);
#endif
Code block 28
#include <stdio.h>
#include "common.h"
#include "compiler.h"
#include "scanner.h"
void compile(const char* source) {
initScanner(source);
}
Code block 29
#ifndef clox_scanner_h
#define clox_scanner_h
void initScanner(const char* source);
#endif
Code block 30
#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
void initScanner(const char* source) {
scanner.start = source;
scanner.current = source;
scanner.line = 1;
}
Code block 32
initScanner(source);
Code block 33
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
}
Code block 35
print 1 + 2;
Code block 36
1 31 'print'
| 21 '1'
| 7 '+'
| 21 '2'
| 8 ';'
2 39 ''
Code block 37
void initScanner(const char* source);
Code block 38
Token scanToken();
Code block 39
#endif
Code block 40
#define clox_scanner_h
Code block 41
typedef struct {
TokenType type;
const char* start;
int length;
int line;
} Token;
Code block 42
void initScanner(const char* source);
Code block 43
#ifndef clox_scanner_h
#define clox_scanner_h
Code block 44
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
typedef struct {
Code block 46
Token scanToken() {
scanner.start = scanner.current;
if (isAtEnd()) return makeToken(TOKEN_EOF);
return errorToken("Unexpected character.");
}
Code block 47
static bool isAtEnd() {
return *scanner.current == '\0';
}
Code block 48
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
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
if (isAtEnd()) return makeToken(TOKEN_EOF);
Code block 51
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
return errorToken("Unexpected character.");
Code block 53
static char advance() {
scanner.current++;
return scanner.current[-1];
}
Code block 54
case '*': return makeToken(TOKEN_STAR);
Code block 55
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
}
Code block 57
static bool match(char expected) {
if (isAtEnd()) return false;
if (*scanner.current != expected) return false;
scanner.current++;
return true;
}
Code block 58
Token scanToken() {
Code block 59
skipWhitespace();
Code block 60
scanner.start = scanner.current;
Code block 61
static void skipWhitespace() {
for (;;) {
char c = peek();
switch (c) {
case ' ':
case '\r':
case '\t':
advance();
break;
default:
return;
}
}
}
Code block 62
static char peek() {
return *scanner.current;
}
Code block 63
break;
Code block 64
case '\n':
scanner.line++;
advance();
break;
Code block 65
default:
return;
Code block 66
break;
Code block 67
case '/':
if (peekNext() == '/') {
// A comment goes until the end of the line.
while (peek() != '\n' && !isAtEnd()) advance();
} else {
return;
}
break;
Code block 68
default:
return;
Code block 69
static char peekNext() {
if (isAtEnd()) return '\0';
return scanner.current[1];
}
Code block 70
match('=') ? TOKEN_GREATER_EQUAL : TOKEN_GREATER);
Code block 71
case '"': return string();
Code block 72
}
Code block 73
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
char c = advance();
Code block 75
if (isDigit(c)) return number();
Code block 76
switch (c) {
Code block 77
static bool isDigit(char c) {
return c >= '0' && c <= '9';
}
Code block 78
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
char c = advance();
Code block 80
if (isAlpha(c)) return identifier();
Code block 81
if (isDigit(c)) return number();
Code block 82
static bool isAlpha(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '_';
}
Code block 83
static Token identifier() {
while (isAlpha(peek()) || isDigit(peek())) advance();
return makeToken(identifierType());
}
Code block 84
static TokenType identifierType() {
return TOKEN_IDENTIFIER;
}
Code block 85
static TokenType identifierType() {
Code block 86
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
return TOKEN_IDENTIFIER;
Code block 88
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
case 'e': return checkKeyword(1, 3, "lse", TOKEN_ELSE);
Code block 90
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
case 'i': return checkKeyword(1, 1, "f", TOKEN_IF);
Code block 92
case 's': return checkKeyword(1, 4, "uper", TOKEN_SUPER);
Code block 93
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
case 'v': return checkKeyword(1, 2, "ar", TOKEN_VAR);
Code block 95
var drink = "Tea";
var steep = 4;
var cool = 2;
print "${drink} will be ready in ${steep + cool} minutes.";
Code block 96
Tea will be ready in 6 minutes.
Code block 97
"Nested ${"interpolation?! Are you ${"mad?!"}"}"
Code block 98
vector<vector<string>> nestedVectors;
参考资料
- 原文:Scanning on Demand
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)