bison 简单计算器
简单计算器的 bison 语法文件
学习bison 过程中,很多人都是从计算器开始的, 这里给一个简单的例子
bison 语法文件 cal.y
%{
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
int yylex (void);
void yyerror (char const *);
%}
%define api.value.type {double}
%token NUM
%left '+' '-'
%left '*' '/'
%left '^'
%%
input:%empty
| input line
;
line: '\n'
| exp '\n' { printf ("%.10g\n", $1); }
;
exp:
NUM
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '(' exp ')' { $$ = $2; }
| exp '^' exp { $$ = pow ($1, $3); } /* Exponentiation */
| exp 'n' { $$ = -$1; } /* Unary minus */
;
%%
int main(void) {
yyparse();
return 0;
}
void yyerror(char const * msg) {
printf("%s\n", msg);
}
int yylex(void) {
int c = getchar ();
/* Skip white space. */
while (c == ' ' || c == '\t') c = getchar ();
/* Process numbers. */
if (c == '.' || isdigit (c))
{
ungetc (c, stdin);
if (scanf ("%lf", &yylval) != 1)
abort ();
return NUM;
}
else if (c == EOF) /* Return end-of-input. */
return YYEOF;
else /* Return a single char. */
return c;
}
Makefile 文件
cal: cal.tab.c
gcc -g -o $@ $^ -lm
cal.tab.c : cal.y
bison $<
clean:
rm cal cal.tab.c
如果你觉得本文有帮助, 请打赏博主!
link.
版权声明:本文为free2o原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。