Kaleidoscope:Parser 与 AST
Kaleidoscope:Parser 与 AST
本章使用第 1 章构建的 lexer,为 Kaleidoscope 构建完整的 parser,并定义 Abstract Syntax Tree(AST)。
TL;DR
- Kaleidoscope 的 parser 结合使用 Recursive Descent Parsing 和 Operator-Precedence Parsing。
- AST 用对象表达语言结构,让后续 compiler stages(例如 code generation)不必关心具体 syntax。
CurTok提供一个简单的 token buffer,使 parser 可以进行 one-token look-ahead。- 二元表达式通过 operator precedence 和递归处理结合方向,例如将
x+y*z解析为x+(y*z)。 - 本章结束后,Kaleidoscope 已经具备 lexer、parser 和 AST builder,可以检查代码是否符合 grammar。
目录
| 章节 | 说明 |
|---|---|
| 本章简介 | parser 的目标和解析策略 |
| Abstract Syntax Tree | AST 节点设计 |
| Parser 基础 | token buffer 与错误处理 |
| 基础表达式解析 | number、括号、变量和函数调用 |
| 二元表达式解析 | operator precedence parsing |
| 其余部分的解析 | prototype、definition、extern 和顶层表达式 |
| Driver | 顶层 dispatch loop |
| 结论 | parser 的结果与下一章 |
| 完整代码清单 | 可编译运行的完整示例 |
本章简介
欢迎来到“使用 LLVM 实现一门语言”教程的第 2 章。本章将展示如何使用第 1 章构建的 lexer,为 Kaleidoscope language 构建一个完整的 parser。有了 parser 之后,我们会定义并构建一个 Abstract Syntax Tree(AST)。
我们构建的 parser 会结合使用 Recursive Descent Parsing 和 Operator-Precedence Parsing 来解析 Kaleidoscope language:前者用于二元表达式,后者用于其余部分。在开始 parsing 之前,我们先讨论 parser 的输出:Abstract Syntax Tree。
Abstract Syntax Tree(AST)
程序的 AST 应当以一种方便 compiler 后续 stages(例如 code generation)解释的方式捕获程序行为。基本上,我们希望语言中的每一种 construct 都对应一个 object,并且 AST 能够紧密地模拟这门语言。在 Kaleidoscope 中,我们有 expressions、prototype 和 function object。先从 expressions 开始:
/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
virtual ~ExprAST() = default;
};
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double Val) : Val(Val) {}
};
上面的代码定义了 ExprAST base class,以及一个用于 numeric literals 的 subclass。需要注意的是,NumberExprAST class 将 literal 的 numeric value 保存为 instance variable。这样,compiler 的后续 phases 就可以知道这里保存的 numeric value。
目前我们只创建 AST,因此节点还没有有用的 accessor methods。例如,添加一个用于 pretty-print code 的 virtual method 会非常容易。下面是 basic Kaleidoscope language 中其他 expression AST node 的定义:
/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
std::string Name;
public:
VariableExprAST(const std::string &Name) : Name(Name) {}
};
/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
char Op;
std::unique_ptr<ExprAST> LHS, RHS;
public:
BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
std::unique_ptr<ExprAST> RHS)
: Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
};
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<std::unique_ptr<ExprAST>> Args;
public:
CallExprAST(const std::string &Callee,
std::vector<std::unique_ptr<ExprAST>> Args)
: Callee(Callee), Args(std::move(Args)) {}
};
这些定义都很直接:variables 保存 variable name,binary operators 保存它们的 opcode(例如 +),calls 保存 function name 以及所有 argument expressions 的列表。AST 的一个优点是,它表达了 language features,却不涉及 language syntax。注意,这里没有讨论 binary operators 的 precedence、lexical structure 等内容。
对于 basic language,这些就是我们定义的全部 expression nodes。由于它没有 conditional control flow,因此还不是 Turing-complete;我们会在后续文章中修复这一点。接下来需要定义两种东西:描述 function interface 的方式,以及 function 本身:
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
std::string Name;
std::vector<std::string> Args;
public:
PrototypeAST(const std::string &Name, std::vector<std::string> Args)
: Name(Name), Args(std::move(Args)) {}
const std::string &getName() const { return Name; }
};
/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
std::unique_ptr<PrototypeAST> Proto;
std::unique_ptr<ExprAST> Body;
public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,
std::unique_ptr<ExprAST> Body)
: Proto(std::move(Proto)), Body(std::move(Body)) {}
};
在 Kaleidoscope 中,function 只通过 argument 的数量来确定类型。由于所有值都是 double precision floating point,因此不需要保存每个 argument 的类型。在一门更复杂、更真实的语言中,ExprAST class 很可能还需要一个 type field。
有了这些 scaffolding,我们现在可以讨论如何解析 Kaleidoscope 中的 expressions 和 function bodies。
Parser 基础
现在我们已经有了需要构建的 AST,接下来需要定义用于构建它的 parser code。这里的目标是把 lexer 返回的三个 tokens——例如 x+y——解析成类似下面这样通过调用构造出来的 AST:
auto LHS = std::make_unique<VariableExprAST>("x");
auto RHS = std::make_unique<VariableExprAST>("y");
auto Result = std::make_unique<BinaryExprAST>('+', std::move(LHS),
std::move(RHS));
为此,我们先定义一些基本的 helper routines:
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
/// token the parser is looking at. getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() {
return CurTok = gettok();
}
这段代码在 lexer 外围实现了一个简单的 token buffer。它允许我们 look ahead 一个 token,查看 lexer 将要返回什么。parser 中的每个 function 都会假设 CurTok 是当前需要解析的 token。
/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
fprintf(stderr, "Error: %s\n", Str);
return nullptr;
}
std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
LogError(Str);
return nullptr;
}
LogError routines 是 parser 用来处理 errors 的简单 helper。这里的 error recovery 不会特别完善,也不算很 user-friendly,但对本教程已经足够。这些 routines 让不同返回类型的 parsing routines 更容易处理错误:它们始终返回 null。
基础表达式解析
我们从 numeric literals 开始,因为它们最容易处理。对于 grammar 中的每一个 production,我们都会定义一个解析该 production 的 function。numeric literals 的 production 是:
/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
getNextToken(); // consume the number
return std::move(Result);
}
这个 routine 很简单:它要求调用时当前 token 是 tok_number,读取当前 number value,创建一个 NumberExprAST node,将 lexer 前进到下一个 token,最后返回。
这里有一个值得注意的地方:这个 routine 会吃掉与 production 对应的所有 tokens,并让 lexer buffer 停留在下一个 token 上——这个 token 不属于当前 grammar production。对于 recursive descent parser,这是一种相当标准的做法。括号 operator 的解析是一个更好的例子:
/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
getNextToken(); // eat (.
auto V = ParseExpression();
if (!V)
return nullptr;
if (CurTok != ')')
return LogError("expected ')'");
getNextToken(); // eat ).
return V;
}
这个 function 展示了 parser 的几个重要特性:
- 它展示了如何使用
LogErrorroutines。调用时当前 token 应该是(,但 subexpression 解析完成后,当前位置可能没有)。例如用户输入(4 x而不是(4)时,parser 应当报告 error。因为可能发生 errors,parser 需要一种表示错误的方式;在这里,我们在出错时返回 null。 - 这个 function 通过调用
ParseExpression使用 recursion(稍后会看到,ParseExpression也可以调用ParseParenExpr)。这很强大,因为它允许我们处理 recursive grammars,并让每个 production 保持简单。注意,括号本身不会导致 AST node 的构建。虽然也可以这样设计,但括号最重要的作用是引导 parser 并提供 grouping。一旦 parser 构建出 AST,括号就不再需要了。
下一个简单的 production 用于处理 variable references 和 function calls:
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
getNextToken(); // eat identifier.
if (CurTok != '(') // Simple variable ref.
return std::make_unique<VariableExprAST>(IdName);
// Call.
getNextToken(); // eat (
std::vector<std::unique_ptr<ExprAST>> Args;
if (CurTok != ')') {
while (true) {
if (auto Arg = ParseExpression())
Args.push_back(std::move(Arg));
else
return nullptr;
if (CurTok == ')')
break;
if (CurTok != ',')
return LogError("Expected ')' or ',' in argument list");
getNextToken();
}
}
// Eat the ')'.
getNextToken();
return std::make_unique<CallExprAST>(IdName, std::move(Args));
}
这个 routine 与前面的 routines 遵循相同风格(它要求调用时当前 token 是 tok_identifier)。它同样使用 recursion 和 error handling。这里有一个有趣之处:它使用 look-ahead 来判断当前 identifier 是一个独立的 variable reference,还是一个 function call expression。
具体做法是检查 identifier 后面的 token 是否为 (,然后根据情况构造 VariableExprAST 或 CallExprAST node。
现在,基础的 expression-parsing logic 已经完成,我们可以定义一个 helper function,把它们包装到同一个 entry point 中。我们把这类 expressions 称为 “primary” expressions;这个名称的原因会在教程后面变得更加清楚。要解析任意的 primary expression,我们需要先判断它属于哪一种:
/// primary
/// ::= identifierexpr
/// ::= numberexpr
/// ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
switch (CurTok) {
default:
return LogError("unknown token when expecting an expression");
case tok_identifier:
return ParseIdentifierExpr();
case tok_number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
}
}
看到这个 function 的定义后,CurTok 在各个 functions 中的状态假设就更清楚了。这里使用 look-ahead 确定当前正在检查哪一种 expression,然后通过 function call 对它进行解析。
二元表达式解析
二元表达式明显更难解析,因为它们经常存在歧义。例如给定字符串 x+y*z,parser 可以把它解析为 (x+y)*z,也可以解析为 x+(y*z)。按照数学中的常见定义,我们期待后一种解析结果,因为 *(乘法)的 precedence 高于 +(加法)。
有很多方式可以处理这个问题,但一种优雅且高效的方式是使用 Operator-Precedence Parsing。这种 parsing technique 使用 binary operators 的 precedence 来引导 recursion。首先,我们需要一个 precedence table:
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
if (!isascii(CurTok))
return -1;
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0) return -1;
return TokPrec;
}
int main() {
// Install standard binary operators.
// 1 is lowest precedence.
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 20;
BinopPrecedence['*'] = 40; // highest.
...
}
在 Kaleidoscope 的 basic form 中,我们只支持 4 个 binary operators(当然,勇敢而无畏的读者可以自行扩展)。GetTokPrecedence 返回当前 token 的 precedence;如果当前 token 不是 binary operator,则返回 -1。
使用 map 可以很容易地添加新 operators,也能清楚地表明算法并不依赖具体 operator。你也可以直接把 map 去掉,将 comparisons 放进 GetTokPrecedence(或者直接使用 fixed-size array)。
定义了 helper 后,现在可以开始解析 binary expressions。operator precedence parsing 的基本思想,是把一条可能含有歧义的 binary-operator expression 拆成若干部分。例如,对于 a+b+(c+d)*e*f+g,operator precedence parsing 会把它视为由 binary operators 分隔的一串 primary expressions。它首先解析开头的 primary expression a,然后看到这些 pairs:[+, b]、[+, (c+d)]、[*, e]、[*, f] 和 [+, g]。
注意,由于括号表达式属于 primary expressions,binary expression parser 完全不需要操心 (c+d) 这样的嵌套 subexpressions。
开始时,一个 expression 是一个 primary expression,后面可能跟着一串 [binop, primaryexpr] pairs:
/// expression
/// ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParsePrimary();
if (!LHS)
return nullptr;
return ParseBinOpRHS(0, std::move(LHS));
}
ParseBinOpRHS 负责解析这一串 pairs。它接收一个 precedence,以及一个指向目前已经解析部分的 expression 的 pointer。注意,x 本身就是一个完全有效的 expression。因此,binoprhs 可以为空,此时 function 会返回传入的 expression。在前面的例子中,代码会将 a 对应的 expression 传入 ParseBinOpRHS,而当前 token 是 +。
传给 ParseBinOpRHS 的 precedence 表示该 function 允许吃掉的最小 operator precedence。例如,当前 pair stream 是 [+, x],而传入的 precedence 是 40,那么它不会消费任何 token,因为 + 的 precedence 只有 20。基于这一点,ParseBinOpRHS 从下面开始:
/// binoprhs
/// ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
std::unique_ptr<ExprAST> LHS) {
// If this is a binop, find its precedence.
while (true) {
int TokPrec = GetTokPrecedence();
// If this is a binop that binds at least as tightly as the current binop,
// consume it, otherwise we are done.
if (TokPrec < ExprPrec)
return LHS;
这段代码取得当前 token 的 precedence,并检查它是否过低。由于我们把 invalid tokens 的 precedence 定义为 -1,因此这里的检查隐含地知道:当 token stream 中没有 binary operators 时,pair-stream 就结束了。如果检查通过,我们就知道当前 token 是 binary operator,并且它将被包含在当前 expression 中:
// Okay, we know this is a binop.
int BinOp = CurTok;
getNextToken(); // eat binop
// Parse the primary expression after the binary operator.
auto RHS = ParsePrimary();
if (!RHS)
return nullptr;
因此,这段代码会吃掉并记住 binary operator,然后解析它后面的 primary expression。这就构成了整个 pair;在当前示例中,第一个 pair 是 [+, b]。
解析完 expression 的 left-hand side 和 RHS sequence 中的一个 pair 后,我们还需要决定 expression 应该如何结合。具体来说,可能是 (a+b) binop unparsed,也可能是 a + (b binop unparsed)。要确定这一点,我们 look ahead 查看 binop 的 precedence,并把它与 BinOp(当前例子中是 +)的 precedence 比较:
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
如果 RHS 右侧的 binop precedence 小于或等于当前 operator 的 precedence,那么括号结合方式就是 (a+b) binop …。当前 operator 和下一个 operator 都是 + 时,它们的 precedence 相同。此时,我们会创建 a+b 对应的 AST node,然后继续解析:
... if body omitted ...
}
// Merge LHS/RHS.
LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
std::move(RHS));
} // loop around to the top of the while loop.
}
在前面的例子中,这会把 a+b+ 变成 (a+b),并进入下一次循环;此时当前 token 是 +。上面的代码会吃掉、记住并解析 (c+d) 作为 primary expression,使当前 pair 变成 [+, (c+d)]。然后它会使用右侧的 * 作为 binop 来计算上面的 if 条件。由于 * 的 precedence 高于 +,因此会进入该条件分支。
剩下的关键问题是:“这个 if 条件如何完整解析 RHS?”为了正确构建示例中的 AST,它需要把 (c+d)*e*f 全部作为 RHS expression variable。实现这一点的代码非常简单(下面的代码复制了前面两个代码块的上下文):
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec+1, std::move(RHS));
if (!RHS)
return nullptr;
}
// Merge LHS/RHS.
LHS = std::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
std::move(RHS));
} // loop around to the top of the while loop.
}
此时,我们知道 primary 右侧的 binary operator precedence 高于当前正在解析的 binop。因此,所有 precedence 都高于 + 的 pair sequence 都应该被一起解析,并作为 RHS 返回。为此,我们递归调用 ParseBinOpRHS,并指定 TokPrec+1 作为它继续处理所需的最小 precedence。
在当前示例中,这会使它返回 (c+d)*e*f 对应的 AST node,并将其设置为 + expression 的 RHS。
最后,在 while loop 的下一次迭代中,会解析并添加 +g 部分。仅用这段代码中 14 行非平凡代码,我们就能正确处理完全通用的 binary expression parsing,而且实现非常优雅。这是对代码的一次快速浏览,其中有一些细节比较微妙。我建议使用一些复杂的示例运行它,完整走一遍过程。
至此,expressions 的处理完成了。现在,我们可以让 parser 面对任意 token stream,构建出一个 expression,并在遇到第一个不属于该 expression 的 token 时停止。接下来需要处理 function definitions 等内容。
其余部分的解析
下一项缺失的能力是处理 function prototypes。在 Kaleidoscope 中,prototype 既用于 extern function declarations,也用于 function body definitions。完成 expression parsing 后,这部分代码就很直接,也没有太多有趣之处:
/// prototype
/// ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
if (CurTok != tok_identifier)
return LogErrorP("Expected function name in prototype");
std::string FnName = IdentifierStr;
getNextToken();
if (CurTok != '(')
return LogErrorP("Expected '(' in prototype");
// Read the list of argument names.
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier)
ArgNames.push_back(IdentifierStr);
if (CurTok != ')')
return LogErrorP("Expected ')' in prototype");
// success.
getNextToken(); // eat ')'.
return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}
有了它,function definition 就很简单了:一个 prototype 加上用于实现 body 的 expression:
/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
getNextToken(); // eat def.
auto Proto = ParsePrototype();
if (!Proto) return nullptr;
if (auto E = ParseExpression())
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
return nullptr;
}
此外,我们支持使用 extern 声明 sin、cos 等 functions,也支持对用户 function 进行 forward declaration。这些 extern 只是没有 body 的 prototypes:
/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
getNextToken(); // eat extern.
return ParsePrototype();
}
最后,我们还允许用户输入任意的 top-level expressions,并即时对它们求值。处理方式是为它们定义 anonymous nullary(zero argument)functions:
/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
// Make an anonymous proto.
auto Proto = std::make_unique<PrototypeAST>("__anon_expr", std::vector<std::string>());
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
现在所有部件都齐了,让我们构建一个小型 driver,真正执行刚才构建的代码!
Driver
driver 通过一个 top-level dispatch loop,依次调用前面实现的 parsing pieces。这里没有太多有趣内容,因此只列出 top-level loop;“Top-Level Parsing”部分的完整代码会在后面给出。
/// top ::= definition | external | expression | ';'
static void MainLoop() {
while (true) {
fprintf(stderr, "ready> ");
switch (CurTok) {
case tok_eof:
return;
case ';': // ignore top-level semicolons.
getNextToken();
break;
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
这里最有趣的地方是我们忽略了 top-level semicolons。为什么要这样做?基本原因是:如果你在 command line 中输入 4 + 5,parser 不知道你接下来是否还会继续输入。例如,下一行可能输入 def foo…,此时 4+5 就是一个 top-level expression 的结尾;也可能输入 * 6,让它继续成为当前 expression 的一部分。
有了 top-level semicolons,你就可以输入 4+5;,parser 便知道当前 expression 已经结束。
结论
通过不到 400 行带注释的代码(其中 240 行是不含注释和空白的代码),我们完整定义了这门最小语言,包括 lexer、parser 和 AST builder。完成后,可执行文件能够验证 Kaleidoscope code,并告诉我们它是否在 grammar 上有效。例如,下面是一次示例交互:
$ ./a.out
ready> def foo(x y) x+foo(y, 4.0);
Parsed a function definition.
ready> def foo(x y) x+y y;
Parsed a function definition.
Parsed a top-level expr
ready> def foo(x y) x+y );
Parsed a function definition.
Error: unknown token when expecting an expression
ready> extern sin(a);
ready> Parsed an extern
ready> ^D
$
这里还有很大的扩展空间。你可以定义新的 AST nodes,以多种方式扩展 language 等。在下一篇中,我们会介绍如何从 AST 生成 LLVM Intermediate Representation(IR)。
完整代码清单
下面是本示例的完整代码清单。
# Compile
clang++ -g -O3 toy.cpp
# Run
./a.out
下面是代码:
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
//===----------------------------------------------------------------------===//
// Lexer
//===----------------------------------------------------------------------===//
// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
// of these for known things.
enum Token {
tok_eof = -1,
// commands
tok_def = -2,
tok_extern = -3,
// primary
tok_identifier = -4,
tok_number = -5
};
static std::string IdentifierStr; // Filled in if tok_identifier
static double NumVal; // Filled in if tok_number
/// gettok - Return the next token from standard input.
static int gettok() {
static int LastChar = ' ';
// Skip any whitespace.
while (isspace(LastChar))
LastChar = getchar();
if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
IdentifierStr = LastChar;
while (isalnum((LastChar = getchar())))
IdentifierStr += LastChar;
if (IdentifierStr == "def")
return tok_def;
if (IdentifierStr == "extern")
return tok_extern;
return tok_identifier;
}
if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
std::string NumStr;
do {
NumStr += LastChar;
LastChar = getchar();
} while (isdigit(LastChar) || LastChar == '.');
NumVal = strtod(NumStr.c_str(), nullptr);
return tok_number;
}
if (LastChar == '#') {
// Comment until end of line.
do
LastChar = getchar();
while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
if (LastChar != EOF)
return gettok();
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF)
return tok_eof;
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
//===----------------------------------------------------------------------===//
// Abstract Syntax Tree (aka Parse Tree)
//===----------------------------------------------------------------------===//
namespace {
/// ExprAST - Base class for all expression nodes.
class ExprAST {
public:
virtual ~ExprAST() = default;
};
/// NumberExprAST - Expression class for numeric literals like "1.0".
class NumberExprAST : public ExprAST {
double Val;
public:
NumberExprAST(double Val) : Val(Val) {}
};
/// VariableExprAST - Expression class for referencing a variable, like "a".
class VariableExprAST : public ExprAST {
std::string Name;
public:
VariableExprAST(const std::string &Name) : Name(Name) {}
};
/// BinaryExprAST - Expression class for a binary operator.
class BinaryExprAST : public ExprAST {
char Op;
std::unique_ptr<ExprAST> LHS, RHS;
public:
BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
std::unique_ptr<ExprAST> RHS)
: Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
};
/// CallExprAST - Expression class for function calls.
class CallExprAST : public ExprAST {
std::string Callee;
std::vector<std::unique_ptr<ExprAST>> Args;
public:
CallExprAST(const std::string &Callee,
std::vector<std::unique_ptr<ExprAST>> Args)
: Callee(Callee), Args(std::move(Args)) {}
};
/// PrototypeAST - This class represents the "prototype" for a function,
/// which captures its name, and its argument names (thus implicitly the number
/// of arguments the function takes).
class PrototypeAST {
std::string Name;
std::vector<std::string> Args;
public:
PrototypeAST(const std::string &Name, std::vector<std::string> Args)
: Name(Name), Args(std::move(Args)) {}
const std::string &getName() const { return Name; }
};
/// FunctionAST - This class represents a function definition itself.
class FunctionAST {
std::unique_ptr<PrototypeAST> Proto;
std::unique_ptr<ExprAST> Body;
public:
FunctionAST(std::unique_ptr<PrototypeAST> Proto,
std::unique_ptr<ExprAST> Body)
: Proto(std::move(Proto)), Body(std::move(Body)) {}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Parser
//===----------------------------------------------------------------------===//
/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
/// token the parser is looking at. getNextToken reads another token from the
/// lexer and updates CurTok with its results.
static int CurTok;
static int getNextToken() { return CurTok = gettok(); }
/// BinopPrecedence - This holds the precedence for each binary operator that is
/// defined.
static std::map<char, int> BinopPrecedence;
/// GetTokPrecedence - Get the precedence of the pending binary operator token.
static int GetTokPrecedence() {
if (!isascii(CurTok))
return -1;
// Make sure it's a declared binop.
int TokPrec = BinopPrecedence[CurTok];
if (TokPrec <= 0)
return -1;
return TokPrec;
}
/// LogError* - These are little helper functions for error handling.
std::unique_ptr<ExprAST> LogError(const char *Str) {
fprintf(stderr, "Error: %s\n", Str);
return nullptr;
}
std::unique_ptr<PrototypeAST> LogErrorP(const char *Str) {
LogError(Str);
return nullptr;
}
static std::unique_ptr<ExprAST> ParseExpression();
/// numberexpr ::= number
static std::unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
getNextToken(); // consume the number
return std::move(Result);
}
/// parenexpr ::= '(' expression ')'
static std::unique_ptr<ExprAST> ParseParenExpr() {
getNextToken(); // eat (.
auto V = ParseExpression();
if (!V)
return nullptr;
if (CurTok != ')')
return LogError("expected ')'");
getNextToken(); // eat ).
return V;
}
/// identifierexpr
/// ::= identifier
/// ::= identifier '(' expression* ')'
static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
std::string IdName = IdentifierStr;
getNextToken(); // eat identifier.
if (CurTok != '(') // Simple variable ref.
return std::make_unique<VariableExprAST>(IdName);
// Call.
getNextToken(); // eat (
std::vector<std::unique_ptr<ExprAST>> Args;
if (CurTok != ')') {
while (true) {
if (auto Arg = ParseExpression())
Args.push_back(std::move(Arg));
else
return nullptr;
if (CurTok == ')')
break;
if (CurTok != ',')
return LogError("Expected ')' or ',' in argument list");
getNextToken();
}
}
// Eat the ')'.
getNextToken();
return std::make_unique<CallExprAST>(IdName, std::move(Args));
}
/// primary
/// ::= identifierexpr
/// ::= numberexpr
/// ::= parenexpr
static std::unique_ptr<ExprAST> ParsePrimary() {
switch (CurTok) {
default:
return LogError("unknown token when expecting an expression");
case tok_identifier:
return ParseIdentifierExpr();
case tok_number:
return ParseNumberExpr();
case '(':
return ParseParenExpr();
}
}
/// binoprhs
/// ::= ('+' primary)*
static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
std::unique_ptr<ExprAST> LHS) {
// If this is a binop, find its precedence.
while (true) {
int TokPrec = GetTokPrecedence();
// If this is a binop that binds at least as tightly as the current binop,
// consume it, otherwise we are done.
if (TokPrec < ExprPrec)
return LHS;
// Okay, we know this is a binop.
int BinOp = CurTok;
getNextToken(); // eat binop
// Parse the primary expression after the binary operator.
auto RHS = ParsePrimary();
if (!RHS)
return nullptr;
// If BinOp binds less tightly with RHS than the operator after RHS, let
// the pending operator take RHS as its LHS.
int NextPrec = GetTokPrecedence();
if (TokPrec < NextPrec) {
RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
if (!RHS)
return nullptr;
}
// Merge LHS/RHS.
LHS =
std::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
}
}
/// expression
/// ::= primary binoprhs
///
static std::unique_ptr<ExprAST> ParseExpression() {
auto LHS = ParsePrimary();
if (!LHS)
return nullptr;
return ParseBinOpRHS(0, std::move(LHS));
}
/// prototype
/// ::= id '(' id* ')'
static std::unique_ptr<PrototypeAST> ParsePrototype() {
if (CurTok != tok_identifier)
return LogErrorP("Expected function name in prototype");
std::string FnName = IdentifierStr;
getNextToken();
if (CurTok != '(')
return LogErrorP("Expected '(' in prototype");
std::vector<std::string> ArgNames;
while (getNextToken() == tok_identifier)
ArgNames.push_back(IdentifierStr);
if (CurTok != ')')
return LogErrorP("Expected ')' in prototype");
// success.
getNextToken(); // eat ')'.
return std::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
}
/// definition ::= 'def' prototype expression
static std::unique_ptr<FunctionAST> ParseDefinition() {
getNextToken(); // eat def.
auto Proto = ParsePrototype();
if (!Proto)
return nullptr;
if (auto E = ParseExpression())
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
return nullptr;
}
/// toplevelexpr ::= expression
static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
if (auto E = ParseExpression()) {
// Make an anonymous proto.
auto Proto = std::make_unique<PrototypeAST>("__anon_expr",
std::vector<std::string>());
return std::make_unique<FunctionAST>(std::move(Proto), std::move(E));
}
return nullptr;
}
/// external ::= 'extern' prototype
static std::unique_ptr<PrototypeAST> ParseExtern() {
getNextToken(); // eat extern.
return ParsePrototype();
}
//===----------------------------------------------------------------------===//
// Top-Level parsing
//===----------------------------------------------------------------------===//
static void HandleDefinition() {
if (ParseDefinition()) {
fprintf(stderr, "Parsed a function definition.\n");
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleExtern() {
if (ParseExtern()) {
fprintf(stderr, "Parsed an extern\n");
} else {
// Skip token for error recovery.
getNextToken();
}
}
static void HandleTopLevelExpression() {
// Evaluate a top-level expression into an anonymous function.
if (ParseTopLevelExpr()) {
fprintf(stderr, "Parsed a top-level expr\n");
} else {
// Skip token for error recovery.
getNextToken();
}
}
/// top ::= definition | external | expression | ';'
static void MainLoop() {
while (true) {
fprintf(stderr, "ready> ");
switch (CurTok) {
case tok_eof:
return;
case ';': // ignore top-level semicolons.
getNextToken();
break;
case tok_def:
HandleDefinition();
break;
case tok_extern:
HandleExtern();
break;
default:
HandleTopLevelExpression();
break;
}
}
}
//===----------------------------------------------------------------------===//
// Main driver code.
//===----------------------------------------------------------------------===//
int main() {
// Install standard binary operators.
// 1 is lowest precedence.
BinopPrecedence['<'] = 10;
BinopPrecedence['+'] = 20;
BinopPrecedence['-'] = 20;
BinopPrecedence['*'] = 40; // highest.
// Prime the first token.
fprintf(stderr, "ready> ");
getNextToken();
// Run the main "interpreter loop" now.
MainLoop();
return 0;
}
下一章
LLVM Kaleidoscope:生成 LLVM IR(待整理)
参考资料
版权说明:本文是基于 LLVM 官方教程的个人学习用途中文翻译。原文版权及许可证以 LLVM 项目官方说明为准。
评论 (0)