【发布时间】:2014-01-31 20:45:33
【问题描述】:
我正在用 Flex/Bison 制作一个基本计算器,我想做指数 (^),但我目前的实现不起作用,谁能告诉我为什么不能以及如何解决它?
%{
#include <stdio.h>
#include <math.h>
void yyerror(char *);
int yylex(void);
int symbol;
%}
%token INTEGER VARIABLE
%left '+' '-' '*' '/' '^'
%%
program:
program statement '\n'
| /* NULL */
;
statement:
expression { printf("%d\n", $1); }
| VARIABLE '=' expression { symbol = $3; }
;
expression:
INTEGER
| VARIABLE { $$ = symbol; }
| '-' expression { $$ = -$2; }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression { $$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression { $$ = $1 / $3; }
| expression '^' expression { $$ = $1 ^ $3; }
| '(' expression ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
fprintf(stderr, "%s\n", s);
}
int main(void) {
yyparse();
}
谢谢
【问题讨论】:
-
请注意您的标记; flex 用于 UI 框架; Flex-lexer 用于词法分析器。
-
取幂运算符是右关联的,而不是左关联的。
标签: compiler-construction bison flex-lexer exponential