在yacc中将多种数据类型分配给非终端 [英] Assigning multiple data types to a non-terminal in yacc

查看:100
本文介绍了在yacc中将多种数据类型分配给非终端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个项目设计类,我们必须在其中构建一个解析器.我们目前处于使用yacc构建解析器的阶段.目前让我感到困惑的是,我读到您需要为每个非终端分配一个类型.在某些情况下,我会有类似的东西:

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

由于有时不能是整数,双精度或bool等,如何将类型赋给expr?

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

请参见 http://www.gnu .org/software/bison/manual/html_node/Action-Types.html#Action-Types 了解更多详细信息.

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

这篇关于在yacc中将多种数据类型分配给非终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