在 yacc 中将多种数据类型分配给非终端

blc*_*llo 4 yacc bison

我正在开发一个班级项目,我们必须在其中构建一个解析器。我们目前正处于在 yacc 中构建解析器的阶段。目前让我困惑的是我读到您需要为每个非终结符分配一个类型。在某些情况下,我会有类似的东西:

...
%union {
    Type dataType;
    int integerConstant;
    bool boolConstant;
    char *stringConstant;
    double doubleConstant;
    char identifier[MaxIdentLen+1]; // +1 for terminating null
    Decl *decl;
    List<Decl*> *declList;
}

%token   <identifier> T_Identifier
%token   <stringConstant> T_StringConstant 
%token   <integerConstant> T_IntConstant
%token   <doubleConstant> T_DoubleConstant
%token   <boolConstant> T_BoolConstant

...

%%
...
Expr                :    /* some rules */
                    |    Constant { /* Need to figure out what to do here */ }
                    |    /* some more rules */
                    ;

Constant            :    T_IntConstant { $$=$1 }
                    |    T_DoubleConstant { $$=$1 }
                    |    T_BoolConstant { $$=$1 }
                    |    T_StringConstant { $$=$1 }
                    |    T_Null { $$=$1 }
...
Run Code Online (Sandbox Code Playgroud)

既然有时不能是整数、双精度数或布尔值等,那么如何将类型分配给 expr 呢?

Rud*_*udi 5

您可以通过以下方式在规则中添加类型

TypesConstant            :    T_IntConstant    { $<integerConstant>$=$1 }
                         |    T_DoubleConstant { $<doubleConstant>$=$1 }
                         |    ...
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅https://www.gnu.org/software/bison/manual/html_node/Action-Types.html#Action-Types 。

  • @Chris:如果您不相信,其他页面上有使用示例,例如[中规则操作](http://www.gnu.org/software/bison/manual/ 上显示的第一个示例) html_node/Mid_002dRule-Actions.html#Mid_002dRule-Actions)页面。 (2认同)