获取多个成员的类型
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不完全理解你的问题,但在 lex/yacc (或 flex/bison)中,你必须使用以下约定:
使用 $$ 来引用结果(目标)项目 如果您要编写一个简单的整数计算器,定义总和的规则将写成这样:
希望这会有所帮助。
I don't completely understand your question, but in lex/yacc (or flex/bison) you have to use the following conventions:
E.g. if you would write a simple integer calculator, the rule that defines the sum, would be written something like this:
Hope this helps.
yylval.type 将返回最后扫描的令牌的类型,这可能是简化为数据的整数,但也可能是其后面的令牌。您永远不应该直接在 yacc/bison 文件中访问 yylval,因为它不可靠。
相反,您应该使用
$1
、$2
等来访问 Patrick 指出的项目的 YYSTYPE 信息。要使其适用于非终端,您需要在 yacc/bison 文件中为它们使用%type
声明,并且这些非终端的规则需要设置$$
,例如: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: