我编写了一个简单的程序,希望它是输出后缀表示及其值的中缀计算器。我不知道为什么,但是当我运行它并向它传递简单数据时,我收到语法错误。这是我传递的内容,以及我与 src 文件一起返回的内容。
执行:
2+2+2
2 2 +
4
syntax error
Bison 文件:
%{
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
extern int yylex();
extern int yyparse();
void yyerror(const char *msg);
%}
%union {
int ival;
}
%token <ival> NUM
%type <ival> N M P A
%%
S : A {printf("\n%d\n", $1);}
;
A : P '-' P {printf("- "); $$ = (int)($1 - $3);}
| P '+' P {printf("+ "); $$ = (int)($1 + $3);}
| P {$$ = $1;}
;
P : M '/' M {printf("/ "); $$ = (int)($1 / $3);}
| M '*' M {printf("* "); $$ = (int)($1 * $3);}
| M '%' M {printf("% "); $$ = (int)($1 % $3);}
| M {$$ = $1;}
;
M : N '^' N {printf("^ "); $$ = (int)pow($1, $3);}
| N {$$ = $1;}
;
N : '(' A ')' {$$ = $2;}
| '-' N {printf("-%d ", $2); (int)($$ = -$2);}
| NUM {printf("%d ", $1); (int)($$ = $1);}
;
%%
void main() {
yyparse();
return;
}
void yyerror(const char *msg) {
fprintf(stderr, "%s\n", msg);
}
Flex 文件:
%{
#include <stdio.h>
#include <stdlib.h>
#include "bison.tab.h"
%}
%%
#.*\n
"\\"\n
[0-9]+ {
yylval.ival = atoi(yytext);
return NUM;
}
[-+*/^%()] {
return yytext[0];
}
[ \t\n]
%%
你能看出我的错误吗? Maby,我只是没有足够好地阅读 Bison 文档。很难找到任何关于它的教程。
最佳答案
好吧,我找到了解决方案,但我不知道为什么它有效。如果有人想澄清,我会感激我不擅长正式语言。我改变的是:
P : M '/' M {printf("/ "); $$ = (int)($1 / $3);}
| M '*' M {printf("* "); $$ = (int)($1 * $3);}
| M '%' M {printf("% "); $$ = (int)($1 % $3);}
| M {$$ = $1;}
;
更改为:
P : P '/' M {printf("/ "); $$ = (int)($1 / $3);}
| P '*' M {printf("* "); $$ = (int)($1 * $3);}
| P '%' M {printf("% "); $$ = (int)($1 % $3);}
| M {$$ = $1;}
;
并对每个非终结符进行相应的操作。
关于c - Bison 抛出语法错误,但我看不到我的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53505000/