Lex regex获得了一些额外的字符 [英] Lex regex gets some extra characters

查看:71
本文介绍了Lex regex获得了一些额外的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的lex文件中具有以下定义:

I have the following definition in my lex file:

L   [a-zA-Z_]                                           
A   [a-zA-Z_0-9] 
%%
{L}{A}*                 { yylval.id = yytext; return IDENTIFIER; }

然后在我的YACC文件中执行以下操作:

And I do the following in my YACC file:

primary_expression
    : IDENTIFIER            { puts("IDENTIFIER: "); printf("%s", $1); }

我的源代码(我正在分析的源代码)具有以下分配:

My source code (the one I'm analyzing) has the following assignment:

ab= 10;

由于某些原因,printf("%s", $1);部分正在打印ab=,而不仅仅是ab.

For some reason, that printf("%s", $1); part is printing ab= and not only ab.

我很确定这是正在打印ab=的部分,因为当我删除printf("%s", $1);时,标识符根本不会打印.

I'm pretty sure that's the section that is printing ab= because when I delete the printf("%s", $1); the identifier is not printed at all.

我真的没办法了.我究竟做错了什么?

I really ran out of ideas. What am I doing wrong?

让我知道我是否可以更清楚.

Let me know if I can be more clear.

推荐答案

我在做什么错了?

What am I doing wrong?

您假设yytext指向的字符串是常量.不是.

You're assuming that the string pointed to by yytext is constant. It is not.

yytext指向的字符串的生存期是关联规则的词汇作用.如果该规则最终返回,则yytext将保留直到下一次调用yylex为止.就是这样.

The lifetime of the string pointed to by yytext is the lexical action of the associated rule. If that rule ends up returning, yytext will survive until the next time yylex is called. And that's it.

bison生成的解析器的前瞻性为一个符号.因此,在解析器执行语义操作时,已再次调用yylex(用于超前).因此,即使对于规则中的最后一个(或唯一)标记,也不能使用yytext的保存值.

bison-generated parsers have a one-symbol lookahead. So by the time the parser executes a semantic action, yylex has been called again (for the lookahead); consequently, you can't use the saved value of yytext even for the last (or only) token in a rule.

解决方案:复制字符串. (我使用strdup,但是出于某些原因,有些人喜欢malloc和strcpy.如果您这样做,请不要忘记NUL终止符.)在完成副本后,请记住要复制free().

Solution: copy the string. (I use strdup, but for whatever reason some people like to malloc and strcpy. If you do, don't forget about the NUL terminator.) And remember to free() the copy when you're done with it.

供参考: flex手册是什么说.

这篇关于Lex regex获得了一些额外的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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