0

I'm writing a grammar using Flex++ to generate a parser and this block of code always returns an "unrecognized rule" error.

%{
#include "Parserbase.h"
%}

%option noyywrap

num         [0-9]+
float       [0-9]+"."[0-9]+
comment     [["//"[.]*\n] | ["/\*"[.]*"\*/"]]
varname     [a-zA-Z][a-zA-Z0-9_]*

%%


";"             {return ParserBase::SEMICOLON;}
"\n"            {return ParserBase::ENDLINE;}

"int"           {return ParserBase::INT;}
"="             {return ParserBase::EQUALS;}
{num}           {return ParserBase::NUM;}
{comment}       {return ParserBase::COMMENT;}
{varname}       {return ParserBase::VARNAME;}

This always returns the following :

bisonc++ Compiler.y
[Warning] Terminal symbol(s) not used in productions:
257: NUM
261: ENDLINE
g++ -c parse.cc
flex++ Compiler.l
Compiler.l:21: unrecognised rule
make: *** [lex.yy.cc] Error 1

I've tried moving around the rules, changing the alias to a simple [a-zA-Z] or even just [a-z] All to no avail, and it's driving me mad... Anyone got any ideas? Thanks!

4

1 回答 1

3

此定义无效:

comment     [["//"[.]*\n] | ["/\*"[.]*"\*/"]]

[并且(是不同的。[...]是一个字符类;也就是说,将匹配单个字符的可能字符列表。(...)用于对正则表达式进行分组。

另外,我不相信您可以在 Flex++ 正则表达式中插入任意空格字符。

所以我认为你的意图是:

comment     ("//".*\n|"/*".*"*/")

在这里,我删除了不正确的方括号,将用于分组的方括号更改为括号,并删除了替代项周围不必要的分组,因为|优先级低于串联。我还删除了不必要的反斜杠转义,因为引用足以使 a*变成一个字符。

但是,这不会正确匹配 C++ 注释:

首先,.*是贪婪的(即,它将匹配最长的可能字符串)所以

/* A comment */ a = 3; /* Another comment */

将被错误地识别为单个评论。

其次,.不匹配换行符。所以多行/* ... */评论不会匹配,因为.*不会到达评论的末尾,只会到行尾。

于 2014-03-10T04:15:24.270 回答