In the following code which is a lexical recognizer in C language:
%{
#include <stdio.h>
void showToken(char*);
%}
%option yylineno
%option noyywrap
digit ([0-9])
letter ([a-zA-Z])
%%
letter(letter | digit)* showToken("id");
(digit)(digit)*(.(digit)(digit)*)? showToken("num");
[(),:;.] printf("%c",yytext[0]);
[ \n]
(==|<>|<|<=|>|>=) showToken("relop");
(+|-) showToken("addop");
(*|/) showToken("mulop");
(=) showToken("assign");
(&&) showToken("and");
(||) showToken("or");
(!) showToken("not");
. {
printf("Lexical Error");
exit(0);
}
%%
void showToken(char* name){
printf("<%s,%s>",name,yytext);
}
%%
I get the following errors, why is that happening I think I wrote the code correctly! I have done too many changes in the code but it doesn't compile.
~/hedor>lex -t lexical.l > lexical.c
lexical.l:13: unrecognized rule
lexical.l:17: unrecognized rule
lexical.l:17: unrecognized rule
lexical.l:17: unrecognized rule
lexical.l:17: unrecognized rule
lexical.l:17: unrecognized rule
lexical.l:18: unrecognized rule
lexical.l:18: unrecognized rule
lexical.l:18: unrecognized rule
lexical.l:18: unrecognized rule
lexical.l:18: unrecognized rule
lexical.l:21: unrecognized rule
lexical.l:21: unrecognized rule
lexical.l:21: unrecognized rule
lexical.l:21: unrecognized rule
There are several issues in your regular expressions:
Line 13, actually the error is in the 12, do not add blanks in the RE, it breaks the expression and does not work as expected:
letter(letter|digit)* showToken("id");
Line 17, the +
is a special character, so escape it with \\
:
(\+|-) showToken("addop");
Line 18, the same with characters *
and /
:
(\*|\/) showToken("mulop");
Line 21, the same with |
:
(\|\|) showToken("or");
That should fix the compilation errors, but note the comment by @JameySharp below, you likely want to write the digit
and letter
references using curly braces: {digit}
and {letter}
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.