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

Crafting Interpreters:Scanning

发布于 2026-09-16 18:41 · 最后编辑于 2026-09-17 22:06 · 版本 v2 · 字数 3,231 · 预计阅读 7 分钟 👁 21 次阅读

Crafting Interpreters:Scanning

作者:Robert Nystrom
原文章节:4 Scanning

logotype

TL;DR

本章为 jlox 实现 scanner,把 source code 的 character stream 分割成 token,为后续 parser 提供干净、带位置和 literal value 的输入。

目录

章节说明
The Interpreter Frameworkjlox 的基础框架与错误处理
Lexemes and Tokenstoken 的结构
Regular Languages and Expressionsregular expression 与 scanner
The Scanner ClassScanner 的接口和状态
Recognizing Lexemes识别 token
Longer Lexemesstring 与 number literal
Reserved Words and Identifierskeyword 与 identifier
Challenges练习
Design Note:Implicit Semicolons自动插入 semicolon

The Interpreter Framework

在实现 language 时,scanner 是 source code 进入 interpreter 的第一道门。它接收原始 character stream,逐个读取 character,并输出 parser 能够消费的 token list。

jlox 需要一个最小的 interpreter framework:读取 source、调用 scanner、处理 error,并为后面的 parser 留出接口。错误处理要记录发生位置,但不要让 scanner 的内部细节泄漏到上层。

Lexemes and Tokens

Source code 的字符序列称为 lexeme。Scanner 将 lexeme 分组为 token;token 至少包含 token type、原始 lexeme 和 source location,必要时还携带 literal value。

lexemes

Token type

Token type 是 parser 关心的分类,例如左括号、operator、identifier、string、number 或 keyword。把具体 characters 转成 token type 后,parser 就不必重复判断字符组合。

Literal value

Literal token 的 lexeme 是 source 中的文字表示,literal value 是 interpreter 执行时真正使用的 value。例如 number lexeme 可以转换为 Java 的 Double,string lexeme 则去除引号后保存内容。

Location information

Token 记录 line number,便于报告 syntax error。Scanner 只需维护当前 line,在读取 newline 时递增;token 创建时记录起始行号。

Regular Languages and Expressions

Lexical grammar 通常属于 regular language,适合用 finite automaton 或 regular expression 描述。Scanner 不需要理解 token 之间的嵌套关系;括号匹配、expression precedence 等工作留给 parser。

The Scanner Class

Scanner 持有 source string、当前起点 start、当前读取位置 current、line,以及最终的 token list。scanTokens 循环读取 token,直到 source 结束,再追加 EOF token。

Recognizing Lexemes

单字符 token 可以直接通过 switch 识别。双字符 operator 需要 lookahead:例如 ! 与 !=、= 与 ==、< 与 <=、> 与 >=。

lexigator

Lexical errors

如果 character 不属于任何合法 token,scanner 报告 lexical error 并继续扫描后面的 input。

Operators

Operator 的识别需要先判断当前 character,再根据下一个 character 决定是单字符还是双字符 token。

Longer Lexemes

String literals

String 从双引号开始,scanner 持续读取直到另一个双引号。String 可以跨越 newline;到 source 结尾仍未遇到 closing quote 时,报告 unterminated string error。

Number literals

Number 读取连续 digit;如果遇到 dot 且 dot 后仍有 digit,就继续读取 fractional part,最后转换为 numeric literal value。

Reserved Words and Identifiers

Identifier 以 letter 或 underscore 开始,后面可以跟 letter、digit 或 underscore。Scanner 先读取完整文字,再查询 reserved-word map;匹配到就生成 keyword token,否则生成 IDENTIFIER token。

Challenges

练习包括 block comment、字符串转义、数字格式、新 operator 和 error-recovery 策略。应在代码副本上完成。

Design Note:Implicit Semicolons

有些 language 允许省略 statement 末尾的 semicolon,在 newline 或其他位置自动插入。这样可以让 source 更简洁,但会增加 scanner、parser 和错误信息的复杂度。

