2017-10-08 237 views
0

我的flex描述似乎在我的更具體的情況之前有一個捕捉。我敢肯定,這是我的一個錯字,但我不知道哪條規則導致我的其他規則無法匹敵。我相信可能的嫌疑犯是我創建的字符串描述。但是我仍然不確定,並且正在尋找答案。導致無法匹敵的規則的Flex描述

branch.l文件:

%option noyywrap 

%{ 
#include "global.h" 
%} 

delim   [\t ] 
ws    {delim}+ 
digit   [0-9] 
num    {digit}+ 
alpha   [_a-zA-Z] 
identifier  {alpha}({alpha}|{digit})* 
relation  [<]|[>]|[>][=]|[<][=]|[=][=]|[!][=] 
string   ["][a-zA-Z0-9]*["] 

%% 

{ws}   {/* skip blanks and tabs */} 
{num} { 
    tokenval = atoi(yytext); 
    return NUM; 
} 

{identifier} { 
    if (strlen(yytext) >= BSIZE) { 
    error("compiler error"); 
    } 
    tokensym = lookup(yytext, ID); 
    tokensym->count += 1; 
    return (int)tokensym->token; 
} 

"BEGIN"   {return BEGN;} 
"IF"   {return IF;} 
"THEN"   {return THEN;} 
"ELSE"   {return ELSE;} 
"GOTO"   {return GOTO;} 
"NULL"   {return NUL;} 
"READ"   {return READ;} 
"PRINT"   {return PRINT;} 
"*"    {return '*';} 
"+"    {return '+';} 
"-"    {return '-';} 
"/"    {return '/';} 
"("    {return '(';} 
")"    {return ')';} 
"="    {return '=';} 
"."    {return '.';} 
"\n"   {lineno++;} 
";"    {return ';';} 
"END"   {return DONE;} 
<<EOF>>   {return DONE;} 

{relation} {return RELATION;} 
{string} {return STRING;}` 

而且這些都是無法比擬的規則...

branch.l:33: warning, rule cannot be matched 
branch.l:34: warning, rule cannot be matched 
branch.l:35: warning, rule cannot be matched 
branch.l:36: warning, rule cannot be matched 
branch.l:37: warning, rule cannot be matched 
branch.l:38: warning, rule cannot be matched 
branch.l:39: warning, rule cannot be matched 
branch.l:40: warning, rule cannot be matched 
branch.l:51: warning, rule cannot be matched 

我無法弄清楚如何輕鬆地添加行號。但警告指的是BEGIN-PRINT行和ELSE行下行。

回答

1

BEGIN將匹配{identifier}"BEGIN"。既然如此,flex將(如文檔所述)匹配文件中的第一個規則,即{identifier}。因此,"BEGIN"將永遠不會匹配。


坦率地說,我會拋棄那些大部分(如果不是全部)宏定義。您可以使用[[:alpha:]_]代替{alpha}[[:digit:]]代替{digit}(事實上,中[[:alnum:]]*代替({alpha}|{digit})*)。大多數情況下,使用宏只能將模式與規則操作分開,使代碼難以閱讀(恕我直言)。如果你有非常複雜的圖案或您多次使用的模式

宏可能是有用的,但很少適用。

+0

謝謝你的回答。你的回答非常有幫助!感謝您參加最佳實踐課程。 –