递归下降解析器问题 [英] Recursive descent parser questions
本文介绍了递归下降解析器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个关于如何编写递归下降解析器的问题:
I have two questions about how to write a recursive descent parser:
第一个是什么时候有一个非终结符可以匹配几个不同的终结符之一?如何检查哪种方式是正确的?
The first is what when you have a nonterminal that can match one of a few different nonterminals? How do you check which way is correct?
其次,如何构建AST?使用YACC,我可以只写一段代码来为非终结符的每个实例执行,并且它有特殊的变量,引用规则的值。如何在递归下降解析器中做类似的事情?
Second, how do you build an AST? Using YACC, I can just write a piece of code to execute for every instance of a nonterminal and it has special variables which refer to the "values" of the rules. How do you do a similar thing in a recursive descent parser?
推荐答案
- ,然后在故障时回溯。或者您证明自己的语言位于 LL( k )
- 对于规则的每一次成功解析,都要从子规则的结果中构造一个对象。
例如
class ASTNode {
public:
virtual int eval() = 0;
virtual ~ASTNode() = 0;
};
// construct this when parsing an integer literal
class Value : ASTNode {
int v;
public:
Value(int v_) : v(v_) {}
virtual int eval() { return v; }
virtual ~Value() {}
};
// construct this when parsing "x+y"
class Addition : ASTNode {
ASTNode *left, *right;
public:
Addition(ASTNode *l, ASTNode *r) : left(l), right(r) {}
virtual int eval() { return l->eval() + r->eval(); }
virtual ~Addition() { delete left; delete right; }
};
这篇关于递归下降解析器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文