Assigning multiple data types to a non-terminal in

2019-04-02 00:10发布

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?

标签: yacc bison
1条回答
不美不萌又怎样
2楼-- · 2019-04-02 00:35

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.

查看更多
登录 后发表回答