Flex:'='标记之前的语法错误

时间:2014-05-09 21:34:16

标签: c c-preprocessor flex-lexer

我正在尝试使用flex构建我自己的迷你 C 语言编译器,但是有一个错误不断出现。你能帮我找一下有什么问题吗?我搜索了一个解决方案,但仍未找到此错误背后的原因。这是代码:

%{
#define KEY_VOID = 258
#define KEY_FLOAT = 260
#define KEY_IF = 261
#define KEY_ELSE = 262
#define KEY_WHILE = 263
#define KEY_FOR = 264
#define KEY_RETURN = 265
#define KEY_BREAK = 266
#define AND_OP = 267
#define OR_OP = 268
#define SMALL_EQ_OP = 269
#define GREAT_EQ_OP = 270
#define EQ_OP = 271
#define SMALL_OP = 272
#define GREAT_OP = 273
#define NOT_EQ_OP = 274
#define ASSIGN_OP = 275
#define OPN_BRACKET = 276
#define CLS_BRACKET = 277
#define CLS_BRACE = 290
#define OPN_BRACE = 291
#define SEMICOLON_SYMBOL = 278
#define COMMA_SYMBOL = 279
#define DOT_SYMBOL = 280
#define ADD_OP = 281
#define SUB_OP = 282
#define ASTERISK_SYMBOL = 283
#define SLASH_SYMBOL = 284
#define START_COMMENT_SYMBOL = 285
#define END_COMMENT_SYMBOL = 286
#define INT_NUM 287
#define FLOAT_NUM 288
#define IDENTIFIER 289
Int  yylval;
%}
Letters     [a-zA-Z]
Digits      [0-9]
Sympols     [@#$%&*-+!"':;/?(),~`|^_=×{}<>]
%%
[/*][{Letters}|{Digits}|{Sympols}|\n|\t]*[/*]       {/* Ignore Comments */} 
[-+]?[{Digits}]+                        {yylval = atoi(yytext); return INT_NUM;}
[-+]?[{Digits}]+.[{Digits}]+                    {yylval = atoi(yytext);return FLOAT_NUM;}
[{Letters}][{Letters}|{Digits}|_]*              {return IDENTIFIER;}
[ \t\n]+                            {/* Ignore WhiteSpaces and New lines */}
"void"      {return KEY_VOID;}
"float"     {return KEY_FLOAT;}
"if"        {return KEY_IF;}
"else"      {return KEY_ELSE ;}
"while"     {return KEY_WHILE;}
"for"       {return KEY_FOR;}
"return"    {return KEY_RETURN;}
"break"     {return KEY_BREAK;}
"&&"        {return AND_OP;}
"||"        {return OR_OP;}
"<="        {return SMALL_EQ_OP;}
">="        {return GREAT_EQ_OP;}
"=="        {return EQ_OP;}
"<"     {return SMALL_OP;}
">"     {return GREAT_OP;}
"!="        {return NOT_EQ_OP;}
"="     {return ASSIGN_OP;}
"("     {return OPN_BRACKET;}
")"     {return CLS_BRACKET;}
";"     {return SEMICOLON_SYMBOL;}
","     {return COMMA_SYMBOL;}
"."     {return DOT_SYMBOL;}
"+"     {return ADD_OP;}
"-"     {return SUB_OP;}
"*"     {return ASTERISK_SYMBOL;}
"/"     {return SLASH_SYMBOL;}
.       {yyerror();}
%%

int main(void)
{
    yyparse();
    return 0;
}

int yywrap(void)
{
    return 1;
}

int yyerror(void)
{
    printf("Error\n");
    exit(1); 
}

这是一直出现的错误:

  在'='标记之前

46 C:\ GnuWin32 \ GnuWin32 \ bin \ Project.l语法错误

1 个答案:

答案 0 :(得分:2)

问题出在你的#define中 - 它们应该看起来像:

#define KEY_VOID 258

但有时候你会有一个额外的等号,例如:

#define KEY_VOID = 258

错误消息行具有误导性,因为仅在随后使用宏的情况下报告错误,而不是在定义宏的位置报告错误。