开发者

Assigning multiple data types to a non-terminal in yacc

开发者 https://www.devze.com 2023-02-08 22:31 出处:网络
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 as

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 fig开发者_JS百科ure 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?


You can add the type in the rule by

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号