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

TL;DR
本章为 jlox 实现 scanner,把 source code 的 character stream 分割成 token,为后续 parser 提供干净、带位置和 literal value 的输入。
目录
| 章节 | 说明 |
|---|---|
| The Interpreter Framework | jlox 的基础框架与错误处理 |
| Lexemes and Tokens | token 的结构 |
| Regular Languages and Expressions | regular expression 与 scanner |
| The Scanner Class | Scanner 的接口和状态 |
| Recognizing Lexemes | 识别 token |
| Longer Lexemes | string 与 number literal |
| Reserved Words and Identifiers | keyword 与 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。

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:例如 ! 与 !=、= 与 ==、< 与 <=、> 与 >=。

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
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
private
static
void
runFile
(
String
path
)
throws
IOException
{
byte
[]
bytes
=
Files
.
readAllBytes
(
Paths
.
get
(
path
));
run
(
new
String
(
bytes
,
Charset
.
defaultCharset
()));
}
Code block 3
(
print
(
eval
(
read
)))
Code block 4
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
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
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
Error: Unexpected "," somewhere in your code. Good luck finding it!
Code block 8
Error: Unexpected "," in argument list.
15 | function(first, second,);
^-- Here.
Code block 9
public class Lox {
Code block 10
static
boolean
hadError
=
false
;
Code block 11
run(new String(bytes, Charset.defaultCharset()));
Code block 12
// Indicate an error in the exit code.
if
(
hadError
)
System
.
exit
(
65
);
Code block 13
}
Code block 14
run(line);
Code block 15
hadError
=
false
;
Code block 16
}
Code block 17
var
language
=
"lox"
;
Code block 18
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
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
[a-zA-Z_][a-zA-Z_0-9]*
Code block 21
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
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
private final List<Token> tokens = new ArrayList<>();
Code block 24
private
int
start
=
0
;
private
int
current
=
0
;
private
int
line
=
1
;
Code block 25
Scanner(String source) {
Code block 26
private
boolean
isAtEnd
() {
return
current
>=
source
.
length
();
}
Code block 27
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
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
case '*': addToken(STAR); break;
Code block 30
default
:
Lox
.
error
(
line
,
"Unexpected character."
);
break
;
Code block 31
}
Code block 32
case '*': addToken(STAR); break;
Code block 33
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
default:
Code block 35
private
boolean
match
(
char
expected
) {
if
(
isAtEnd
())
return
false
;
if
(
source
.
charAt
(
current
) !=
expected
)
return
false
;
current
++;
return
true
;
}
Code block 36
break;
Code block 37
case
'/'
:
if
(
match
(
'/'
)) {
// A comment goes until the end of the line.
while
(
peek
() !=
'\n'
&& !
isAtEnd
())
advance
();
}
else
{
addToken
(
SLASH
);
}
break
;
Code block 38
default:
Code block 39
private
char
peek
() {
if
(
isAtEnd
())
return
'\0'
;
return
source
.
charAt
(
current
);
}
Code block 40
break;
Code block 41
case
' '
:
case
'\r'
:
case
'\t'
:
// Ignore whitespace.
break
;
case
'\n'
:
line
++;
break
;
Code block 42
default:
Lox.error(line, "Unexpected character.");
Code block 43
// this is a comment
(( )){}
// grouping stuff
!*+-/=<> <= ==
// operators
Code block 44
break;
Code block 45
case
'"'
:
string
();
break
;
Code block 46
default:
Code block 47
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
print
-
123
.
abs
();
Code block 49
var
n
=
123
;
print
-
n
.
abs
();
Code block 50
1234
12.34
Code block 51
.
1234
1234
.
Code block 52
default:
Code block 53
if
(
isDigit
(
c
)) {
number
();
}
else
{
Lox
.
error
(
line
,
"Unexpected character."
);
}
Code block 54
break;
Code block 55
private
boolean
isDigit
(
char
c
) {
return
c
>=
'0'
&&
c
<=
'9'
;
}
Code block 56
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
private
char
peekNext
() {
if
(
current
+
1
>=
source
.
length
())
return
'\0'
;
return
source
.
charAt
(
current
+
1
);
}
Code block 58
case
'o'
:
if
(
match
(
'r'
)) {
addToken
(
OR
);
}
break
;
Code block 59
---
a
;
Code block 60
- --
a
;
Code block 61
-- -
a
;
Code block 62
default:
if (isDigit(c)) {
number();
Code block 63
}
else
if
(
isAlpha
(
c
)) {
identifier
();
Code block 64
} else {
Lox.error(line, "Unexpected character.");
}
Code block 65
private
void
identifier
() {
while
(
isAlphaNumeric
(
peek
()))
advance
();
addToken
(
IDENTIFIER
);
}
Code block 66
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
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
while (isAlphaNumeric(peek())) advance();
Code block 69
String
text
=
source
.
substring
(
start
,
current
);
TokenType
type
=
keywords
.
get
(
text
);
if
(
type
==
null
)
type
=
IDENTIFIER
;
addToken
(
type
);
Code block 70
}
Code block 71
if
(
condition
)
return
"value"
Code block 72
func
(
parenthesized
)
Code block 73
first
-
second
Code block 74
a
=
1
b
=
2
Code block 75
console
.
log
(
function
() {
statement
();
});
~~~+
## 参考资料
- [原文:Scanning](https://craftinginterpreters.com/scanning.html)
- [Crafting Interpreters 系列索引](00%20系列索引.md)
> 版权说明:官方页面标注 © 2015–2021。原作版权归 Robert Nystrom 及相关权利人所有。本笔记为个人学习用途的中文翻译。
评论 (0)