Flex: Unrecognized rule error

I come up with an "unrecognized rule" error in Flex. I have read some articles but I did not find any solution to my problem. I have tried to make some changes in my code, but nothing seems to make it work(sometimes these changes made it even worse instead). I post my code below hoping a solution to be found.

My flex code:

%{
#include <stdio.h>
%}
VAR_DEFINER "var"
VAR_NAME [a-zA-Z][a-zA-Z0-9_]*
VAR_TYPE "real" | "boolean" | "integer" | "char"
%%
{VAR_DEFINER}              {printf("A keyword: %sn", yytext);}
{VAR_NAME} | ","{VAR_NAME} {printf("A variable name: %sn", yytext);}
":"                        {printf("A colonn");}
{VAR_TYPE}";""n"          {printf("The variable type is: %sn", yytext);}
"n"{VAR_DEFINER}          {printf("Error: The keyword 'var' is defined once at the beginning.n");}
[ tn]+                   /* eat up whitespace */
.                          {printf("Unrecognized character: %sn", yytext);}
%%
main(argc, argv)
int argc;
char** argv;
{
++argv, --argc;
if (argc > 0) 
yyin = fopen(argv[0],"r");
else 
yyin = stdin;
yylex();
}

As you wrote in your own answer to your question, you can fix the errors by being careful with whitespace.

But the underlying problem is that you are trying to let the scanner do work that is better done by the parser. If you want to parse things like var x boolean , then that shouldn't be a single token, discovered by the scanner. The usual, and most often much better, approach is to let the scanner discover three separate tokens ( var , x and boolean ), and then let the parser group them into a variable declaration.


I found the answer on my own. I would like to post it to help anyone else who may have a similar problem, just in case.

My fault was that I left unquoted whitespaces amongst the terms of expressions or amongst the variable types in declaration part. For example, I have written VAR_TYPE "real" | "boolean" | "integer" | "char" , instead of VAR_TYPE "real"|"boolean"|"integer"|"char" (without whitespaces).

So, mind all kinds of brackets and the whitespaces!!!

I hope to have helped!

链接地址: http://www.djcxy.com/p/57876.html

上一篇: Symfony2 UniqueEntity验证约束作为级联?

下一篇: Flex:无法识别的规则错误