为什么在柔性/野牛多行注释如此回避? [英] Why are multi-line comments in flex/bison so evasive?

查看:129
本文介绍了为什么在柔性/野牛多行注释如此回避?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的柔性(.L)来分析C风格的多行注释文件:

I'm trying to parse C-style multi-line comments in my flex (.l) file:

%s ML_COMMENT
%%

...

<INITIAL>"/*"                   BEGIN(ML_COMMENT);
<ML_COMMENT>"*/"                BEGIN(INITIAL);  
<ML_COMMENT>[.\n]+              { }

我不返回任何令牌和我的语法(.Y)不以任何方式解决意见。

I'm not returning any token and my grammar (.y) doesn't address comments in any way.

当我运行我的可执行文件,我得到一个解析错误:

When I run my executable, I get a parse error:

$ ./a.out
/*
abc 
def
Parse error: parse error
$ echo "/* foo */" | ./a.out
Parse error: parse error

(我的yyerror函数做一个printf(解析错误:%s \\ n),这哪里是多余的错误消息的上半年来自)。

(My yyerror function does a printf("Parse error: %s\n"), which is where the first half of the redundant error message comes from).

我明白为什么,因为输入的全部是评论,因为评论被忽略的语法,没有报表的第二个例子失败。因此,输入不是有效的方案。但是第一部分抛出一个语法错误之前,我甚至完成注释。

I can see why the second example fails since the entirety of the input is a comment, and since comments are ignored by the grammar, there are no statements. Thus the input isn't a valid program. But the first part throws a parse error before I even finish the comment.

也让人摸不着头脑:

$ ./a.out
/* foo */
a = b;
Parse error: parse error

在这种情况下,注释之前实际有效输入(其中,不包括注释,解析就好)关闭。故障实际上解析一,不试图解析分配之后后出现A = B;。如果我输入A上自己的路线,它仍然抛出一个错误。

In this case, the comment is closed prior to actual valid input (which, without the comment, parses just fine). The failure actually occurs after parsing "a", not after attempting to parse the assignment "a = b;". If I enter "a" on its own line, it still throws an error.

鉴于该错误信息是语法解析错误,而不是扫描仪错误,有什么我失踪关键在我的.Y文件?还是我做错了什么在我的扫描仪规则传播到解析器一边?

Given that the error message is a parser error and not a scanner error, is there something crucial I'm missing in my .y file? Or am I doing something wrong in my scanner rules that propagates over to the parser side?

编辑:每@鲁迪的建议下,我打开调试,发现:

Per @Rudi's suggestion, I turned on debugging and found:

$ ./a.out
Starting parse
Entering state 0
Reading a token: /*
foo
Next token is 44 (IDENTIFER)
Shifting token 44 (IDENTIFER), Entering state 4
Reducing via rule 5 (line 130), IDENTIFER  -> identifier
state stack now 0
Entering state 5

我关掉调试,发现 / *富* / =酒吧; 确实解析相同富=酒吧; 。我使用Flex 2.5.4;它不给我,我试图使用有状态的任何警告。

I turned off debugging and found that /* foo */ = bar; indeed parses the same as foo = bar;. I'm using flex 2.5.4; it doesn't give me any warnings about the stateful rules I'm attempting to use.

推荐答案

我想你需要声明你ML_COMMENT启动的情况作为一个独特的启动条件所以只有ML_COMMENT规则是积极的。 %×ML_COMMENT 而不是%S ML_COMMENT

I think you need to declare your ML_COMMENT start condition as an exclusive start condition so only the ML_COMMENT rules are active. %x ML_COMMENT instead of %s ML_COMMENT

否则没有开始条件的规则也很活跃。

Otherwise rules with no start conditions are also active.

这篇关于为什么在柔性/野牛多行注释如此回避?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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