Lox 选择显式 semicolon,因为规则简单、歧义少,也适合手写 scanner。

原文代码

下面保留本章原文中的全部 Java code block;代码内容不翻译,仅翻译 surrounding prose。 +### Code block 1

java
package
 
com.craftinginterpreters.lox
;


import
 
java.io.BufferedReader
;

import
 
java.io.IOException
;

import
 
java.io.InputStreamReader
;

import
 
java.nio.charset.Charset
;

import
 
java.nio.file.Files
;

import
 
java.nio.file.Paths
;

import
 
java.util.List
;


public
 
class
 
Lox
 {
  
public
 
static
 
void
 
main
(
String
[] 
args
) 
throws
 
IOException
 {
    
if
 (
args
.
length
 > 
1
) {
      
System
.
out
.
println
(
"Usage: jlox [script]"
);
      
System
.
exit
(
64
);
 

    } 
else
 
if
 (
args
.
length
 == 
1
) {
      
runFile
(
args
[
0
]);
    } 
else
 {
      
runPrompt
();
    }
  }
}

Code block 2

java
private
 
static
 
void
 
runFile
(
String
 
path
) 
throws
 
IOException
 {
    
byte
[] 
bytes
 = 
Files
.
readAllBytes
(
Paths
.
get
(
path
));
    
run
(
new
 
String
(
bytes
, 
Charset
.
defaultCharset
()));
  }

Code block 3

java
(
print
 (
eval
 (
read
)))

Code block 4

java
private
 
static
 
void
 
runPrompt
() 
throws
 
IOException
 {
    
InputStreamReader
 
input
 = 
new
 
InputStreamReader
(
System
.
in
);
    
BufferedReader
 
reader
 = 
new
 
BufferedReader
(
input
);

    
for
 (;;) {
 

      
System
.
out
.
print
(
"> "
);
      
String
 
line
 = 
reader
.
readLine
();
      
if
 (
line
 == 
null
) 
break
;
      
run
(
line
);
    }
  }

Code block 5

java
private
 
static
 
void
 
run
(
String
 
source
) {
    
Scanner
 
scanner
 = 
new
 
Scanner
(
source
);
    
List
<
Token
> 
tokens
 = 
scanner
.
scanTokens
();

    
// For now, just print the tokens.

    
for
 (
Token
 
token
 : 
tokens
) {
      
System
.
out
.
println
(
token
);
    }
  }

Code block 6

java
static
 
void
 
error
(
int
 
line
, 
String
 
message
) {
    
report
(
line
, 
""
, 
message
);
  }

  
private
 
static
 
void
 
report
(
int
 
line
, 
String
 
where
,
                             
String
 
message
) {
    
System
.
err
.
println
(
        
"[line "
 + 
line
 + 
"] Error"
 + 
where
 + 
": "
 + 
message
);
    
hadError
 = 
true
;
  }

Code block 7

java
Error: Unexpected "," somewhere in your code. Good luck finding it!

Code block 8

java
Error: Unexpected "," in argument list.

    15 | function(first, second,);
                               ^-- Here.

Code block 9

java
public class Lox {

Code block 10

java
static
 
boolean
 
hadError
 = 
false
;

Code block 11

java
run(new String(bytes, Charset.defaultCharset()));

Code block 12

java
// Indicate an error in the exit code.

    
if
 (
hadError
) 
System
.
exit
(
65
);

Code block 13

java
}

Code block 14

java
run(line);

Code block 15

java
hadError
 = 
false
;

Code block 16

java
}

Code block 17

java
var
 
language
 = 
"lox"
;

Code block 18

java
package
 
com.craftinginterpreters.lox
;


enum
 
