在词法分析中出现了未被识别的规则

5

我正在使用lex编写程序,它给了我以下错误提示:

scanner.l:49: 无法识别的规则

第49行是:{number} {return(NUM);}

编辑: 然而,该错误似乎与之前的那一行有关,{id} {return(ID);}。 即使这一行为空白,它也会将紧随其后的那行列为错误源。

以下是我的代码:

#include <stdio.h>

%token BOOL, ELSE, IF, TRUE, WHILE, DO, FALSE, INT, VOID
%token LPAREN, RPAREN, LBRACK, RBRACK, LBRACE, RBRACE, SEMI, COMMA, PLUS, MINUS, TIMES
%token DIV, MOD, AND, OR, NOT, IS, ADDR, EQ, NE, LT, GT, LE, GE
%token NUM, ID, PUNCT, OP

int line = 1, numAttr;
char *strAttr;
%}

/* regular definitions */

delim   [ \t]
ws      {delim}+
letter  [A-Za-z]
digit   [0-9]
id      ({letter} | _)({letter} | {digit} | _)*
number  {digit}+

%%

{ws}        {/* no action and no return */}
[\n]        {line++;}
bool        {return(BOOL);}
else        {return(ELSE);}
if          {return(IF);}
true        {return(TRUE);}
while       {return(WHILE);}
do          {return(DO);}
false       {return(FALSE);}
int         {return(INT);}
void        {return(VOID);}

{id}        {return(ID);}  // error is on these two lines
{number}    {return(NUM);} //

"("         {yylval = LPAREN; return(PUNCT);}
")"         {yylval = RPAREN; return(PUNCT);}
"["         {yylval = LBRACK; return(PUNCT);}
"]"         {yylval = RBRACK; return(PUNCT);}
"{"         {yylval = LBRACE; return(PUNCT);}
"}"         {yylval = RBRACE; return(PUNCT);}
";"         {yylval = SEMI;   return(PUNCT);}
","         {yylval = COMMA;  return(PUNCT);}

"+"         {yylval = PLUS;   return(OP);}
"-"         {yylval = MINUS;  return(OP);}
"*"         {yylval = TIMES;  return(OP);}
"/"         {yylval = DIV;    return(OP);}
"%"         {yylval = MOD;    return(OP);}
"&"         {yylval = ADDR;   return(OP);}
"&&"        {yylval = AND;    return(OP);}
"||"        {yylval = OR;     return(OP);}
"!"         {yylval = NOT;    return(OP);}
"!="        {yylval = NE;     return(OP);}
"="         {yylval = IS;     return(OP);}
"=="        {yylval = EQ;     return(OP);}
"<"         {yylval = LT;     return(OP);}
"<="        {yylval = LE;     return(OP);}
">"         {yylval = GT;     return(OP);}
">="        {yylval = GE;     return(OP);}

%%

那个规则有什么问题吗?谢谢。
2个回答

14

前一行代码引起了问题。如果在{id}规则和{number}规则之间添加一个空格,你会发现错误的行号没有改变。

模式中不允许有空格。因此应如下定义{id}:

id      ({letter}|_)({letter}|{digit}|_)*

0

我也遇到了这个问题。我在id的定义行后面加了一个注释。也许这里也是一个注释问题。


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接