lex中无法识别的规则

时间:2010-04-25 01:40:05

标签: lex

我正在用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);}

%%

该规则有什么问题?感谢。

1 个答案:

答案 0 :(得分:7)

上一行导致了问题。如果您在{id}规则和{number}规则之间添加空格,则会注意到错误的行号不会更改。

模式中不允许使用空格。因此定义{id}:

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