TokenType
 {
  
// Single-character tokens.

  
LEFT_PAREN
, 
RIGHT_PAREN
, 
LEFT_BRACE
, 
RIGHT_BRACE
,
  
COMMA
, 
DOT
, 
MINUS
, 
PLUS
, 
SEMICOLON
, 
SLASH
, 
STAR
,

  
// One or two character tokens.

  
BANG
, 
BANG_EQUAL
,
  
EQUAL
, 
EQUAL_EQUAL
,
  
GREATER
, 
GREATER_EQUAL
,
  
LESS
, 
LESS_EQUAL
,

  
// Literals.

  
IDENTIFIER
, 
STRING
, 
NUMBER
,

  
// Keywords.

  
AND
, 
CLASS
, 
ELSE
, 
FALSE
, 
FUN
, 
FOR
, 
IF
, 
NIL
, 
OR
,
  
PRINT
, 
RETURN
, 
SUPER
, 
THIS
, 
TRUE
, 
VAR
, 
WHILE
,

  
EOF

}

Code block 19

java
package
 
com.craftinginterpreters.lox
;


class
 
Token
 {
  
final
 
TokenType
 
type
;
  
final
 
String
 
lexeme
;
  
final
 
Object
 
literal
;
  
final
 
int
 
line
;
 


  
Token
(
TokenType
 
type
, 
String
 
lexeme
, 
Object
 
literal
, 
int
 
line
) {
    
this
.
type
 = 
type
;
    
this
.
lexeme
 = 
lexeme
;
    
this
.
literal
 = 
literal
;
    
this
.
line
 = 
line
;
  }

  
public
 
String
 
toString
() {
    
return
 
type
 + 
" "
 + 
lexeme
 + 
" "
 + 
literal
;
  }
}

Code block 20

java
[a-zA-Z_][a-zA-Z_0-9]*

Code block 21

java
package
 
com.craftinginterpreters.lox
;


import
 
java.util.ArrayList
;

import
 
java.util.HashMap
;

import
 
java.util.List
;

import
 
java.util.Map
;


import static
 
com.craftinginterpreters.lox.TokenType.*
;
 



class
 
Scanner
 {
  
private
 
final
 
String
 
source
;
  
private
 
final
 
List
<
Token
> 
tokens
 = 
new
 
ArrayList
<>();

  
Scanner
(
String
 
source
) {
    
this
.
source
 = 
source
;
  }
}

Code block 22

java
List
<
Token
> 
scanTokens
() {
    
while
 (!
isAtEnd
()) {
      
// We are at the beginning of the next lexeme.

      
start
 = 
current
;
      
scanToken
();
    }

    
tokens
.
add
(
new
 
Token
(
EOF
, 
""
, 
null
, 
line
));
    
return
 
tokens
;
  }

Code block 23

java
private final List<Token> tokens = new ArrayList<>();

Code block 24

java
private
 
int
 
start
 = 
0
;
  
private
 
int
 
current
 = 
0
;
  
private
 
int
 
line
 = 
1
;

Code block 25

java
Scanner(String source) {

Code block 26

java
private
 
boolean
 
isAtEnd
() {
    
return
 
current
 >= 
source
.
length
();
  }

Code block 27

java
private
 
void
 
scanToken
() {
    
char
 
c
 = 
advance
();
    
switch
 (
c
) {
      
case
 
'('
: 
addToken
(
LEFT_PAREN
); 
break
;
      
case
 
')'
: 
addToken
(
RIGHT_PAREN
); 
break
;
      
case
 
'{'
: 
addToken
(
LEFT_BRACE
); 
break
;
      
case
 
'}'
: 
addToken
(
RIGHT_BRACE
); 
break
;
      
case
 
','
: 
addToken
(
COMMA
); 
break
;
      
case
 
'.'
: 
addToken
(
DOT
); 
break
;
      
case
 
'-'
: 
addToken
(
MINUS
); 
break
;
      
case
 
'+'
: 
addToken
(
PLUS
); 
break
;
      
case
 
';'
: 
addToken
(
SEMICOLON
); 
break
;
      
case
 
'*'
: 
addToken
(
STAR
); 
break
;
 

    }
  }

Code block 28

java
private
 
char
 
advance
() {
    
return
 
source
.
charAt
(
current
++);
  }

  
private
 
void
 
addToken
(
TokenType
 
type
) {
    
addToken
(
type
, 
null
);
  }

  
private
 
void
 
addToken
(
TokenType
 
type
, 
Object
 
literal
) {
    
String
 
text
 = 
source
.
substring
(
start
, 
current
);
    
tokens
.
add
(
new
 
Token
(
type
, 
text
, 
literal
, 
line
));
  }

Code block 29

java
case '*': addToken(STAR); break;

Code block 30

java
default
:
        
Lox
.
error
(
line
, 
"Unexpected character."
);
        
break
;

Code block 31

java
}

