Xin CA
Xin CA

Reputation: 27

"warning, rule cannot be matched" Defining String in lex

I was trying to create a rule to create a String and print it. So heres the code:

 %{
char buff[200];
char *s;
}%
%X STRLIT
%%
\"                  {BEGIN STRLIT; s = buf;}
<STRLIT><<EOF>>     {printf("unterminated string literal\n");
                     BEGIN 0;}
<STRLIT>\\          {*s++ = '\\';}
<STRLIT>\f          {*s++ = '\f';}
<STRLIT>\n          ;
<STRLIT>\r          ;
<STRLIT>\t          {*s++ = '\t';}
<STRLIT>.           {*s++ = *yytext;}
<STRLIT>\"          {*s = 0;printf("STRING(%s)\n",buf);BEGIN 0;}

The error is in the last line, but i cant figure why.

Upvotes: 0

Views: 130

Answers (1)

sepp2k
sepp2k

Reputation: 370112

When there are multiple rules that can match on the current input and produce a match of the same size, flex will take the rule that's defined first.

So, for example, if there's a \t, both the rules \t and . could match, but \t comes first, so it's the one that's used. But if a " appears, . is used because \" comes after it in your flex file. So there's no way that the \" rule in STRLIT would ever be used and that's what the error is about.

To fix this, simply move . to be the last rule. That way it will only match if none of the other rules match.

Upvotes: 1

Related Questions