题目链接:UVA12421
难得一见的编译原理题。题解中大佬们都是不错的,不过我想补充一个真正从编译原理角度进行思考的题解。因此,费曼技巧一下,顺便还巩固一下我自己的基本编译原理知识。
想入门编译原理的,推荐这本书:《Crafting Interpreter》,比传统的编译原理书籍更简单且更现代。在线阅读链接:英语、简体中文(志愿翻译)。这本书的教学语言 Lox 语言也是我学习编译原理“梦开始的地方”。后来我自己的 Loxinas 语言的名字就以 Lox 作为前缀。
本题解将不会过多涉及到编译原理的细节问题,给出一个大方向的思考方式和带注释的代码。因此,如果你还刚开始学习编程,不保证你能看懂。
声明
这篇题解发布的时候,洛谷的 RemoteJudge 已经不可用,而 UVa 访问不稳定且所支持的编程语言太老。因此,这里面的代码是经过人工构造数据(包括讨论区中的 hack 数据)进行测试的。我自学了一些 Lua 编程语言(刚好 Neovim 要用)并编写了一些简单的程序进行测试,确认在大多数情况下本片题解的代码是正确的。
当然,也无法避免有我没有考虑到的情况。如果你发现了 hack 数据,请公布在讨论区,我在看到并复现后将第一时间修改。也欢迎其他大佬提供思路或代码的建议。不过,对于 Mini-Lua 这种简单的教育型玩具编程语言,请避免推荐使用复杂的编译原理技术。
本文中的理论与技术包含了我个人在学习过程中的总结与感悟,有不准确或错误的地方可以指出。
谢谢!
这是 Mua 编程语言解释器(Interpreter)系列的第一题,要求实现一个 Lua 编成语言的子集——Mini-Lua 语言(简称 Mua)——的词法分析器(Lexical Analyzer,也可称作 Lexer)。词法分析器将一串源代码按照语言的语法规则分割为若干个 Token(可译作词素)。这些 Token 所组成的 Token 列表将传递给语法解析器(Syntax Parser)来进行进一步的处理。在 Mua 编程语言解释器系列的第二题中,我们就将编写一个简单的语法解析器。
简单编译原理概览
这部分内容是大背景,如果你只是想通过这道题或学习词法分析器,你可以跳过这一部分。
这是一般的简单编译器或解释器前端的大体流程图:
源代码:纯文本
|
|
词法分析器:Token 列表
|
|
语法解析器:抽象语法树(AST)
|
|
语义分析器:带语义分析结果的抽象语法树 或 高级中间代码(HIR)
|
|
前端编译器:最终代码(机器代码 或 低级中间代码 或 虚拟机字节码)当然,真正的编译器或解释器要更复杂一些。首先就是词法分析器不一定要生成 Token 列表,而是可以由语法解析器自主调用,按需进行词法扫描。
C++ 的变更中就有这样的例子:在 C++11 以前,模板类型的右尖括号不能连在一起,否则,根据词法分析器的贪心扫描,会被识别为右移运算符:
std::vector<std::vector<int> >;
// ^在 C++ 11 标准发布后,该问题被解决。
一种解决方案就是,不要一次性就把整个源代码扫描成 Token 列表,而是根据在语法解析器在进行语法解析的时候,根据需要调用词法分析器,实时生成 Token。在调用过程中,你可以传入上下文(Context),以控制词法分析器的行为。
在上面这个 C++ 的例子中,语法解析器在解析一个类型标识,那么语法解析器在调用词法分析器的时候,就可以通知词法分析器:我正在解析一个类型标识。这时候词法分析器就知道:我不应该将其解析为右移运算符。
此外,语义分析器和前端编译器大多也是融合的,因为编译需要语义分析结果,而分析结果可能又依赖于前面某些编译的结果。
当然,编译的优化,例如常量折叠、循环展开、死代码消除、内联优化等,也是在编译阶段发生的。
编译原理的世界,无比广阔。
本题的词法分析器
构建词法结构
Token 是有不同类型的,不同类型的 Token 需要保留不同的数据供后面的语法解析器使用。而词法分析器需要返回统一的 Token 列表。因此我们得使用一种属于性的建模模式来代表各个 Token。在面向对象中,可以使用继承或接口来实现。当然,在其他编程语言中也有其他的解决方案。这里介绍三种。
面向对象的多态
在 C++、C#、Java 等编程语言中,面向对象所带来的多态性是很有用的。哪怕在这题中我们暂时不会添加多态的方法(Method),但继承带来的天然的所属的性质使得我们很容易将各种 Token 进行统一建模。
例如,在 C++ 语言中,可以这样进行建模:
//! C++
class Token {
public:
virtual ~Token() = default; // 添加至少一个虚函数以启用 RTTI(运行时类型表示)。当无其他方法可以作为虚函数时,一般虚化默认析构函数。
};
class TokenNumber final: public Token {
public:
double value;
TokenNumber(double init): value(init) {}
};
class TokenString final: public Token {
public:
std::string value;
TokenString(std::string&& init): value(init) {} // 我们在这里使用右值引用来强制使用者移动字符串,提高性能。
};
// 就可以这样表示 Token 列表:
std::vector<Token*> token_list;
// 以这种方式构造各种类型的 Token 并统一使用 Token 类型管理和存储:
Token* token_number = new TokenNumber(1.2);
Token* token_string = new TokenString("hello");
token_list.push_back(token_number);
token_list.push_back(token_string);在 C# 中使用面向对象则更方便:
//! C#
interface IToken;
sealed record class TokenNumber(double Value): IToken;
sealed record class TokenString(string Value): IToken;
// 就可以这样表示 Token 列表:
List<IToken> tokenList;
// 以这种方式构造各种类型的 Token 并统一使用 Token 类型管理和存储:
IToken tokenNumber = new TokenNumber(1.2);
IToken tokenString = new TokenString("hello");
tokenList.Add(tokenNumber);
tokenList.Add(tokenString);
枚举与联合配合使用
这适合在 C 语言中使用。直接看例子吧:
//! C
typedef enum {
Number,
String,
} TokenType;
typedef struct {
TokenType token_type;
union {
double number_value;
char* string_value;
} value;
} Token;
// 就可以这样表示 Token 列表:
Token* token_list;
// 以这种方式构造各种类型的 Token 并统一使用 Token 类型管理和存储:
// 这里假设 token_list 已经分配足够的内存,且有下面的函数向其中添加值:
size_t token_list_append(Token* token_list, size_t size, Token token);
// 有下面的函数统一进行字符串内存管理的构建,方便回收内存(因为字符串字面量是静态值,不能释放内存):
char* make_string(const char* source);
// 有下面的变量记录 Token 列表的大小:
size_t token_size;
// 这里使用了 C99 的方式来构造结构体。
Token token_number = (Token){
.token_type = Number,
.value.number_value = 1.2,
};
Token token_string = (Token){
.token_type = String,
.value.string_value = make_string("hello"),
};
token_size = token_list_append(token_list, token_size, token_number);
token_size = token_list_append(token_list, token_size, token_string);使用枚举标记 Token 的具体类型,并把相应的值用联合体存储一下。
结构体“继承”技巧
事实上在 C 语言中,有一种“继承”结构体的技巧。由于 C 标准要求结构体的第一个成员必须偏移量为 0(不得在前面进行内存对齐),我们事实上可以利用此特性来在 C 语言中模拟“继承”的效果。
具体看代码:
//! C
typedef enum {
Number,
String,
} TokenType;
typedef struct {
TokenType token_type;
} Token;
typedef struct {
Token base;
double value;
} TokenNumber;
typedef struct {
Token base;
char* value;
} TokenString;
// 就可以这样表示 Token 列表:
Token** token_list;
// 以这种方式构造各种类型的 Token 并统一使用 Token 类型管理和存储:
// 这里假设 token_list 已经分配足够的内存,且有下面的函数向其中添加值:
size_t token_list_append(Token** token_list, size_t size, Token* token);
// 有下面的函数统一进行字符串内存管理的构建,方便回收内存(因为字符串字面量是静态值,不能释放内存):
char* make_string(const char* source);
// 有下面的变量记录 Token 列表的大小:
size_t token_size;
// 构造并强制类型转换,这里省略了内存分配异常的检测:
TokenNumber* token_number = malloc(sizeof(TokenNumber));
token_number->base->token_type = Number;
token_number->value = 1.2
TokenString* token_string = malloc(sizeof(TokenString));
token_string->base->token_type = String;
token_string->value = make_string("hello");
Token* token_number_token = (Token*)token_number;
Token* token_string_token = (Token*)token_string;
token_size = token_list_append(token_list, token_size, token_number_token);
token_size = token_list_append(token_list, token_size, token_string_token);由于我们不在 Mua 系列题目的解释器中使用 C 语言,所以这个方法大家了解就好。
枚举变体
枚举变体是另一种实现方式,类似 C 语言的枚举与联合配合,但更现代也更安全。这一方法的性能远超需要运行时类型表示(RTTI)的面向对象结构,以 Rust 著称。这恐怕是最简洁的一种实现方式了。
下面是一个例子:
//! Rust
enum Token {
Number(f64),
String(String),
}
// 就可以这样表示 Token 列表:
let mut token_list: Vec<Token>;
// 以这种方式构造各种类型的 Token 并统一使用 Token 类型管理和存储:
let token_number = Token::Number(1.2);
let token_string = Token::String("hello".to_string()); // 字符串字面量是 &'static str 类型,需要转换为 String 类型,这里有数据复制的性能损耗。复杂项目可以考虑使用 Cow(Copy on Write,写时复制)技术。
token_list.push(token_number); // 这里使用数据移动,没有复制的性能损耗。
token_list.push(token_string);由于单独介绍这些方法还是需要大量篇幅,并且会偏离我们的主题。所以这里一笔带过,有兴趣的读者可以自行学习。我们继续构思词法分析器的更多内容。
Token 解析方法
接下来介绍各个种类的 Token 的具体解析方法。
保留字与名称
这两者可以放在一起解析,因为它们的区别只有名称是否是特定的而已。所以我们下面统称名称。
由于我们只解析 ASCII 字符的 Mua 代码,因此下面也不考虑 Unicode 的情况。
名称的解析需要注意的是:名称的第一个字符必须是 ASCII 字母或下划线,而其他字符可以是 ASCII 字母、数字或下划线。需要特别判定第一个字符。
随后贪心扫描所有后续的字符,直到遇到一个不合法字符,则视为此 Token 结束。从源代码中提取名称,对比保留字列表即可。
符号
符号的扫描解析也遵循贪心扫描原则,也就是说,对于符号:
<=
需要将其解析为小于等于号,而不是一个小于号和一个等于号。
这里有一种解决方案:对于具有相同前缀的符号,扫描到一个字符的时候,探视(不扫描)下一个字符,并决定是否需要和当前字符拼起来作为一个符号。
举个例子:
=
==
当发现字符 = 的时候,探视下一个字符。如果是 =,则将两个字符拼合,生成“等于”符号(=);如果不是,则生成“赋值”符号(==)。
再例如:
.
..
...
当发现 . 的时候,探视下一个字符。如果不是 .,则生成“表访问(点号)”符号(.);如果是 .,则继续探视:如果继续发现 . 符号,则生成“变长参数(省略号)”符号(...),否则生成“拼接”符号(..)。
拓展:Lua 符号含义
有几个在其他编程语言中使用较少的符号,这里拓展一下。
.. 符号用于字符串拼接:
local name = "Clean".."Ice"
print(name) -- CleanIce
~= 是不等号:
if 1 ~= 2 then
print("Not Equal!") -- 这条语句始终会执行。
end
/ 表示除法。由于 Lua 统一使用浮点数表示数字,因此这个符号固定表示浮点除法(整除使用 // 符号,和 Python 挺像的):
local result = 3 / 2
print(result) -- 1.5
# 表示取字符串或列表的长度:
print(#"Luogu") -- 5
local numbers = {1, 2, 3, 4, 5}
print(#numbers) -- 5
. 表示取出表的某一项,必须满足键是合法标识符的条件。索引操作符 [] 同样可以:
local person = {
name = "Someone",
}
-- 下面三句代码都会打印“Someone”。
print(person.name)
print(person["name"])
print(person[name])
: 表示方法成员方法调用:
local person = {
name = "Luogu",
}
function person:sayHello()
print("Hello, "..self.name)
end
person:sayHello() -- Hello, Luogu
... 表示变长参数。例如:
function printLog(...)
local args = {...}
table.insert(args, 1, "[LOG]")
print(table.concat(args, " "))
end
printLog("1", "2", "hello") -- [LOG] 1 2 hello
[] 还可用于列表索引,不过从 1 开始:
local names = {"Alice", "Bob"}
print(names[1]) -- Alice
print(names[2]) -- Bob
-- 表示注释开始。其标记行注释的开始,并不标记结束。例如:
print("Hello") -- 这是注释。这句代码会打印“Hello”。 -- 这还是注释。
字符串
字符串扫描其实算比较简单的。只不过注意,遇到转义符(\)且后面是引号的时候,不要错误地将其视作字符串的结束标志。
数字
数字是 Mua 词法解析器中最难解析的,因为其结构复杂多变,代码设计精巧。如果这一段看不懂,可以去看看后面的代码。
首先,整数以浮点形式存储。因此我们可以用同一个类型的 Token 表示。整数解析需要注意十六进制的解析:以 0x 开头。当确认数字以这个前缀开头的时候,你就需要以十六进制的方式解析整数。
浮点数更麻烦。首先,Mua 允许省略为 0 的整数部分或小数部分,但不允许都省略。例如,.7 表示 0.7;8. 表示 8.0;而 . 就是点号。
其次,科学记数法是一个难点。在一个正常的数字(非十六进制)之后,可能跟随字母 e 或 E,随后跟随一个可以带符号位的整数表示指数。例如,下面三个数字是相同的:
3.14
31.4e-1
0.314e+1
但是,一旦指数开始了,后面的符号就是运算符(加或减)了,这里要注意。例如,下面的两个表达式是相同的:
3.14e+1+5
3.14e+1 + 5
同样地,字母 e 前面的浮点数可以省略为 0 的整数部分或小数部分:
.14e+1
3.e-1
注释
遇到 -- 的时候,进行注释的扫描。在实际实现中,你可以将注释也视作一种 Token,以简化代码的实现。需要注意的是,Lua 的注释默认到行尾结束,因此需要一直扫描到行尾。换行符不要进行扫描,因为需要产生一个叫 EOL 的特殊 Token。我们在后面解释。
行尾 EOL
Mua 不像 C++ 使用分号作为语句的分隔符,而是使用换行符。这点与 Python 类似。因此,我们需要将换行符单独算作一种 Token。这也说明了为什么前面我们说扫描注释的时候,不要扫描换行符。
文件尾 EOF
题目中没有明确指出我们需要这个 Token,但事实上这个 Token 对于后面编写语法解析器有很大的帮助。我们可以在 Token 列表完全扫描完成之后,额外附加上一个 EOF Token。当然,对于本题而言,你不需要输出这个 Token。
双指针词法扫描
一种常见的进行词法扫描的方法是使用双指针。例如:
提示
接下来我们使用 C++ 语言作为文本中的说明语言。文末有四种编程语言的实现代码。
std::size_t start;
std::size_t current;其中 start 表示当前正在扫描的 Token 在源代码中的起始位置,而 current 表示即将扫描的字符的位置。当一个 Token 扫描完成之后,这个 Token 所对应的在源代码中的位置就是左闭右开区间 [start, current)。随后我们可以使用子字符串(如 C++ 的 std::string::substr 方法)将这个 Token 所对应源代码提取出来。例如:
local variable = 1
当我们扫描 variable 的时候,start 固定在字母 v 的位置,而 current 不断向后移动进行扫描。当 current 移动到字母 e 的下一个位置(即字母 e 之后的空格)的时候,我们发现该 Token 已经扫描完成。因此,将 variable 从源代码中提取出来,并生成一个名称 Token。
为了更方便地操作这两个指针,以及通过这两个指针进行扫描操作,我们可以使用以下接口:
class Lexer final {
/* ... */
private:
std::string source; // 源代码字符串。
std::size_t start; // 起始指针。
std::size_t current; // 扫描指针。
/* ... */
void align_pointer(); // 对齐指针:将 start 移动至当前的 current。在扫描新 Token 前使用。
char advance(); // 消耗字符:返回下一个即将扫描的字符,并消耗该字符(令 current 自增即可)。
char previous(); // 回顾字符:返回最后一个被消耗的字符。
char peek() const; // 探视字符:返回下一个即将扫描的字符但不消耗。
bool match_char(char target); // 匹配字符:如果下一个字符是 target,则消耗,否则保持不变。
bool is_at_end() const; // 是否结尾:返回是否已经扫描到了结尾(current 是否是源代码长度)。
/* ... */
};这里举例看看 advance 方法的实现:
char Lexer::advance() {
if (is_at_end()) {
return '\0';
} else {
return source[current++];
}
}我们用了一个技巧:当需要返回的值不可用时(这里是指没有更多字符可扫描),我们返回空字符 '\0'。由于任何 Token 扫描都不会使用该字符,所以这是一种很好地表示不可用数据的方式。
其他方法的实现类似。
错误处理
其实并不需要进行错误处理。题目保证所给定的 Mua 程序是合法的,这意味着我们不需要考虑可能的错误情况,例如未知字符、未结束的字符串等等。如果代码流程路径中遇到了这些情况,简单地抛出错误即可,因为题目数据中不存在这种错误情况,抛出错误反而可以帮助你调试程序。
例如,进行字符串扫描的时候,我们使用一个循环来判断是否到了字符串的结尾:
while (peek() != str_tag) { // str_tag 是字符串标志,表示字符串开始的是双引号还是单引号。
/* do something... */
}你完全可以假设你绝对不会遇到 peek() 返回 '\0' 而无限循环的可能,因为题目给出而 Mua 程序都是合法的。
假若你真的要进行错误处理,可能是这样的:
while (!is_at_end() && peek() != str_tag) {
/* do something... */
}
if (is_at_end() && previous() != str_tag) { // 还没有等到引号就已经到了文件结尾。
/* 抛出编译错误——语法错误 */
}可见题目已经帮我们省去了很多工作。在真实开发中,错误处理往往是最麻烦的。
代码实现及详细注解
更多的具体内容,就需要配合代码和注释来理解了。我在代码中加了详细的注释,这些注释单拿出来都是一篇小文章了。我选择了我最喜欢的四门编程语言——C++、Rust、C#、Python——进行实现。你可以阅读你熟悉的编程语言代码。
代码中的注释不仅有实现词法分析器的说明,也有编程语言相关的解释。
说实话,让我把这么大的项目写在一个文件里真的很折磨人……
C++ 代码实现及注解
#include <cstddef> // for: std::size_t
#include <iostream> // for: std::cin
#include <iterator> // for: std::istreambuf_iterator
#include <locale> // for: std::locale, std::isspace, std::isalnum, std::isalpha, std::isdigit, std::tolower
#include <print> // for: std::print, std::println
#include <stdexcept> // for: std::logic_error
#include <string> // for: std::string, std::stod, std::stoull
#include <typeinfo> // for: std::type_info
#include <unordered_map> // for: std::unordered_map
#include <utility> // for: std::move
#include <vector> // for: std::vector
// 保留字枚举量。
enum class ReservedWord {
And,
Break,
Do,
Else,
ElseIf,
End,
False,
For,
Function,
If,
In,
Local,
Nil,
Not,
Or,
Repeat,
Return,
Then,
True,
Until,
While,
};
// 符号枚举量。
enum class Symbol {
Add, // +
Minus, // -
Multiply, // *
Divide, // /
Mod, // %
Power, // ^
Length, // #
Equal, // ==
GreaterEqual, // >=
LessEqual, // <=
Less, // <
Greater, // >
NotEqual, // ~=
LeftParen, // (
RightParen, // )
LeftBrace, // {
RightBrace, // }
LeftBracket, // [
RightBracket, // ]
Semicolon, // ;
Colon, // :
Comma, // ,
Dot, // .
Concat, // ..
Ellipsis, // ...
Assign, // =
};
// 总的 Token 基类。
class Token {
public:
virtual ~Token() = default; // 至少提供一个虚函数才能启用 RTTI(运行时类型表示)。
};
// 保留字 Token。
class TokenReserved final: public Token { // 继承 Token。final 是上下文关键字,在此处才被视作关键字,表示无法被继续继承。
public:
ReservedWord value;
TokenReserved(ReservedWord init);
};
// 数字 Token。
class TokenNumber final: public Token {
public:
double value; // Mua 中数字统一都是浮点数。
TokenNumber(double init);
};
// 字符串 Token。
class TokenString final: public Token {
public:
std::string value;
TokenString(std::string&& init); // 使用右值引用,强制要求调用者移动字符串,减少复制开销。
};
// 符号 Token。
class TokenSymbol final: public Token {
public:
Symbol value;
TokenSymbol(Symbol init);
};
// 名称 Token。
class TokenName final: public Token {
public:
std::string value;
TokenName(std::string&& init);
};
// 注释 Token。作占位符用的。
class TokenComment final: public Token {};
// 行尾 Token。
class TokenEOL final: public Token {};
// 文件尾 Token。
class TokenEOF final: public Token {};
// 词法分析器。
class Lexer final {
private:
std::string source; // 源代码。
std::size_t current; // 扫描指针。
std::size_t start; // 起始指针。
// 这是保留字列表。
inline static std::unordered_map<std::string, ReservedWord> reserved_words = {
{"and", ReservedWord::And},
{"break", ReservedWord::Break},
{"do", ReservedWord::Do},
{"else", ReservedWord::Else},
{"elseif", ReservedWord::ElseIf},
{"end", ReservedWord::End},
{"false", ReservedWord::False},
{"for", ReservedWord::For},
{"function", ReservedWord::Function},
{"if", ReservedWord::If},
{"in", ReservedWord::In},
{"local", ReservedWord::Local},
{"nil", ReservedWord::Nil},
{"not", ReservedWord::Not},
{"or", ReservedWord::Or},
{"repeat", ReservedWord::Repeat},
{"return", ReservedWord::Return},
{"then", ReservedWord::Then},
{"true", ReservedWord::True},
{"until", ReservedWord::Until},
{"while", ReservedWord::While},
};
Token* scan_token(); // 扫描单个 Token。
void scan_comment(); // 扫描注释。
TokenNumber* scan_number(); // 扫描数字 Token。
TokenString* scan_string(); // 扫描字符串 Token。
Token* scan_name(); // 扫描名称 Token。
char parse_escape(); // 解析转义字符。
std::string extract_word() const; // 提取 Token 对应的源代码。
void skip_whitespace(); // 忽略空白符。
void align_pointer(); // 对齐指针,将 start 移动至 current。
static bool is_name_char(char ch, bool start); // 判断是否是名称中的合法字符。
bool is_at_end() const; // 判断是否扫描到结尾。
char advance(); // 消耗并返回下一个字符。
char previous(); // 返回最后一个被扫描过的字符。
char peek() const; // 探视下一个即将扫描的字符。
bool match_char(char target); // 探视下一个字符,若匹配则消耗。
public:
std::vector<Token*> token_list; // Token 列表。
Lexer(std::string&& init);
void scan_tokens(); // 扫描所有 Token。
};
void clear_resources(const Lexer& lexer); // 清理资源。
int main() {
std::string source{std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>()}; // 一次性读取标准输入。
Lexer lexer(std::move(source)); // 构建词法分析器。
lexer.scan_tokens(); // 扫描词法。
clear_resources(lexer); // 记得清理资源。
return 0;
}
void clear_resources(const Lexer& lexer) {
for (const Token* token : lexer.token_list) {
delete token; // 释放所有 Token 所占用的内存。
}
}
TokenReserved::TokenReserved(ReservedWord init): value(init) {}
TokenNumber::TokenNumber(double init): value(init) {}
TokenString::TokenString(std::string&& init): value(init) {}
TokenSymbol::TokenSymbol(Symbol init): value(init) {}
TokenName::TokenName(std::string&& init): value(init) {}
Lexer::Lexer(std::string&& init): source(init), current(0), start(0), token_list() {}
void Lexer::scan_tokens() {
while (!is_at_end()) { // 持续扫描。
Token* token = scan_token();
const std::type_info& type_info = typeid(*token); // 获取运行时类型信息(Token 的实际类型)。
if (type_info != typeid(TokenComment)) { // 忽略注释 Token。
std::string word = extract_word(); // 题目要求输出的是源代码中的原始表示,因此我们在指针对齐之前提取 Token 源代码。
std::string token_type; // 保留 Token 类型字符串。
// 实际上 typeid + if-else 是一种不怎么好的程序设计(可以用虚函数多态代替),但 Mua 编程语言较简单,我们姑且先这样设计。
if (type_info == typeid(TokenReserved)) {
token_type = "[RESERVED]";
} else if (type_info == typeid(TokenNumber)) {
token_type = "[NUMBER]";
} else if (type_info == typeid(TokenString)) {
token_type = "[STRING]";
} else if (type_info == typeid(TokenSymbol)) {
token_type = "[SYMBOL]";
} else if (type_info == typeid(TokenName)) {
token_type = "[NAME]";
} else if (type_info == typeid(TokenEOL)) {
token_type = "[EOL]";
} else if (type_info == typeid(TokenComment)) {
throw std::logic_error("Unexpected Comment token."); // 不应该出现的情况(不可达路径),直接抛出错误。
} else if (type_info == typeid(TokenEOF)) {
throw std::logic_error("Unexpected EOF token.");
} else {
std::unreachable();
}
std::print("{}", token_type);
if (type_info == typeid(TokenEOL)) {
std::println();
} else {
std::println(" {}", word);
}
token_list.push_back(token); // 加入 Token 列表。
} else {
delete token; // 由于 TokenComment* 不会被加入 Token 列表,因此程序结束的时候不会回收这部分资源,因此需要立即释放占用的内存。
}
}
token_list.push_back(new TokenEOF()); // 人工加入一个文件尾 Token。
}
Token* Lexer::scan_token() {
skip_whitespace(); // 先跳过空白符。
align_pointer(); // 再对齐指针。
switch (advance()) {
case '\n': return new TokenEOL(); // 换行也要被扫描成一个 Token。
case '+': return new TokenSymbol(Symbol::Add);
case '-':
if (match_char('-')) { // 贪心匹配。
scan_comment();
return new TokenComment();
} else {
return new TokenSymbol(Symbol::Minus);
}
case '*': return new TokenSymbol(Symbol::Multiply);
case '/': return new TokenSymbol(Symbol::Divide);
case '%': return new TokenSymbol(Symbol::Mod);
case '^': return new TokenSymbol(Symbol::Power);
case '#': return new TokenSymbol(Symbol::Length);
case '=':
if (match_char('=')) {
return new TokenSymbol(Symbol::Equal);
} else {
return new TokenSymbol(Symbol::Assign);
}
case '>':
if (match_char('=')) {
return new TokenSymbol(Symbol::GreaterEqual);
} else {
return new TokenSymbol(Symbol::Greater);
}
case '<':
if (match_char('=')) {
return new TokenSymbol(Symbol::LessEqual);
} else {
return new TokenSymbol(Symbol::Less);
}
case '~':
if (match_char('=')) {
return new TokenSymbol(Symbol::NotEqual);
} else {
throw std::logic_error("Invalid token."); // 不可达路径:题目保证 Mua 程序有效。
}
case '(': return new TokenSymbol(Symbol::LeftParen);
case ')': return new TokenSymbol(Symbol::RightParen);
case '{': return new TokenSymbol(Symbol::LeftBrace);
case '}': return new TokenSymbol(Symbol::RightBrace);
case '[': return new TokenSymbol(Symbol::LeftBracket);
case ']': return new TokenSymbol(Symbol::RightBracket);
case ';': return new TokenSymbol(Symbol::Semicolon);
case ':': return new TokenSymbol(Symbol::Colon);
case ',': return new TokenSymbol(Symbol::Comma);
case '.':
if (std::isdigit(peek(), std::locale())) { // 省略整数部分的数字。
return scan_number();
} else if (match_char('.')) {
if (match_char('.')) {
return new TokenSymbol(Symbol::Ellipsis);
} else {
return new TokenSymbol(Symbol::Concat);
}
} else {
return new TokenSymbol(Symbol::Dot);
}
case '"':
case '\'':
return scan_string();
default:
char ch = previous();
if (std::isdigit(ch, std::locale())) {
return scan_number();
} else if (is_name_char(ch, true)) {
return scan_name();
} else {
throw std::logic_error("Invalid token.");
}
}
}
void Lexer::scan_comment() {
while (peek() != '\n') { // 不要消耗换行符。
advance();
}
}
TokenNumber* Lexer::scan_number() {
bool hex = false; // 十六进制。
bool floating = false; // 浮点数。
bool science = false; // 科学记数法。
if (previous() == '0' && (match_char('x') || match_char('X'))) { // 检测十六进制。注意短路求值,不会出现 0xX 被误判的情况。
hex = true;
}
if (previous() == '.') { // 省略整数的浮点数。
floating = true;
}
bool signed_power = false; // 科学记数法指数部分已出现符号。
bool number_power = false; // 科学记数法指数部分已出现数字。
while (true) {
char ch = peek();
if (std::isdigit(ch, std::locale())) {
if (science) {
number_power = true;
}
advance();
} else if (!hex && (ch == 'e' || ch == 'E')) { // 在十六进制整数中,e 或 E 应该被当作数位。
floating = true;
science = true;
advance();
} else if ('a' <= std::tolower(ch, std::locale()) && std::tolower(ch, std::locale()) <= 'f') {
if (hex) {
advance();
} else {
throw std::logic_error("Invalid number."); // 不可达路径。
}
} else if (ch == '.') {
if (hex || floating) {
throw std::logic_error("Invalid number.");
} else {
advance();
floating = true;
}
} else if ((ch == '-' || ch == '+') && science && !signed_power && !number_power) {
signed_power = true;
advance();
} else {
break;
}
}
std::string word = extract_word();
// C++ 的标准库函数可以正确转换这些数字格式。
if (floating) {
return new TokenNumber(std::stod(word));
} else {
// 使用 unsigned long long,避免整数太大。不必考虑负数,负号被解析为单个符号。
if (hex) {
return new TokenNumber(static_cast<double>(std::stoull(word.substr(2, word.size() - 2), nullptr, 16)));
} else {
return new TokenNumber(static_cast<double>(std::stoull(word, nullptr, 10)));
}
}
}
TokenString* Lexer::scan_string() {
char str_tag = previous(); // 哪种引号。
std::string string;
while (peek() != str_tag) {
if (match_char('\\')) { // 转义符。
string += parse_escape();
} else {
string += advance();
}
}
advance(); // 消耗结尾的引号。
return new TokenString(std::move(string)); // 移动语义,减小复制开销。
}
Token* Lexer::scan_name() {
while (is_name_char(peek(), false)) {
advance();
}
std::string word = extract_word();
if (reserved_words.contains(word)) { // 查找保留字。
return new TokenReserved(reserved_words[word]);
} else {
return new TokenString(std::move(word));
}
}
char Lexer::parse_escape() {
switch (advance()) {
case '\\': return '\\';
case 'n': return '\n';
case '\'': return '\'';
case '"': return '"';
default: throw std::logic_error("Invalid escape char.");
}
}
std::string Lexer::extract_word() const {
return source.substr(start, current - start);
}
void Lexer::skip_whitespace() {
while (peek() != '\n' && std::isspace(peek(), std::locale())) { // 不要消耗换行符!
advance();
}
}
void Lexer::align_pointer() {
start = current;
}
bool Lexer::is_name_char(char ch, bool start) {
if (start && (std::isalpha(ch, std::locale()) || ch == '_')) {
return true;
} else if (std::isalnum(ch, std::locale()) || ch == '_') {
return true;
} else {
return false;
}
}
bool Lexer::is_at_end() const {
return current >= source.size();
}
char Lexer::advance() {
if (is_at_end()) {
return '\0';
} else {
return source[current++];
}
}
char Lexer::previous() {
if (current == 0) {
return '\0';
} else {
return source[current - 1];
}
}
char Lexer::peek() const {
if (is_at_end()) {
return '\0';
} else {
return source[current];
}
}
bool Lexer::match_char(char target) {
if (is_at_end()) {
return false;
} else {
if (peek() == target) {
advance();
return true;
} else {
return false;
}
}
}Rust 代码实现及注解
use std::collections::HashMap;
use std::io::{self, Read};
fn main() {
let mut source = String::new();
io::stdin().read_to_string(&mut source).unwrap(); // 一次性读取标准输入。
let mut lexer = Lexer::new(source); // 构建词法分析器。
lexer.scan_tokens(); // 扫描所有词法。
}
// Token 枚举变体。
enum Token {
Reserved(ReservedWord), // 保留字 Token。
Number(f64), // 数字 Token。
String(String), // 字符串 Token。
Symbol(Symbol), // 符号 Token。
Name(String), // 名称 Token。
Comment, // 注释 Token。
EOL, // 换行 Token。
EOF, // 文件尾 Token。
}
// 保留字枚举。
#[derive(Clone)] // 非变体的枚举复制的性能很高,开销可忽略不计。
enum ReservedWord {
And,
Break,
Do,
Else,
ElseIf,
End,
False,
For,
Function,
If,
In,
Local,
Nil,
Not,
Or,
Repeat,
Return,
Then,
True,
Until,
While,
}
// 符号枚举。
enum Symbol {
Add, // +
Minus, // -
Multiply, // *
Divide, // /
Mod, // %
Power, // ^
Length, // #
Equal, // ==
GreaterEqual, // >=
LessEqual, // <=
Less, // <
Greater, // >
NotEqual, // ~=
LeftParen, // (
RightParen, // )
LeftBrace, // {
RightBrace, // }
LeftBracket, // [
RightBracket, // ]
Semicolon, // ;
Colon, // :
Comma, // ,
Dot, // .
Concat, // ..
Ellipsis, // ...
Assign, // =
}
// 词法分析器。
struct Lexer {
source: Vec<char>, // 源代码(使用 char 列表,String 的下标访问是访问码点而不是字符)。
token_list: Vec<Token>, // Token 列表。
current: usize, // 扫描指针。
start: usize, // 起始指针。
reserved_words: HashMap<String, ReservedWord>, // 保留字列表。
}
impl Lexer {
fn new(source: String) -> Self {
Self {
source: source.chars().collect(),
token_list: vec![],
current: 0,
start: 0,
reserved_words: [ // 初始化保留字列表。
("and", ReservedWord::And),
("break", ReservedWord::Break),
("do", ReservedWord::Do),
("else", ReservedWord::Else),
("elseif", ReservedWord::ElseIf),
("end", ReservedWord::End),
("false", ReservedWord::False),
("for", ReservedWord::For),
("function", ReservedWord::Function),
("if", ReservedWord::If),
("in", ReservedWord::In),
("local", ReservedWord::Local),
("nil", ReservedWord::Nil),
("not", ReservedWord::Not),
("or", ReservedWord::Or),
("repeat", ReservedWord::Repeat),
("return", ReservedWord::Return),
("then", ReservedWord::Then),
("true", ReservedWord::True),
("until", ReservedWord::Until),
("while", ReservedWord::While),
].into_iter().map(|x| (x.0.to_string(), x.1)).collect(), // 转迭代器并将 &str 转换为 String 之后收集为 HashMap。
}
}
// 扫描 Token 列表。
fn scan_tokens(&mut self) {
while !self.is_at_end() { // 持续扫描。
let token = self.scan_token(); // 扫描 Token。
if !matches!(token, Token::Comment) { // 忽略注释 Token。
let word = self.extract_word(); // 题目要求输出 Token 对应的源代码,因此在指针对齐之前提取 Token 的源代码。
print!(
"{token_type}",
token_type = match token { // 基于表达式的语法体系的强大!模式匹配的强大!
Token::Reserved(_) => "[RESERVED]",
Token::Number(_) => "[NUMBER]",
Token::String(_) => "[STRING]",
Token::Symbol(_) => "[SYMBOL]",
Token::Name(_) => "[NAME]",
Token::EOL => "[EOL]",
Token::Comment => unreachable!("Unexpected Comment token."),
Token::EOF => unreachable!("Unexpected EOF token."),
}
);
if matches!(token, Token::EOL) {
println!();
} else {
println!(" {word}");
}
self.token_list.push(token); // 加入 Token 列表。
}
}
self.token_list.push(Token::EOF); // 人工添加文件尾 Token。
}
// 扫描单个 Token。
fn scan_token(&mut self) -> Token {
self.skip_whitespace(); // 先忽略空白符。
self.align_pointer(); // 再对齐指针。
match self.advance() {
'\n' => Token::EOL, // 换行符被解析为行尾 Token。
'+' => Token::Symbol(Symbol::Add),
'-' => if self.match_char('-') { // 贪心匹配。
self.scan_comment(); // 扫描注释。
Token::Comment
} else {
Token::Symbol(Symbol::Minus)
},
'*' => Token::Symbol(Symbol::Multiply),
'/' => Token::Symbol(Symbol::Divide),
'%' => Token::Symbol(Symbol::Mod),
'^' => Token::Symbol(Symbol::Power),
'#' => Token::Symbol(Symbol::Length),
'=' => if self.match_char('=') {
Token::Symbol(Symbol::Equal)
} else {
Token::Symbol(Symbol::Assign)
},
'>' => if self.match_char('=') {
Token::Symbol(Symbol::GreaterEqual)
} else {
Token::Symbol(Symbol::Greater)
},
'<' => if self.match_char('=') {
Token::Symbol(Symbol::LessEqual)
} else {
Token::Symbol(Symbol::Less)
},
'~' => if self.match_char('=') {
Token::Symbol(Symbol::NotEqual)
} else {
unreachable!("Invalid token.") // 不可达路径。
},
'(' => Token::Symbol(Symbol::LeftParen),
')' => Token::Symbol(Symbol::RightParen),
'{' => Token::Symbol(Symbol::LeftBrace),
'}' => Token::Symbol(Symbol::RightBrace),
'[' => Token::Symbol(Symbol::LeftBracket),
']' => Token::Symbol(Symbol::RightBracket),
';' => Token::Symbol(Symbol::Semicolon),
':' => Token::Symbol(Symbol::Colon),
',' => Token::Symbol(Symbol::Comma),
'.' => if self.peek().is_numeric() { // 省略整数的数字 Token。
self.scan_number()
} else if self.match_char('.') {
if self.match_char('.') {
Token::Symbol(Symbol::Ellipsis)
} else {
Token::Symbol(Symbol::Concat)
}
} else {
Token::Symbol(Symbol::Dot)
},
'"' | '\'' => self.scan_string(),
ch if ch.is_numeric() => self.scan_number(),
ch if Self::is_name_char(ch, true) => self.scan_name(),
_ => unreachable!("Invalid token."), // 不可达路径。
}
}
// 扫描注释。
fn scan_comment(&mut self) {
while self.peek() != '\n' { // 不要扫描换行符!
self.advance();
}
}
// 扫描数字 Token。
fn scan_number(&mut self) -> Token {
let mut hex = false; // 十六进制。
let mut float = false; // 浮点数。
let mut science = false; // 科学记数法。
if self.previous() == '0' && (self.match_char('x') || self.match_char('X')) { // 判断十六进制。注意短路求值,不会误判类似 0xX 的东西。
hex = true;
}
if self.previous() == '.' { // 省略整数的浮点数。
float = true;
}
let mut signed_power = false; // 科学记数法指数部分已经出现符号。
let mut number_power = false; // 科学记数法指数部分已经出现数字。
loop {
let ch = self.peek();
if ch.is_numeric() {
if science {
number_power = true;
}
self.advance();
} else if !hex && (ch == 'e' || ch == 'E') { // 在十六进制整数中,e 和 E 应该被视作数位。
float = true;
science = true;
self.advance();
} else if let 'a'..='f' = ch.to_lowercase().next().unwrap() { // 模式匹配的强大!
if hex {
self.advance();
} else {
unreachable!("Invalid number.");
}
} else if ch == '.' {
if hex || float {
unreachable!("Invalid number.");
} else {
self.advance();
float = true;
}
} else if (ch == '-' || ch == '+') && science && !signed_power && !number_power {
signed_power = true;
self.advance();
} else {
break;
}
}
let word = self.extract_word(); // 提取数字源代码。
// Rust 的标准库函数可以正确转换这些格式的数字。
if float {
Token::Number(word.parse::<f64>().unwrap())
} else {
// 使用 u64 避免整数过大。不需要考虑负数,负号被解析为单独的符号。
if hex {
Token::Number(u64::from_str_radix(&word[2..], 16).unwrap() as f64)
} else {
Token::Number(word.parse::<u64>().unwrap() as f64)
}
}
}
// 扫描字符串 Token。
fn scan_string(&mut self) -> Token {
let str_tag = self.previous(); // 哪种引号。
let mut string = String::new();
while self.peek() != str_tag {
if self.match_char('\\') {
string.push(self.parse_escape());
} else {
string.push(self.advance());
}
}
self.advance(); // 消耗结尾的引号。
Token::String(string)
}
// 扫描名称 Token。
fn scan_name(&mut self) -> Token {
while Self::is_name_char(self.peek(), false) {
self.advance();
}
let word = self.extract_word();
if let Some(reserved) = self.reserved_words.get(&word) { // 查找保留字。模式匹配!
Token::Reserved(reserved.clone()) // 非变体枚举的复制性能很高,开销可忽略不计。
} else {
Token::Name(word)
}
}
// 解析转义字符。
fn parse_escape(&mut self) -> char {
match self.advance() {
'\\' => '\\',
'n' => '\n',
'\'' => '\'',
'"' => '"',
_ => unreachable!("Invalid escape char.")
}
}
// 提取源代码。
fn extract_word(&self) -> String {
String::from_iter(&self.source[self.start..self.current])
}
// 跳过空白符。
fn skip_whitespace(&mut self) {
while self.peek() != '\n' && self.peek().is_whitespace() { // 不要扫描换行符!
self.advance();
}
}
// 对齐指针。
fn align_pointer(&mut self) {
self.start = self.current;
}
// 是否是合法的名称字符。
fn is_name_char(ch: char, start: bool) -> bool {
if start && (ch.is_alphabetic() || ch == '_') {
true
} else if ch.is_alphanumeric() || ch == '_' {
true
} else {
false
}
}
// 是否扫描到结尾。
fn is_at_end(&self) -> bool {
self.current >= self.source.len()
}
// 消耗并返回下一个被扫描的字符。
fn advance(&mut self) -> char {
if self.is_at_end() {
'\0'
} else {
self.current += 1;
self.source[self.current - 1]
}
}
// 返回最后被扫描过的字符。
fn previous(&self) -> char {
if self.current == 0 {
'\0'
} else {
self.source[self.current - 1]
}
}
// 探视下一个即将被扫描的字符。
fn peek(&mut self) -> char {
if self.is_at_end() {
'\0'
} else {
self.source[self.current]
}
}
// 探视下一个字符,若匹配则消耗。
fn match_char(&mut self, target: char) -> bool {
if self.is_at_end() {
false
} else {
if self.peek() == target {
self.advance();
true
} else {
false
}
}
}
}C# 代码实现及注解
using System.Diagnostics;
using System.Text;
namespace MiniLuaCSharp;
static class Program {
public static void Main() {
string source = Console.In.ReadToEnd(); // 一次性读取标准输入。
var lexer = new Lexer(source); // 构建词法分析器。
lexer.ScanTokens(); // 扫描所有 Token。
}
}
// 词法分析器。
sealed class Lexer(string source) { // sealed 表示类不可被继承。
private readonly string source = source; // 源代码。
private int current = 0; // 扫描指针。
private int start = 0; // 起始指针。
// 保留字列表。
private static readonly Dictionary<string, ReservedWord> reservedWords = new() {
["and"] = ReservedWord.And,
["break"] = ReservedWord.Break,
["do"] = ReservedWord.Do,
["else"] = ReservedWord.Else,
["elseif"] = ReservedWord.ElseIf,
["end"] = ReservedWord.End,
["false"] = ReservedWord.False,
["for"] = ReservedWord.For,
["function"] = ReservedWord.Function,
["if"] = ReservedWord.If,
["in"] = ReservedWord.In,
["local"] = ReservedWord.Local,
["nil"] = ReservedWord.Nil,
["not"] = ReservedWord.Not,
["or"] = ReservedWord.Or,
["repeat"] = ReservedWord.Repeat,
["return"] = ReservedWord.Return,
["then"] = ReservedWord.Then,
["true"] = ReservedWord.True,
["until"] = ReservedWord.Until,
["while"] = ReservedWord.While,
};
public List<IToken> TokenList = []; // Token 列表。
// 扫描 Token 列表。
public void ScanTokens() {
while (!IsAtEnd()) { // 持续扫描。
IToken token = ScanToken(); // 扫描单个 Token。
if (token is not TokenComment) { // 忽略注释 Token。
string word = ExtractWord(); // 题目要求输出 Token 所对应的源代码原始表示,因此在对齐指针之前提取 Token 对应的源代码。
string tokenType = token switch { // 获取 Token 类型。
TokenReserved => "[RESERVED]",
TokenNumber => "[NUMBER]",
TokenString => "[STRING]",
TokenSymbol => "[SYMBOL]",
TokenName => "[NAME]",
TokenEOL => "[EOL]",
TokenComment => throw new UnreachableException("Unexpected Comment token."), // 不可达代码。
TokenEOF => throw new UnreachableException("Unexpected EOF token."),
_ => throw new UnreachableException("Unknown token type."),
};
Console.Write($"{tokenType}");
if (token is TokenEOL) {
Console.WriteLine();
} else {
Console.WriteLine($" {word}");
}
TokenList.Add(token); // 加入 Token 列表。
}
}
TokenList.Add(new TokenEOF()); // 人工手动加入文件尾 Token。
}
// 扫描单个 Token。
private IToken ScanToken() {
SkipWhitespace(); // 先跳过空白符。
AlignPointer(); // 再对齐指针。
switch (Advance()) {
case '\n': return new TokenEOL(); // 行尾 Token。
case '+': return new TokenSymbol(Symbol.Add);
case '-':
if (MatchChar('-')) { // 贪心匹配。
ScanComment(); // 扫描注释。
return new TokenComment();
} else {
return new TokenSymbol(Symbol.Minus);
}
case '*': return new TokenSymbol(Symbol.Multiply);
case '/': return new TokenSymbol(Symbol.Divide);
case '%': return new TokenSymbol(Symbol.Mod);
case '^': return new TokenSymbol(Symbol.Power);
case '#': return new TokenSymbol(Symbol.Length);
case '=':
if (MatchChar('=')) {
return new TokenSymbol(Symbol.Equal);
} else {
return new TokenSymbol(Symbol.Assign);
}
case '>':
if (MatchChar('=')) {
return new TokenSymbol(Symbol.GreaterEqual);
} else {
return new TokenSymbol(Symbol.Greater);
}
case '<':
if (MatchChar('=')) {
return new TokenSymbol(Symbol.LessEqual);
} else {
return new TokenSymbol(Symbol.Less);
}
case '~':
if (MatchChar('=')) {
return new TokenSymbol(Symbol.NotEqual);
} else {
throw new UnreachableException("Invalid token."); // 不可达代码。
}
case '(': return new TokenSymbol(Symbol.LeftParen);
case ')': return new TokenSymbol(Symbol.RightParen);
case '{': return new TokenSymbol(Symbol.LeftBrace);
case '}': return new TokenSymbol(Symbol.RightBrace);
case '[': return new TokenSymbol(Symbol.LeftBracket);
case ']': return new TokenSymbol(Symbol.RightBracket);
case ';': return new TokenSymbol(Symbol.Semicolon);
case ':': return new TokenSymbol(Symbol.Colon);
case ',': return new TokenSymbol(Symbol.Comma);
case '.':
if (char.IsDigit(Peek())) { // 省略整数部分的数字 Token。
return ScanNumber();
} else if (MatchChar('.')) {
if (MatchChar('.')) {
return new TokenSymbol(Symbol.Ellipsis);
} else {
return new TokenSymbol(Symbol.Concat);
}
} else {
return new TokenSymbol(Symbol.Dot);
}
case '"' or '\'': return ScanString();
case char ch when char.IsDigit(ch): return ScanNumber();
case char ch when IsNameChar(ch, true): return ScanName();
default: throw new UnreachableException("Invalid token."); // 不可达代码。
}
}
// 扫描注释。
private void ScanComment() {
while (Peek() != '\n') { // 不要扫描换行符!
Advance();
}
}
// 扫描数字 Token。
private TokenNumber ScanNumber() {
bool hex = false; // 十六进制。
bool floating = false; // 浮点数。
bool science = false; // 科学记数法。
if (Previous() == '0' && (MatchChar('x') || MatchChar('X'))) { // 判断十六进制。注意短路求值,不会误判类似 0xX 的情况。
hex = true;
}
if (Previous() == '.') { // 省略整数部分的浮点数。
floating = true;
}
bool signedPower = false; // 科学记数法中指数部分已扫描符号。
bool numberPower = false; // 科学记数法中指数部分已扫描数字。
while (true) {
char ch = Peek();
if (char.IsDigit(ch)) {
if (science) {
numberPower = true;
}
Advance();
} else if (!hex && (ch == 'e' || ch == 'E')) { // 在十六进制整数中,字母 e 和 E 应该被视作数位。
floating = true;
science = true;
Advance();
} else if (char.ToLower(ch) is >='a' and <='f') { // 模式匹配!
if (hex) {
Advance();
} else {
throw new UnreachableException("Invalid number.");
}
} else if (ch == '.') {
if (hex || floating) {
throw new UnreachableException("Invalid number.");
} else {
Advance();
floating = true;
}
} else if ((ch == '-' || ch == '+') && science && !signedPower && !numberPower) {
signedPower = true;
Advance();
} else {
break;
}
}
string word = ExtractWord(); // 提取数字源代码。
// C# 标准库函数可以正确转换这些格式的数字。
if (floating) {
return new(double.Parse(word));
} else {
// 使用 ulong 避免数字过大。不需要考虑负数,负号被单独解析成一个符号。
if (hex) {
return new(Convert.ToUInt64(word[2..], 16));
} else {
return new(ulong.Parse(word));
}
}
}
// 扫描字符串 Token。
private TokenString ScanString() {
char strTag = Previous(); // 哪种引号。
var builder = new StringBuilder(); // 使用 StringBuilder 加速字符串拼接。
while (Peek() != strTag) {
if (MatchChar('\\')) {
builder.Append(ParseEscape());
} else {
builder.Append(Advance());
}
}
Advance(); // 消耗末尾引号。
return new(builder.ToString());
}
// 扫描名称 Token。
private IToken ScanName() {
while (IsNameChar(Peek(), false)) {
Advance();
}
string word = ExtractWord();
if (reservedWords.TryGetValue(word, out var reserved)) { // 匹配保留字。
return new TokenReserved(reserved);
} else {
return new TokenName(word);
}
}
// 解析转义字符。
private char ParseEscape() => Advance() switch {
'\\' => '\\',
'n' => '\n',
'\'' => '\'',
'"' => '"',
_ => throw new UnreachableException("Invalid escape char."), // 不可达代码。
};
// 提取源代码。
private string ExtractWord() => source[start..current];
// 跳过空白符。
private void SkipWhitespace() {
while (Peek() != '\n' && char.IsWhiteSpace(Peek())) { // 不要扫描换行符!
Advance();
}
}
// 对齐指针。
private void AlignPointer() => start = current;
// 判断是否是合法的名称字符。
private static bool IsNameChar(char ch, bool start) {
if (start && (char.IsLetter(ch) || ch == '_')) {
return true;
} else if (char.IsLetterOrDigit(ch) || ch == '_') {
return true;
} else {
return false;
}
}
// 是否已经扫描到了结尾。
private bool IsAtEnd() => current >= source.Length;
// 消耗并返回下一个即将扫描的字符。
private char Advance() {
if (IsAtEnd()) {
return '\0';
} else {
return source[current++];
}
}
// 返回最后被扫描过了的字符。
private char Previous() {
if (current == 0) {
return '\0';
} else {
return source[current - 1];
}
}
// 探视下一个即将被扫描的字符。
private char Peek() {
if (IsAtEnd()) {
return '\0';
} else {
return source[current];
}
}
// 探视下一个字符,如果匹配,则消耗。
private bool MatchChar(char target) {
if (IsAtEnd()) {
return false;
} else {
if (Peek() == target) {
Advance();
return true;
} else {
return false;
}
}
}
}
// Token 接口。C# 命名习惯在命名空间名称前加 I。
interface IToken;
// 保留字 Token。
sealed record class TokenReserved(ReservedWord Value): IToken; // record class 是记录类。
// 数字 Token。
sealed record class TokenNumber(double Value): IToken;
// 字符串 Token。
sealed record class TokenString(string Value): IToken;
// 符号 Token。
sealed record class TokenSymbol(Symbol Value): IToken;
// 名称 Token。
sealed record class TokenName(string Value): IToken;
// 注释 Token。
sealed record class TokenComment: IToken;
// 行尾 Token。
sealed record class TokenEOL: IToken;
// 文件尾 Token。
sealed record class TokenEOF: IToken;
// 保留字枚举。
enum ReservedWord {
And,
Break,
Do,
Else,
ElseIf,
End,
False,
For,
Function,
If,
In,
Local,
Nil,
Not,
Or,
Repeat,
Return,
Then,
True,
Until,
While,
}
// 符号枚举。
enum Symbol {
Add, // +
Minus, // -
Multiply, // *
Divide, // /
Mod, // %
Power, // ^
Length, // #
Equal, // ==
GreaterEqual, // >=
LessEqual, // <=
Less, // <
Greater, // >
NotEqual, // ~=
LeftParen, // (
RightParen, // )
LeftBrace, // {
RightBrace, // }
LeftBracket, // [
RightBracket, // ]
Semicolon, // ;
Colon, // :
Comma, // ,
Dot, // .
Concat, // ..
Ellipsis, // ...
Assign, // =
}
Python 代码实现及注解
import enum
import sys
# 模拟主函数。
def main():
source = sys.stdin.read() # 一次性读取标准输入。
lexer = Lexer(source) # 构建词法分析器。
lexer.scan_tokens() # 扫描所有 Token。
# Token 基类。
class Token:
pass
# 保留字枚举。使用标准库 enum.Enum。
class ReservedWord(enum.Enum):
And = enum.auto()
Break = enum.auto()
Do = enum.auto()
Else = enum.auto()
ElseIf = enum.auto()
End = enum.auto()
False_ = enum.auto()
For = enum.auto()
Function = enum.auto()
If = enum.auto()
In = enum.auto()
Local = enum.auto()
Nil = enum.auto()
Not = enum.auto()
Or = enum.auto()
Repeat = enum.auto()
Return = enum.auto()
Then = enum.auto()
True_ = enum.auto()
Until = enum.auto()
While = enum.auto()
# 符号枚举。
class Symbol(enum.Enum):
Add = enum.auto() # +
Minus = enum.auto() # -
Multiply = enum.auto() # *
Divide = enum.auto() # /
Mod = enum.auto() # %
Power = enum.auto() # ^
Length = enum.auto() # #
Equal = enum.auto() # ==
GreaterEqual = enum.auto() # >=
LessEqual = enum.auto() # <=
Less = enum.auto() # <
Greater = enum.auto() # >
NotEqual = enum.auto() # ~=
LeftParen = enum.auto() # (
RightParen = enum.auto() # )
LeftBrace = enum.auto() # {
RightBrace = enum.auto() # }
LeftBracket = enum.auto() # [
RightBracket = enum.auto() # ]
Semicolon = enum.auto() # ;
Colon = enum.auto() # :
Comma = enum.auto() # ,
Dot = enum.auto() # .
Concat = enum.auto() # ..
Ellipsis = enum.auto() # ...
Assign = enum.auto() # =
# 保留字 Token。
class TokenReserved(Token):
def __init__(self, init: ReservedWord):
self.value = init
# 数字 Token。
class TokenNumber(Token):
def __init__(self, init: float):
self.value = init
# 字符串 Token。
class TokenString(Token):
def __init__(self, init: str):
self.value = init
# 符号 Token。
class TokenSymbol(Token):
def __init__(self, init: Symbol):
self.value = init
# 名称 Token。
class TokenName(Token):
def __init__(self, init: str):
self.value = init
# 注释 Token。
class TokenComment(Token):
pass
# 行尾 Token。
class TokenEOL(Token):
pass
# 文件尾 Token。
class TokenEOF(Token):
pass
# 词法分析器。
class Lexer:
# 保留字列表。
reserved_words = {
"and": ReservedWord.And,
"break": ReservedWord.Break,
"do": ReservedWord.Do,
"else": ReservedWord.Else,
"elseif": ReservedWord.ElseIf,
"end": ReservedWord.End,
"false": ReservedWord.False_,
"for": ReservedWord.For,
"function": ReservedWord.Function,
"if": ReservedWord.If,
"in": ReservedWord.In,
"local": ReservedWord.Local,
"nil": ReservedWord.Nil,
"not": ReservedWord.Not,
"or": ReservedWord.Or,
"repeat": ReservedWord.Repeat,
"return": ReservedWord.Return,
"then": ReservedWord.Then,
"true": ReservedWord.True_,
"until": ReservedWord.Until,
"while": ReservedWord.While,
}
# 构造函数。
def __init__(self, source: str):
self.source = source # 源代码。
self.token_list: list[Token] = [] # Token 列表。
self.current = 0 # 扫描指针。
self.start = 0 # 起始指针。
# 扫描 Token 列表。
def scan_tokens(self):
while not self.is_at_end(): # 持续扫描。
token = self.scan_token() # 扫描单个 Token。
if not isinstance(token, TokenComment): # 忽略注释 Token。
word = self.extract_word() # 题目要求输出 Token 对应的源代码原始表示。因此在对齐指针前,提取源代码。
# 获取 Token 类型字符串。
match token:
case TokenReserved():
token_type = "[RESERVED]"
case TokenNumber():
token_type = "[NUMBER]"
case TokenString():
token_type = "[STRING]"
case TokenSymbol():
token_type = "[SYMBOL]"
case TokenName():
token_type = "[NAME]"
case TokenEOL():
token_type = "[EOL]"
case TokenComment():
raise RuntimeError("Unexpected Comment token.") # 不可达代码。
case TokenEOF():
raise RuntimeError("Unexpected EOF token.")
case _:
raise RuntimeError("Unknown token type.")
print(f"{token_type}", end="")
if isinstance(token, TokenEOL):
print()
else:
print(f" {word}")
self.token_list.append(token) # 加入
self.token_list.append(TokenEOF()) # 人工手动加入文件尾 Token。
# 扫描单个 Token。
def scan_token(self) -> Token:
self.skip_whitespace() # 先跳过空白符。
self.align_pointer() # 再对齐指针。
match self.advance():
case "\n": # 换行符解析为行尾 Token。
return TokenEOL()
case "+":
return TokenSymbol(Symbol.Add)
case "-":
if self.match_char("-"): # 贪心匹配。
self.scan_comment() # 扫描注释。
return TokenComment()
else:
return TokenSymbol(Symbol.Minus)
case "*":
return TokenSymbol(Symbol.Multiply)
case "/":
return TokenSymbol(Symbol.Divide)
case "%":
return TokenSymbol(Symbol.Mod)
case "^":
return TokenSymbol(Symbol.Power)
case "#":
return TokenSymbol(Symbol.Length)
case "=":
if self.match_char("="):
return TokenSymbol(Symbol.Equal)
else:
return TokenSymbol(Symbol.Assign)
case ">":
if self.match_char("="):
return TokenSymbol(Symbol.GreaterEqual)
else:
return TokenSymbol(Symbol.Greater)
case "<":
if self.match_char("="):
return TokenSymbol(Symbol.LessEqual)
else:
return TokenSymbol(Symbol.Less)
case "~":
if self.match_char("="):
return TokenSymbol(Symbol.NotEqual)
else:
raise RuntimeError("Invalid token.")
case "(":
return TokenSymbol(Symbol.LeftParen)
case ")":
return TokenSymbol(Symbol.RightParen)
case "{":
return TokenSymbol(Symbol.LeftBrace)
case "}":
return TokenSymbol(Symbol.RightBrace)
case "[":
return TokenSymbol(Symbol.LeftBracket)
case "]":
return TokenSymbol(Symbol.RightBracket)
case ";":
return TokenSymbol(Symbol.Semicolon)
case ":":
return TokenSymbol(Symbol.Colon)
case ",":
return TokenSymbol(Symbol.Comma)
case ".":
if self.peek().isdigit(): # 省略整数的数字 Token。
return self.scan_number()
elif self.match_char("."):
if self.match_char("."):
return TokenSymbol(Symbol.Ellipsis)
else:
return TokenSymbol(Symbol.Concat)
else:
return TokenSymbol(Symbol.Dot)
case "\"" | "'":
return self.scan_string()
case _:
ch = self.previous()
if ch.isdigit():
return self.scan_number()
elif self.is_name_char(ch, True):
return self.scan_name()
else:
raise RuntimeError("Invalid token.")
# 扫描注释。
def scan_comment(self):
while self.peek() != "\n": # 不要扫描换行符!
self.advance()
# 扫描数字 Token。
def scan_number(self) -> TokenNumber:
hex = False # 十六进制。
floating = False # 浮点数。
science = False # 科学记数法。
if self.previous() == "0" and (self.match_char("x") or self.match_char("X")): # 检查十六进制。注意短路求值,不会出现误判如 0xX 的情况。
hex = True
if self.previous() == ".": # 省略整数部分的浮点数。
floating = True
signed_power = False # 科学记数法中指数部分已经扫描符号。
number_power = False # 科学记数法中指数部分已经扫描数字。
while True:
ch = self.peek()
if ch.isdigit():
if science:
number_power = True
self.advance()
elif not hex and (ch == 'e' or ch == 'E'): # 在十六进制整数中,字母 e 和 E 应该被视作数位。
floating = True
science = True
self.advance()
elif ch.lower() in "abcdef":
if hex:
self.advance()
else:
raise RuntimeError("Invalid number.") # 不可达代码。
elif ch == ".":
if hex or floating:
raise RuntimeError("Invalid number.")
else:
self.advance()
floating = True
elif (ch == "-" or ch == "+") and science and not signed_power and not number_power:
signed_power = True
self.advance()
else:
break
word = self.extract_word() # 提取数字源代码。
# Python 的内置函数可以正确转换这种格式的数字。
if floating:
return TokenNumber(float(word))
else:
# 二进制级别的高精整数!好耶!不需要考虑负数,负号会被单独解析为一个符号。
if hex:
return TokenNumber(int(word[2:], 16))
else:
return TokenNumber(int(word))
# 扫描字符串 Token。
def scan_string(self) -> TokenString:
str_tag = self.previous() # 引号类型
string = ""
while self.peek() != str_tag:
if self.match_char("\\"): # 转义符。
string += self.parse_escape()
else:
string += self.advance()
self.advance() # 消耗末尾引号。
return TokenString(string)
# 扫描名称 Token。
def scan_name(self) -> Token:
while self.is_name_char(self.peek(), False):
self.advance()
word = self.extract_word()
if word in self.reserved_words:
return TokenReserved(self.reserved_words[word])
else:
return TokenName(word)
# 解析转义字符。
def parse_escape(self) -> str:
match self.advance():
case "\\":
return "\\"
case "n":
return "\n"
case "'":
return "'"
case "\"":
return "\""
case _:
raise RuntimeError("Invalid escape char.")
# 提取源代码。
def extract_word(self) -> str:
return self.source[self.start:self.current]
# 跳过空白符。
def skip_whitespace(self):
while self.peek() != "\n" and self.peek().isspace():
self.advance()
# 对齐指针。
def align_pointer(self):
self.start = self.current
# 判断是否是合法的名称字符。
@staticmethod # 静态方法
def is_name_char(ch: str, start: bool) -> bool:
if start and (ch.isalpha() or ch == "_"):
return True
elif ch.isalnum() or ch == "_":
return True
else:
return False
# 是否扫描到源代码末尾。
def is_at_end(self) -> bool:
return self.current >= len(self.source)
# 消耗并返回下一个要被扫描的字符。
def advance(self) -> str:
if self.is_at_end():
return "\0"
else:
self.current += 1
return self.source[self.current - 1]
# 返回最后被扫描过了的字符。
def previous(self) -> str:
if self.current == 0:
return "\0"
else:
return self.source[self.current - 1]
# 探视下一个即将要被扫描的字符。
def peek(self) -> str:
if self.is_at_end():
return "\0"
else:
return self.source[self.current]
# 探视下一个字符,若匹配,则消耗。
def match_char(self, target: str) -> bool:
if self.is_at_end():
return False
else:
if self.peek() == target:
self.advance()
return True
else:
return False
# 程序入口点。
if __name__ == "__main__":
main()拓展:开发中的错误处理
可怕的错误处理!
想看的点开看看吧!
拓展:开发中的错误处理
前面提到,编译器中的错误处理是非常繁琐的。为了正确地检测错误并提供友好的报错信息,你还需要保存各种位置信息。
以下代码皆为截止至 2026 年 2 月 9 日的版本。新版本可能有修改。
下面是我在 CSharpLoxinas(Loxinas 的 C# 语言实现)项目中的代码片段:
using System.Text;
namespace Information;
/// <summary>
/// 一段位置(<c>End.Idx</c> 是超尾位置)。
/// </summary>
/// <param name="Start">起始点。</param>
/// <param name="End">终止点,为超尾位置。</param>
public record struct Location(Position Start, Position End) {
public override readonly string ToString() {
var builder = new StringBuilder($"[line {Start.Line}");
if (End.Line != Start.Line) {
builder.Append($"-{End.Line}");
}
builder.Append($" at {Start.Idx + 1}");
if (End.Idx - 1 != Start.Idx) {
builder.Append($"-{End.Idx}");
}
builder.Append(']');
return builder.ToString();
}
/// <summary>
/// 合并两段位置。取左右两端点合并。
/// </summary>
/// <param name="start">起始位置</param>
/// <param name="end">终止位置。</param>
/// <returns>合并后的位置。</returns>
public static Location Combine(Location start, Location end) => new(start.Start, end.End);
}
/// <summary>
/// 单点位置。
/// </summary>
/// <param name="Line">行号,1-based。</param>
/// <param name="Idx">于当前行的位置,0-based。</param>
public record struct Position(int Line, int Idx) {
public override readonly string ToString() => $"[line {Line} at {Idx + 1}]";
}
这就是最基本的位置信息的存储方式。
而使用位置信息也很繁杂。例如,这是 CSharpLoxinas 中一小段表示 Token 的代码(其中还包含一些调试用的调试信息):
using System.Diagnostics;
using System.Text;
using Information;
namespace Compiler;
/// <summary>
/// 词素。
/// </summary>
/// <param name="Location">位置信息。</param>
public record Token(Location Location);
/// <summary>
/// EOF 词素,表示文件尾。
/// </summary>
/// <param name="Location">位置信息(超尾位置)。</param>
public record TokenEOF(Location Location) : Token(Location);
/// <summary>
/// 操作符词素。
/// </summary>
/// <param name="Location">位置信息。</param>
/// <param name="Operator">操作符。</param>
public record TokenOperator(Location Location, Operator Operator) : Token(Location);
/// <summary>
/// 标识符词素。
/// </summary>
/// <param name="Location">位置信息。</param>
/// <param name="Name">标识符名称。</param>
public record TokenIdentifier(Location Location, string Name) : Token(Location);
/// <summary>
/// 关键字词素。
/// </summary>
/// <param name="Location">位置信息。</param>
/// <param name="Keyword">关键字。</param>
public record TokenKeyword(Location Location, Keyword Keyword) : Token(Location);
/// <summary>
/// 数字词素。
/// </summary>
/// <param name="Location">位置信息。</param>
/// <param name="Value"数值</param>
public record TokenNumber(Location Location, IValue Value) : Token(Location);
#if DEBUG
/// <summary>
/// 为词素添加调试信息。
/// </summary>
public static class TokenExtensionsDebug {
/// <summary>
/// 获取词素的调试信息。
/// </summary>
/// <param name="token">词素。</param>
/// <returns>调试信息的字符串表示。</returns>
/// <exception cref="UnreachableException"></exception>
public static string DebugInfo(this Token token) => token switch {
TokenEOF tokenEOF => PackInfo("EOF", GetInfo(tokenEOF)),
TokenOperator tokenOperator => PackInfo("Operator", GetInfo(tokenOperator)),
TokenIdentifier tokenIdentifier => PackInfo("Identifier", GetInfo(tokenIdentifier)),
TokenKeyword tokenKeyword => PackInfo("Keyword", GetInfo(tokenKeyword)),
TokenNumber tokenNumber => PackInfo("Number", GetInfo(tokenNumber)),
_ => throw new UnreachableException(),
};
/// <summary>
/// 包装词素信息(格式化)。
/// </summary>
/// <param name="name">词素名称。</param>
/// <param name="infoList">词素信息。</param>
/// <returns>包装后的字符串。</returns>
private static string PackInfo(string name, List<string> infoList) {
var builder = new StringBuilder($"Token [{name}] => {{");
foreach (string info in infoList) {
builder.Append($"\n {info}");
}
builder.Append("\n}");
return builder.ToString();
}
/// <summary>
/// 获取 EOF 词素信息。
/// </summary>
/// <param name="token">EOF 词素。</param>
/// <returns>词素信息。</returns>
private static List<string> GetInfo(TokenEOF token) {
List<string> info = [];
info.Add($"Location: {token.Location}");
return info;
}
/// <summary>
/// 获取操作符词素信息。
/// </summary>
/// <param name="token">操作符词素。</param>
/// <returns>词素信息。</returns>
private static List<string> GetInfo(TokenOperator token) {
List<string> info = [];
info.Add($"Location: {token.Location}");
info.Add($"Operator: {token.Operator.DebugInfo()}");
return info;
}
/// <summary>
/// 获取标识符词素信息。
/// </summary>
/// <param name="token">标识符词素。</param>
/// <returns>词素信息。</returns>
private static List<string> GetInfo(TokenIdentifier token) {
List<string> info = [];
info.Add($"Location: {token.Location}");
info.Add($"Name: {token.Name}");
return info;
}
/// <summary>
/// 获取关键字词素信息。
/// </summary>
/// <param name="token">关键字词素。</param>
/// <returns>词素信息。</returns>
private static List<string> GetInfo(TokenKeyword token) {
List<string> info = [];
info.Add($"Location: {token.Location}");
info.Add($"Keyword: {token.Keyword.DebugInfo()}");
return info;
}
/// <summary>
/// 获取数字词素信息。
/// </summary>
/// <param name="token">数字词素。</param>
/// <returns>词素信息。</returns>
private static List<string> GetInfo(TokenNumber token) {
List<string> info = [];
info.Add($"Location: {token.Location}");
info.Add($"Value: {token.Value.DebugInfo()}");
return info;
}
}
#endif
在词法扫描器中则有这一段,其中有存储位置信息的字段(你还能看到如何通过词法扫描器是如何给语法解析器提供按需调用的接口的):
/// <summary>
/// 词法扫描器。
/// </summary>
public partial class Lexer {
/// <summary>
/// 正在扫描的词素类型。
/// </summary>
private enum ScanningType {
/// <summary>
/// 最普通的类型。
/// </summary>
None,
/// <summary>
/// 名称类型,标识符或关键字。
/// </summary>
Identifier,
/// <summary>
/// 数值类型。
/// </summary>
Number,
}
/// <summary>
/// 源代码。
/// </summary>
private readonly string source;
/// <summary>
/// 源代码超尾位置。
/// </summary>
private readonly Location endLocation;
/// <summary>
/// 统一生成的 EOF 词素。
/// </summary>
private readonly TokenEOF tokenEOF;
/// <summary>
/// 词素扫描起始点,相对于整个源代码字符串。
/// </summary>
private int startIdx = 0;
/// <summary>
/// 即将扫描的字符位置,相对于整个源代码字符串。
/// </summary>
private int currentIdx = 0;
/// <summary>
/// 词素起始位置。
/// </summary>
private Position startPos = new(1, 0);
/// <summary>
/// 词素终止位置。
/// </summary>
private Position endPos = new(1, 0);
/// <summary>
/// 前一个已经扫描过的词素。
/// </summary>
private Token previous;
/// <summary>
/// 即将扫描的词素。
/// </summary>
private Token current;
/// <summary>
/// 正在扫描的词素类型。
/// </summary>
private ScanningType scanningType = ScanningType.None;
// 后续省略
}
加上位置信息的词法扫描器将这样处理位置信息:
using Information;
namespace Compiler;
/// <summary>
/// 词法扫描器。
/// </summary>
public partial class Lexer {
/// <summary>
/// 判断是否为标识符起始字符。
/// </summary>
/// <param name="ch">字符</param>
/// <returns>是/否。</returns>
private static bool IsIdentifierBeginChar(char ch) => char.IsLetter(ch) || ch == '_';
/// <summary>
/// 判断是否为标识符字符。
/// </summary>
/// <param name="ch">字符</param>
/// <returns>是/否。</returns>
private static bool IsIdentifierChar(char ch) => char.IsLetterOrDigit(ch) || ch == '_';
/// <summary>
/// 获取当前词素的位置信息。
/// </summary>
/// <returns>当前词素的位置信息。</returns>
private Location CurrentLocation() => new(startPos, endPos);
/// <summary>
/// 刷新词素。此方法会重置词素的起始位置信息,对齐到当前扫描位置。
/// </summary>
private void Fresh() {
scanningType = ScanningType.None;
startIdx = currentIdx;
startPos = endPos;
}
/// <summary>
/// 遇到换行符的位置信息更新。
/// </summary>
private void NewLine() {
endPos.Line++;
endPos.Idx = 0;
}
/// <summary>
/// 消耗字符。
/// </summary>
/// <returns>消耗的字符。若已到结尾则返回空字符。</returns>
private char AdvanceChar() {
if (AtEnd()) {
return '\0';
}
currentIdx++;
endPos.Idx++;
return source[currentIdx - 1];
}
/// <summary>
/// 获取下一个即将扫描的字符。
/// </summary>
/// <returns>即将扫描的字符。若已到结尾则返回空字符。</returns>
private char PeekChar() {
if (AtEnd()) {
return '\0';
}
return source[currentIdx];
}
/// <summary>
/// 获取前一个已经被扫描过的字符。
/// </summary>
/// <returns>前一个字符。若没有扫描过字符,则返回空字符。</returns>
private char PreviousChar() {
if (currentIdx == 0) {
return '\0';
}
return source[currentIdx - 1];
}
/// <summary>
/// 匹配消耗字符。若下一个字符与目标匹配,则消耗;若不匹配,则不做任何事情。
/// </summary>
/// <param name="target">目标字符。</param>
/// <returns>是否匹配。</returns>
private bool MatchChar(char target) {
if (PeekChar() == target) {
AdvanceChar();
return true;
} else {
return false;
}
}
/// <summary>
/// 判断是否扫描到源代码结尾。
/// </summary>
/// <returns>是/否。</returns>
private bool AtEnd() => currentIdx == source.Length;
}
错误处理器则是更为复杂:
using CLI;
using Information;
namespace Error;
/// <summary>
/// 错误处理器。
/// </summary>
public static class ErrorHandler {
/// <summary>
/// 打印错误。
/// </summary>
/// <param name="error">Loxinas 错误。</param>
public static void PrintError(LoxinasError error) {
if (Program.LogFile is null) {
Console.ForegroundColor = ConsoleColor.Red;
}
switch (error) {
case ProgramError programError:
PrintProgramError(programError);
break;
case CompileError compileError:
PrintCompileError(compileError);
break;
case DisassembleError disassembleError:
PrintDisassembleError(disassembleError);
break;
}
if (Program.LogFile is null) {
Console.ResetColor();
}
}
/// <summary>
/// 打印 Loxinas 编译器程序错误。
/// </summary>
/// <param name="error">程序错误。</param>
private static void PrintProgramError(ProgramError error) => PrintNamedError("Program Error", error);
/// <summary>
/// 打印 Loxinas 编译错误。
/// </summary>
/// <param name="error">编译错误。</param>
private static void PrintCompileError(CompileError error) {
if (Program.LogFile is null) {
Console.WriteLine(error.Location);
} else {
Program.LogFile.WriteLine(error.Location);
}
PrintLocationSource(Program.sourceLines, error.Location);
PrintNamedError("Compile Error", error);
}
/// <summary>
/// 打印 Loxinas 反汇编错误。
/// </summary>
/// <param name="error">反汇编错误。</param>
private static void PrintDisassembleError(DisassembleError error) => PrintNamedError("Disassemble Error", error);
/// <summary>
/// 打印带名称的 Loxinas 错误。
/// </summary>
/// <param name="name">名称。</param>
/// <param name="error">Loxinas 错误。</param>
private static void PrintNamedError(string name, LoxinasError error) => Logging.LogError($"{name}: {error.Message}");
/// <summary>
/// 打印位置信息的源代码提示。
/// </summary>
/// <param name="sourceLines">源代码行。</param>
/// <param name="location">位置信息。</param>
private static void PrintLocationSource(string[] sourceLines, Location location) {
string firstLine = sourceLines[location.Start.Line - 1];
string output = $"|> {firstLine}";
if (Program.LogFile is null) {
Console.WriteLine(output);
} else {
Program.LogFile.WriteLine(output);
}
if (location.End.Line == location.Start.Line) {
string spaces = new(' ', location.Start.Idx);
string arrows = new('^', location.End.Idx - location.Start.Idx);
output = $"|> {spaces}{arrows}";
if (Program.LogFile is null) {
Console.WriteLine(output);
} else {
Program.LogFile.WriteLine(output);
}
} else {
string firstLineSpaces = new(' ', location.Start.Idx);
string firstLineArrows = new('^', firstLine.Length - location.Start.Idx);
output = $"|> {firstLineSpaces}{firstLineArrows}";
if (Program.LogFile is null) {
Console.WriteLine(output);
} else {
Program.LogFile.WriteLine(output);
}
if (location.End.Line - location.Start.Line > 1) { // 注意超尾位置(左闭右开)。
output = $"|> ...";
if (Program.LogFile is null) {
Console.WriteLine(output);
} else {
Program.LogFile.WriteLine(output);
}
}
string lastLine = sourceLines[location.End.Line - 1];
output = $"|> {lastLine}";
if (Program.LogFile is null) {
Console.WriteLine(output);
} else {
Program.LogFile.WriteLine(output);
}
string lastLineArrows = new('^', location.End.Idx - 1);
output = $"|> {lastLineArrows}";
if (Program.LogFile is null) {
Console.WriteLine(output);
} else {
Program.LogFile.WriteLine(output);
}
}
}
}
而 CSharpLoxinas 项目也只是我个人的业余项目,Loxinas 也只是学习用的兴趣编程语言,肯定用不上很多高级的技术和特性,我可能也受限于个人能力和教育环境而无法实现很多高级功能。不过仅仅是一个简单的编译器,就已经开始变得错综复杂。
Mua 系列的题目,已经是最简单的解释器了。
编译原理的世界,无比广阔。