获取多个成员的类型

发布于 2024-08-21 15:58:00 字数 532 浏览 9 评论 0原文

我正在使用 Yacc/Flex 编写一个程序,并且使用以下代码(不完全相同,因为我混合了其他文件中的代码):

DataType datat;
%union {  
    int integer;  
    char *string;  
    DataType type;  
}

Integer { yylval.type = INTEGER; return INT; }
%type <type> INT
data : INTNUM { yylval.type = INTEGER; }

然后,如果我编写如下内容:

foo : data { bar(yylval.type); }

bar正确获取数据类型INTEGER,但如果我有这个:

foo : data data { ??? }

如何分别获取第一个和第二个成员的yylval.type

多谢!

I'm writing a program with Yacc/Flex and I'm using the following code (not exactly the same because I'm mixing code from other file):

DataType datat;
%union {  
    int integer;  
    char *string;  
    DataType type;  
}

Integer { yylval.type = INTEGER; return INT; }
%type <type> INT
data : INTNUM { yylval.type = INTEGER; }

Then if I write something like this:

foo : data { bar(yylval.type); }

bar gets correctly the datatype INTEGER, but if I have this:

foo : data data { ??? }

How do I get the yylval.type for the first and second member separately?

Thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七度光 2024-08-28 15:58:00

我不完全理解你的问题,但在 lex/yacc (或 flex/bison)中,你必须使用以下约定:

  • 使用 $1 引用第一个项目的 yylval
  • 使用 $2 引用第二个项目的 yylval
  • 的 yylval

使用 $$ 来引用结果(目标)项目 如果您要编写一个简单的整数计算器,定义总和的规则将写成这样:

Sum : Term '+' Term
   {
   $.Value = $1.Value + $3.Value
   }

希望这会有所帮助。

I don't completely understand your question, but in lex/yacc (or flex/bison) you have to use the following conventions:

  • Use $1 to refer to the yylval of the first item
  • Use $2 to refer to the yylval of the second item
  • Use $$ to refer to the yylval of the resulting (target) item

E.g. if you would write a simple integer calculator, the rule that defines the sum, would be written something like this:

Sum : Term '+' Term
   {
   $.Value = $1.Value + $3.Value
   }

Hope this helps.

ヅ她的身影、若隐若现 2024-08-28 15:58:00

yylval.type 将返回最后扫描的令牌的类型,这可能是简化为数据的整数,但也可能是其后面的令牌。您永远不应该直接在 yacc/bison 文件中访问 yylval,因为它不可靠。

相反,您应该使用 $1$2 等来访问 Patrick 指出的项目的 YYSTYPE 信息。要使其适用于非终端,您需要在 yacc/bison 文件中为它们使用 %type 声明,并且这些非终端的规则需要设置 $$,例如:

%type <type> data

%%

data : INTNUM { $ = INTEGER; }

foo : data { bar($1); }

foo : data data { bar($1, $2); }

yylval.type will return you the type from the last token scanned, which might be the Integer that got reduced to data, but might be the token after it. You should NEVER access yylval directly in the yacc/bison file, as its not reliable.

Instead, you should use $1, $2, etc to access the YYSTYPE info of the items as noted by Patrick. To make this work for non-terminals, you need to use %type declarations for them in the yacc/bison file, and the rules for those non terminals need to set $$, eg:

%type <type> data

%%

data : INTNUM { $ = INTEGER; }

foo : data { bar($1); }

foo : data data { bar($1, $2); }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文