我正在与 Bison 合作,为我正在编写的编译器构建 AST。在 AST 中构建节点的最佳方法是什么?举例说明我的问题可能会更清楚。
给定以下代码段:
field
: modifier type TOK_IDENT TOK_SEMICOLON
{
// I want to return a pointer to a node of type Field
// i.e. $$ = new Field(name, isVisible, isStatic, type);
}
;
modifier
: visibility_opt static_opt
{
// Should I make the new Field here and pass it up?
// Or a new type that contains both vis and static options?
}
;
visibility_opt
: /* default */ { $$ = true; }
| TOK_PUBLIC { $$ = true; }
| TOK_PRIVATE { $$ = false; }
;
static_opt
: /* default */ { $$ = false; }
| TOK_STATIC { $$ = true; }
;
在上面的示例中,我希望字段规则返回一个 Field 节点,但我需要一些修饰符规则的属性,这些属性将在解析期间传递(即这些是合成属性)。
我可以想到两种不改变语法的方法。
- 让非终结符修饰符的类型为 Field,在这里创建新的 Field,我能填的填上,然后传给 field 来填剩下的。
- 让修饰符有自己的类型,它包含两个 bool 值,并在字段规则中创建新字段时将其向上提取数据。
在这种情况下,首选的方法是什么?
最佳答案
就像其他人建议的那样,首选方法是使用具有可见性和静态选项的结构修饰符。但我可能会将其设为静态修饰符,因为它不会传递到字段中,而只是用于提取值,然后传递到字段中。您甚至可以在堆栈中分配它,然后重用它以加快速度。
大致如下:
static struct { boolean vis_opt; boolean static_opt; } mod;
field
: modifier type TOK_IDENT TOK_SEMICOLON
{
$$ = new Field(..., mod.vis_opt, mod.static_opt, ...);
}
;
modifier
: visibility_opt static_opt
{
mod.vis_opt = $1;
mod.static_opt = $2;
}
;
visibility_opt
: /* default */ { $$ = true; }
| TOK_PUBLIC { $$ = true; }
| TOK_PRIVATE { $$ = false; }
;
static_opt
: /* default */ { $$ = false; }
| TOK_STATIC { $$ = true; }
;
此外,除非您非常确定该语言的 future ,否则您可能需要考虑将可见性设为枚举。你永远不知道在开发语言时你最终会梦想什么样的可见性,至少如果你在枚举中有它,以后更容易扩展。
享受吧。
关于c++ - 使用 Bison 构建 AST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9853752/