728x90
2단계 : 소수점이 있는 수를 입력받아 사칙연산을 수행하기
[makefile]
all: compiler_v2
compiler_v2: compiler.l compiler.y
bison -d compiler.y
flex compiler.l
cc -o $@ compiler.tab.c lex.yy.c -lfl
clean:
rm -f *.c
rm -f compiler_v2
rm -f *.h
[compiler.l]
%{
#include "compiler.tab.h"
#include <stdio.h>
#include <stdlib.h>
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
([0-9]+\.[0-9]+)|([0-9]+) {
double temp;
sscanf(yytext, "%lf", &temp);
yylval.double_val = temp;
return NUMBER;
}
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
[compiler.y]
%{
#include <stdio.h>
#include <stdlib.h>
%}
%union {
double double_val;
}
%token<double_val> NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%type<double_val> term exp factor negative calclist
%%
calclist:
| calclist exp EOL {printf("= %lf\n", $2);}
;
negative:
| SUB exp {$$ = -$2;}
| SUB factor {$$ = -$2;}
;
exp: factor
| negative
| exp ADD exp { $$ = $1 + $3;}
| exp SUB exp { $$ = $1 - $3;}
;
factor: term
| negative
| factor MUL factor {$$ = $1 * $3;}
| factor DIV factor {$$ = $1 / $3;}
;
term: NUMBER
| ABS exp ABS {$$ = $2 >= 0? $2 : -$2;}
;
%%
int main()
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
}
728x90
'BoB > Compiler' 카테고리의 다른 글
[v4, 5.] flex and bison (0) | 2022.03.17 |
---|---|
[v3.] flex and bison (0) | 2022.03.17 |
[v1.] flex and bison (0) | 2022.03.17 |
댓글