我正在 RED HAT LINUX 上使用 flex 制作 C 编译器。但进展不顺利,请帮忙。它没有显示任何这些。 为什么它没有在 printf 语句中显示输出。 如何创建库和预定义指令的检查?
keywords auto | break | default | case | for | char | malloc |int |const |continue |do |double |if |else | enum | extern |float | goto |long |void |return |short |static | sizeof|switch| typedef |union|unsigned| signed | volatile| while | do | struct
%%
{keywords}*
{
printf ( "\n\n\nThese are keywords:" ) ; printf( "'%s'\n" , yytext ) ;
}
"#include define"
{
printf ( "\n\n\nThese are predefined directives:" );
printf( "'%s'\n",yytext );
}
"#include <"|"#include \" "
{
printf ( "\n\n\nThese are libraries:");
printf ( "'%s'\n",yytext);
}
""|,|;|:|!
{
printf ("\n\n\n These are puctuation :") ;
printf("'%s'\n",yytext);
}
"<<"|">>"|"<"|">"|"<="|">="|"+"|"-"|"*"|"/"|"{"|"}"|"["|"]"|"&&"|"||"
{
printf("\n\n\nThese are operators:");
printf("'%s'\n",yytext);
}
"//"|"/*"|"*/"
{
printf("\n\n\nThese are comments:");
printf("'%s'\n",yytext);
}
%%
int yywrap(void)
{
return 1;
}
int main (void)
{
yylex();
return 0;
}
最佳答案
您的 Flex 输入非常糟糕,实际上不会生成扫描仪,只是一堆(可能非常令人困惑)错误消息。
第一个问题是空格和换行符在语法上对于 Flex 来说非常重要——空格将模式与操作分开,换行符结束操作。因此,keyword
模式中的所有空格都会导致问题;你需要摆脱它们:
keywords auto|break|default|case|for|char|malloc|int|const|continue|do|double|if|else|enum|extern|float|goto|long|void|return|short|static|sizeof|switch|typedef|union|unsigned|signed|volatile|while|do|struct
然后,规则中的模式和操作之间不能有换行符(否则最终会得到两个模式并且没有操作)。所以你需要:
{keywords}* {
printf ( "\n\n\nThese are keywords:" ) ; printf( "'%s'\n" , yytext ) ;
}
其余规则也是如此。
一旦你这样做了,你就可以让你的代码通过flex运行并生成一个扫描仪。现在您可以给它输入并看看它会做什么。
任何与其中一条规则匹配的内容都会触发该规则。例如,break
将触发“关键字”规则,但 casecharswitch
或任何其他混合在一起的关键字字符串也会触发“关键字”规则。那是因为您在该规则上使用了 *
。
任何不符合任何规则的内容都会简单地回显到输出中。由于这可能不是您想要的,因此您需要确保您的规则与规则末尾的 .
和 \n
匹配,以便每个可能的输入将匹配某些规则。
关于使用flex的C编译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513628/