【发布时间】:2018-07-16 08:06:11
【问题描述】:
我正在学习使用 Flex 编写词法分析器,但发现了一个奇怪的问题。 我尝试定义关键字class的正则表达式。
对于我的测试用例:
class T{
}
表达式1:
ws [\t\r\f\v ]
CLASS (^class$)|(^class{ws})|({ws}class{ws})|({ws}class$)
没用。
表达式2:
ws [\t\r\f\v ]
CLASS ^class{ws}
有效。
表达式 3:
ws [\t\r\f\v ]
CLASS1 ^class{ws}
CLASS {CLASS1}
报告错误说无法识别的规则。
我感到很困惑,2和3之间有什么区别吗? 我参考Flex github 上的示例。它只是使用类似的表达式来定义数字。
任何帮助将不胜感激!
更新:
我的脚本:
%{
/* Some include headers here */
/* The compiler assumes these identifiers. */
#define yylval cool_yylval
#define yylex cool_yylex
/* Max size of string constants */
#define MAX_STR_CONST 1025
#define YY_NO_UNPUT /* keep g++ happy */
extern FILE *fin; /* we read from this file */
/* define YY_INPUT so we read from the FILE fin:
* This change makes it possible to use this scanner in
* the Cool compiler.
*/
#undef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( (result = fread( (char*)buf, sizeof(char), max_size, fin)) < 0) \
YY_FATAL_ERROR( "read() in flex scanner failed");
char string_buf[MAX_STR_CONST]; /* to assemble string constants */
char *string_buf_ptr;
extern int curr_lineno;
extern int verbose_flag;
extern YYSTYPE cool_yylval;
%}
/*
* Define names for regular expressions here.
*/
ws [\t\r\f\v ]
CLASS1 {ws}class$
CLASS2 ^class$
CLASS3 ^class{ws}
CLASS4 {ws}class{ws}
CLASS {CLASS2}
DARROW =>
STRING \"[^\n"]+\"
%%
{CLASS} {return (CLASS);} /*returned CLASS is defined in other header files*/
%%
【问题讨论】:
-
我无法重现您的问题。你能发布一个产生“无法识别的规则”错误的最小但完整的 flex 文件吗?
-
@sepp2k 我更新了 flex 文件。
CLASS {CLASS2}导致错误,但CLASS {CLASS1}没问题。
标签: regex flex-lexer