본문 바로가기
BoB/Compiler

[v1.] flex and bison

by reindeer002 2022. 3. 17.
728x90

1단계 : 정수, 절대값을 입력받아 사칙연산을 수행하기

[makefile]

all: compiler_v1

compiler_v1: 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_v1
	rm -f *.h

 

[compiler.l]

%{
	#include "compiler.tab.h"
%}

%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%

 

[compiler.y]

%{
	#include <stdio.h>
%}

%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL

%%
calclist:
	| calclist exp EOL {printf("= %d\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
[v2.] flex and bison  (0) 2022.03.17

댓글