Code block 32

java
case '*': addToken(STAR); break;

Code block 33

java
case
 
'!'
:
        
addToken
(
match
(
'='
) ? 
BANG_EQUAL
 : 
BANG
);
        
break
;
      
case
 
'='
:
        
addToken
(
match
(
'='
) ? 
EQUAL_EQUAL
 : 
EQUAL
);
        
break
;
      
case
 
'<'
:
        
addToken
(
match
(
'='
) ? 
LESS_EQUAL
 : 
LESS
);
        
break
;
      
case
 
'>'
:
        
addToken
(
match
(
'='
) ? 
GREATER_EQUAL
 : 
GREATER
);
        
break
;

Code block 34

java
default:

Code block 35

java
private
 
boolean
 
match
(
char
 
expected
) {
    
if
 (
isAtEnd
()) 
return
 
false
;
    
if
 (
source
.
charAt
(
current
) != 
expected
) 
return
 
false
;

    
current
++;
    
return
 
true
;
  }

Code block 36

java
break;

Code block 37

java
case
 
'/'
:
        
if
 (
match
(
'/'
)) {
          
// A comment goes until the end of the line.

          
while
 (
peek
() != 
'\n'
 && !
isAtEnd
()) 
advance
();
        } 
else
 {
          
addToken
(
SLASH
);
        }
        
break
;

Code block 38

java
default:

Code block 39

java
private
 
char
 
peek
() {
    
if
 (
isAtEnd
()) 
return
 
'\0'
;
    
return
 
source
.
charAt
(
current
);
  }

Code block 40

java
break;

Code block 41

java
case
 
' '
:
      
case
 
'\r'
:
      
case
 
'\t'
:
        
// Ignore whitespace.

        
break
;

      
case
 
'\n'
:
        
line
++;
        
break
;

Code block 42

java
default:
        Lox.error(line, "Unexpected character.");

Code block 43

java
// this is a comment

(( )){} 
// grouping stuff

!*+-/=<> <= == 
// operators

Code block 44

java
break;

Code block 45

java
case
 
'"'
: 
string
(); 
break
;

Code block 46

java
default:

Code block 47

java
private
 
void
 
string
() {
    
while
 (
peek
() != 
'"'
 && !
isAtEnd
()) {
      
if
 (
peek
() == 
'\n'
) 
line
++;
      
advance
();
    }

    
if
 (
isAtEnd
()) {
      
Lox
.
error
(
line
, 
"Unterminated string."
);
      
return
;
    }

    
// The closing ".

    
advance
();

    
// Trim the surrounding quotes.

    
String
 
value
 = 
source
.
substring
(
start
 + 
1
, 
current
 - 
1
);
    
addToken
(
STRING
, 
value
);
  }

Code block 48

java
print
 -
123
.
abs
();

Code block 49

java
var
 
n
 = 
123
;

print
 -
n
.
abs
();

Code block 50

java
1234


12.34

Code block 51

java
.
1234


1234
.

Code block 52

java
default:

Code block 53

java
if
 (
isDigit
(
c
)) {
          
number
();
        } 
else
 {
          
Lox
.
error
(
line
, 
"Unexpected character."
);
        }

Code block 54

java
break;

Code block 55

java
private
 
boolean
 
isDigit
(
char
 
c
) {
    
return
 
c
 >= 
'0'
 && 
c
 <= 
'9'
;
  }

