为什么下面的 LEX 程序不打印 "No. of tokens"
Why the following LEX program is not printing "No. of tokens"
我的代码正在打印标识符、分隔符和所有其他东西,只是它没有打印 tokens.Can 的数字。没有指出问题。
%{
int n=0;
%}
%%
"while"|"if"|"else"|"printf" {
n++;
printf("\t keywords : %s", yytext);}
"int"|"float" {
n++;printf("\t identifier : %s", yytext);
}
"<="|"=="|"="|"++"|"-"|"*"|"+" {
n++;printf("\t operator : %s", yytext);
}
[(){}|, ;] {n++;printf("\t seperator : %s", yytext);}
[0-9]*"."[0-9]+ {
n++;printf("\t float : %s", yytext);
}
[0-9]+ {
n++;printf("\t integer : %s", yytext);
}
.;
%%
int main(void)
{
yylex();
printf("\n total no. of tokens = %d\n",n);
}
int yywrap()
{
return 0;
}
如果yywrap()
returns 0,词法分析器假设yywrap()
以某种方式安排yyin
有更多数据,词法分析器将继续读取输入.所以你的词法分析器永远不会终止。
如果你想发出没有更多数据的信号,你需要return 1 from yywrap()
。
最好通过放置
来避免对 yywrap
的需要
%option noyywrap
在 flex 序言中。
我通常使用 %option noinput nounput noyywrap
,它消除了一些编译器警告,假设您要求编译器警告,您应该始终这样做。 %option nodefault
还可以帮助您找到 lex 规范错误,因为如果某些输入没有匹配规则,它会抱怨。 (对无法识别的输入的默认 (f)lex 操作是简单地将不匹配的字符写入标准输出。这通常不是很有帮助,而且与错误消息不同,它很容易被遗漏。)最后,%option 8bit
是仅当您请求针对速度而不是 table-size 优化的词法分析器时才需要。但是添加它并没有坏处,如果您(或某人)有一天决定尝试更快的扫描仪骨架,它可能会使您免于遇到令人尴尬的错误。 (不推荐,除非在非常特殊的情况下。)
我的代码正在打印标识符、分隔符和所有其他东西,只是它没有打印 tokens.Can 的数字。没有指出问题。
%{
int n=0;
%}
%%
"while"|"if"|"else"|"printf" {
n++;
printf("\t keywords : %s", yytext);}
"int"|"float" {
n++;printf("\t identifier : %s", yytext);
}
"<="|"=="|"="|"++"|"-"|"*"|"+" {
n++;printf("\t operator : %s", yytext);
}
[(){}|, ;] {n++;printf("\t seperator : %s", yytext);}
[0-9]*"."[0-9]+ {
n++;printf("\t float : %s", yytext);
}
[0-9]+ {
n++;printf("\t integer : %s", yytext);
}
.;
%%
int main(void)
{
yylex();
printf("\n total no. of tokens = %d\n",n);
}
int yywrap()
{
return 0;
}
如果yywrap()
returns 0,词法分析器假设yywrap()
以某种方式安排yyin
有更多数据,词法分析器将继续读取输入.所以你的词法分析器永远不会终止。
如果你想发出没有更多数据的信号,你需要return 1 from yywrap()
。
最好通过放置
来避免对yywrap
的需要
%option noyywrap
在 flex 序言中。
我通常使用 %option noinput nounput noyywrap
,它消除了一些编译器警告,假设您要求编译器警告,您应该始终这样做。 %option nodefault
还可以帮助您找到 lex 规范错误,因为如果某些输入没有匹配规则,它会抱怨。 (对无法识别的输入的默认 (f)lex 操作是简单地将不匹配的字符写入标准输出。这通常不是很有帮助,而且与错误消息不同,它很容易被遗漏。)最后,%option 8bit
是仅当您请求针对速度而不是 table-size 优化的词法分析器时才需要。但是添加它并没有坏处,如果您(或某人)有一天决定尝试更快的扫描仪骨架,它可能会使您免于遇到令人尴尬的错误。 (不推荐,除非在非常特殊的情况下。)