C++ 使用Bison构建AST
我正在与Bison合作,为我正在编写的编译器构建AST。在AST中构建节点的最佳方式是什么?举个例子,我的问题可能会更清楚 给出以下代码段:C++ 使用Bison构建AST,c++,compiler-construction,bison,abstract-syntax-tree,C++,Compiler Construction,Bison,Abstract Syntax Tree,我正在与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);
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节点,但我需要在解析期间传递的修饰符规则的一些属性(即,这些是合成属性)
在不改变语法的情况下,我可以想出两种方法
在这种情况下,首选的方法是什么?像其他人建议的那样,首选的方法是使用带有可见性和静态选项的结构修改器。但我可能会使它成为一个静态修饰符,因为它不会传递到字段中,而是简单地用于提取值,然后传递到字段中。您甚至可以在堆栈中分配它,并重用它以加快速度 大致如下:
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; }
;
此外,除非你对语言的未来很有把握,否则你可能会想让能见度成为一个枚举。你永远不知道在开发语言的过程中,你最终会梦到什么样的可视性,至少如果你在枚举中有它,那么以后扩展起来就更容易了
享受。我个人会选择备选方案二。主要是因为
modifier
实际上不是一个字段,而是一个独立的字段。是的,我选择了第二种方法,现在让modifier具有std::pair类型。但这似乎要视情况而定,因为在另一种情况下,采用第一种方法更有意义。。。