본문 바로가기
BoB/Compiler

[v3.] flex and bison

by reindeer002 2022. 3. 17.
728x90

3단계 : 소괄호 '( )' 로 묶은 수식을 우선하여 사칙연산을 수행하기

[makefile]

all: compiler_v3

compiler_v3: 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_v3
	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;
}
"(" {return OP;}
")" {return CP;}
"//".*
\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
%token OP CP

%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;}
	| OP exp CP {$$ = $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
[v2.] flex and bison  (0) 2022.03.17
[v1.] flex and bison  (0) 2022.03.17

댓글