Code block 56

java
private
 
void
 
number
() {
    
while
 (
isDigit
(
peek
())) 
advance
();

    
// Look for a fractional part.

    
if
 (
peek
() == 
'.'
 && 
isDigit
(
peekNext
())) {
      
// Consume the "."

      
advance
();

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

    
addToken
(
NUMBER
,
        
Double
.
parseDouble
(
source
.
substring
(
start
, 
current
)));
  }

Code block 57

java
private
 
char
 
peekNext
() {
    
if
 (
current
 + 
1
 >= 
source
.
length
()) 
return
 
'\0'
;
    
return
 
source
.
charAt
(
current
 + 
1
);
  }

Code block 58

java
case
 
'o'
:
  
if
 (
match
(
'r'
)) {
    
addToken
(
OR
);
  }
  
break
;

Code block 59

java
---
a
;

Code block 60

java
- --
a
;

Code block 61

java
-- -
a
;

Code block 62

java
default:
        if (isDigit(c)) {
          number();

Code block 63

java
} 
else
 
if
 (
isAlpha
(
c
)) {
          
identifier
();

Code block 64

java
} else {
          Lox.error(line, "Unexpected character.");
        }

Code block 65

java
private
 
void
 
identifier
() {
    
while
 (
isAlphaNumeric
(
peek
())) 
advance
();

    
addToken
(
IDENTIFIER
);
  }

Code block 66

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

  
private
 
boolean
 
isAlphaNumeric
(
char
 
c
) {
    
return
 
isAlpha
(
c
) || 
isDigit
(
c
);
  }

Code block 67

java
private
 
static
 
final
 
Map
<
String
, 
TokenType
> 
keywords
;

  
static
 {
    
keywords
 = 
new
 
HashMap
<>();
    
keywords
.
put
(
"and"
,    
AND
);
    
keywords
.
put
(
"class"
,  
CLASS
);
    
keywords
.
put
(
"else"
,   
ELSE
);
    
keywords
.
put
(
"false"
,  
FALSE
);
    
keywords
.
put
(
"for"
,    
FOR
);
    
keywords
.
put
(
"fun"
,    
FUN
);
    
keywords
.
put
(
"if"
,     
IF
);
    
keywords
.
put
(
"nil"
,    
NIL
);
    
keywords
.
put
(
"or"
,     
OR
);
    
keywords
.
put
(
"print"
,  
PRINT
);
    
keywords
.
put
(
"return"
, 
RETURN
);
    
keywords
.
put
(
"super"
,  
SUPER
);
    
keywords
.
put
(
"this"
,   
THIS
);
    
keywords
.
put
(
"true"
,   
TRUE
);
    
keywords
.
put
(
"var"
,    
VAR
);
    
keywords
.
put
(
"while"
,  
WHILE
);
  }

Code block 68

java
while (isAlphaNumeric(peek())) advance();

Code block 69

java
String
 
text
 = 
source
.
substring
(
start
, 
current
);
    
TokenType
 
type
 = 
keywords
.
get
(
text
);
    
if
 (
type
 == 
null
) 
type
 = 
IDENTIFIER
;
    
addToken
(
type
);

Code block 70

java
}

Code block 71

java
if
 (
condition
) 
return


"value"

Code block 72

java
func

(
parenthesized
)

Code block 73

java
first

-
second

Code block 74

java
a
 = 
1
 
b
 = 
2

Code block 75

java
console
.
log
(
function
() {
  
statement
();
});
~~~+

## 参考资料

- [原文:Scanning](https://craftinginterpreters.com/scanning.html)
- [Crafting Interpreters 系列索引](00%20系列索引.md)

> 版权说明:官方页面标注 © 2015–2021。原作版权归 Robert Nystrom 及相关权利人所有。本笔记为个人学习用途的中文翻译。
← 返回列表
← 上一篇 A Tree-Walk Interpreter:用 Java 实现 jlox 下一篇 → Crafting Interpreters:Representing Code

评论 (0)

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