본문 바로가기
BoB/Compiler

[v4, 5.] flex and bison

by reindeer002 2022. 3. 17.
728x90

4단계 : 잘못된 수식을 입력하면, 수식에서 연산자의 좌변, 우변 중 불충분한 부분을 오류로 출력하기
5단계 : 주석기능으로 수식 // 을 인식하고, 이후의 문자열은 예외처리하는 수식 계산기

[makefile]

all: compiler_v4-5

compiler_v4-5: 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_v4-5
	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);}
        ;
exp: factor
        | exp ADD factor { $$ = $1 + $3;}
        | exp SUB factor { $$ = $1 - $3;}
        ;
factor: term
        | factor MUL term {$$ = $1 * $3;}
        | factor DIV term {$$ = $1 / $3;}
        ;
term: NUMBER
        | ABS exp ABS {$$ = $2 >= 0? $2 : -$2;}
        | OP exp CP {$$ = $2;}
        | SUB term {$$ = -$2;}
        | SUB term {$$ = -$2;}
        ;
%%

int main()
{
        yyparse();
}

yyerror(char *s)
{
        fprintf(stderr, "There is no value left or right\n");
        fprintf(stderr, "error: %s\n", s);
}
728x90

'BoB > Compiler' 카테고리의 다른 글

[v3.] flex and bison  (0) 2022.03.17
[v2.] flex and bison  (0) 2022.03.17
[v1.] flex and bison  (0) 2022.03.17

댓글