递归下降分析和语法树
Recursive Descent Parsing and Syntax Trees
所以我几个月来一直在研究和试验语言设计,我比几个月前有了更好的理解。不过,我仍然对一些事情感到困惑...我已经在没有研究的情况下砍掉了一些糟糕的解析器,但我需要更好的东西。所以我正在尝试编写一个递归下降解析器,因为我已经读到它是手写的最合乎逻辑的解析器。据我了解,每个规则都实现到它自己的功能中。所以我想我明白我会如何写这些,但只有前半部分......解析器的工作是创建一个语法树或类似的东西,对吗?我也一直在尝试研究这个主题,但我无法找到任何如何在语言中表示树的例子。我用 D 编写,因为它是我最喜欢的语言,但它与 C/C++ 非常相似,所以我会理解用这些语言或伪代码编写的任何示例。
在我所看到的中,有大量的类相互继承,因此可能有一个语句类,例如 IfStatement 类扩展了该类。但是我一直无法找到所有这些如何在树上表示,甚至无法找到它后来是如何行走的。
如果有人能给我看一个例子或更深入地谈论这些事情,那就太好了。任何帮助真的意义重大,有助于我的好奇心和目标,提前感谢!
树通常表示为包含指向其子级的指针的结构,并且它有一个存储其节点类型的node
成员,或者它属于某个类,以便您可以派生其实际类型(即,如果它包含算术表达式,if语句,循环等)。
正如你提到的,一个简单的例子确实是if
声明。为此,您可以执行以下操作(伪 C 如下):
enum AST_Node {
Node_if,
Node_and,
Node_or,
Node_not,
Node_equal,
Node_less,
// etc., other node types follow
};
struct AST {
struct AST *children[MAX_CHILDREN]; // don't do this
enum AST_Node node;
};
struct AST *parse_if_statement()
{
// expect tokens in order
expect("if");
// parse condition
expect("(");
struct AST *condition = parse_expression();
expect(")");
// parse two child statements
struct AST *then_branch = parse_statement();
struct AST *else_branch = NULL;
if (accept("else")) {
else_branch = parse_statement();
}
// create AST, fill in children
struct AST *if_statement = new_AST_node(Node_if);
if_statement->children[0] = condition;
if_statement->children[1] = then_branch;
if_statement->children[2] = else_branch;
return if_statement;
}
所以基本上你只是期望/接受永久的词汇元素("if",条件周围的括号等),然后你把子树(条件和两个分支)的解析交给适当的解析器函数。
这就是你走树的方式:你基本上做一个深度优先的行走,按顺序编译或解释每个孩子。然后,添加当前正在解释/编译的子树的节点类型所暗示的额外语义。
Value *interpret_if_statement(struct AST *ast)
{
assert(ast->node == Node_if);
struct AST *condition = ast->children[0];
struct AST *then_branch = ast->children[1];
struct AST *else_branch = ast->children[2];
// evaluate condition
Value *condval = interpret_expression(condition);
if (condval->bool_value == TRUE) {
// if condition is true, interpret "then" branch
return interpret_statement(then_branch);
} else if (else_branch != NULL) {
// otherwise interpret "else" branch, if any
return interpret_statement(else_branch);
} else {
return NULL;
}
}
相关文章:
- 在递归二叉搜索树中搜索
- 二叉树结构平衡,使用递归时EXC_BAD_ACCESS
- 通过提升属性树(递归方式)发出 YAML 迭代
- 二叉树递归的高度
- 多态性抽象语法树(递归下降解析器):不可能
- 四叉树递归检索
- 函数结束后儿童节点的树递归C 缺失值
- C++二进制树递归析构函数问题
- 从C++中的二进制搜索树(递归)复制叶
- 通过类型C++ 的继承树递归导致此指针问题
- 二叉树递归插入方法不起作用
- 将STL列表转换为二进制搜索树递归模板
- 递归下降分析和语法树
- 二叉搜索树递归显示节点
- 二进制搜索树递归插入导致堆栈溢出,迭代插入不起作用
- 二叉搜索树递归插入
- 二叉树递归加法不能产生正确的结果
- 二叉搜索树递归删除
- 二进制搜索树递归析构函数
- 如何避免深树递归中的堆栈溢出