本文实现二元表达式的解析和构造。
static std::map<char, int> operator_precedence;
static void init_precedence() {
operator_precedence['-'] = 1;
operator_precedence['+'] = 2;
operator_precedence['/'] = 3;
operator_precedence['*'] = 4;
}
static int getBinOpPrecedence() {
if(isascii(current_token)) {
return -1;
}
int tokPrec = operator_precedence[current_token];
if (tokPrec <= 0) return -1;
return tokPrec;
}
static BaseAST* paran_parser() {
next_token();
BaseAST* v = expression_parser();
if (!v) return 0;
if (current_token != ')') return 0;
return v;
}
static void HandleDefn() {
if (FunctionDefnAST *f = func_defn_parser()) {
if (Function* lf = f->Codegen()) {
}
} else {
next_token();
}
}
static void HandleTopExpression() {
if (FunctionDefnAST* *f = top_level_parser()) {
if (Function* lf = f->Codegen()) {
}
} else {
next_token();
}
}
static BaseAST* Base_Parser() {
switch(current_token) {
default: return 0;
case IDENTIFIER_TOKEN: return identifier_parser();
case NUMERIC_TOKEN: return numeric_parser();
case '(': return paran_parser();
}
}
static BaseAST* binary_op_parser(int old_prec, BaseAST* lhs) {
while (true) {
int operator_prec = getBinOpPrecedence();
if (operator_prec < old_prec) return lhs;
int BinOp = current_token;
next_token();
BaseAST* rhs = Base_Parser();
if (!rhs) return 0;
int next_prec = getBinOpPrecedence();
if (operator_prec < next_prec) {
rhs = binary_op_parser(operator_prec + 1, rhs);
if (rhs == 0) return 0;
}
lhs = new BinaryAST(std::to_string(BinOp), lhs, rhs);
}
}