无法在野牛代码中找到'syntax error'的原因



我正在尝试连接简单的flex和bison代码,现在只能识别一个字符。然而我正面临着这个错误。我已经通读了很多答案,想弄清楚是什么错了,但我迷路了。任何帮助将是非常感激的,因为我刚刚开始探索这个,不能找到很多的资源。

我的。l文件

%{
#include <stdlib.h>
#include <stdio.h>
#include "MiniJSC.tab.h"
void yyerror (char *s);
int yylex();
%}
%%

[0-9]+                                                              { yylval.num = atoi(yytext); return T_INT_VAL; }
%%
int yywrap (void) {return 1;}

my .y file

%{
void yyerror (char *s);
int yylex();
#include <stdio.h>     /* C declarations used in actions */
#include <stdlib.h>
%}
%union {int num; char id;}         /* Yacc definitions */
%start line
%token print
%token T_INT_VAL
%type <num> line
%type <num> term 
%type <num> T_INT_VAL
%%
/* descriptions of expected inputs     corresponding actions (in C) */
line    : print term ';'            {printf("Printing %dn", $2);}
;

term    : T_INT_VAL                 {$$ = $1;}
;
%%                     /* C code */
void yyerror (char *s) {
fprintf (stderr, "%sn", s);
}
int main (void) {
return yyparse ( );
}

编译和输出:

$ bison MiniJSC.y -d
$ lex MiniJSC.l
$ gcc lex.yy.c MiniJSC.tab.c
$ ./a.out
10
syntax error
$ 
line    : print term ';'

根据这个,一个有效的行包含一个print令牌后面跟着一个term。由于term必须是T_INT_VAL令牌,这意味着一个有效的行是print令牌后面跟着T_INT_VAL令牌。

你的输入只包含一个T_INT_VAL标记,所以它不是一个有效的行,这就是为什么你得到一个语法错误。

还要注意,您的词法分析器从未生成print令牌,因此即使您输入print 10作为输入,也会出现错误,因为词法分析器不会将print识别为令牌。所以你也应该为它添加一个模式

您还应该重命名print以匹配您对令牌的命名约定(即ALL_CAPS)。

相关内容

最新更新