Assigning multiple data types to a non-terminal in yacc

我怕爱的太早我们不能终老 提交于 2019-12-05 06:08:09

问题


I'm working on a project for class in which we have to build a parser. We're currently in the stage of building the parser in yacc. The thing currently confusing me is I've read that you need to assign a type to each nonterminal. In some cases though I'll have Something like:

...
%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 }
...

How can you assing a type to expr since can't it sometimes be an integer or double, or bool, etc?


回答1:


You can add the type in the rule by

TypesConstant            :    T_IntConstant    { $<integerConstant>$=$1 }
                         |    T_DoubleConstant { $<doubleConstant>$=$1 }
                         |    ...

See http://www.gnu.org/software/bison/manual/html_node/Action-Types.html#Action-Types for more details.



来源:https://stackoverflow.com/questions/4905819/assigning-multiple-data-types-to-a-non-terminal-in-yacc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!