-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr-explicit.y
36 lines (34 loc) · 1015 Bytes
/
expr-explicit.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
%{
#include <stdio.h>
int yylex();
int yyerror(char *s);
extern int yylval; // yylval 변수를 외부에서 참조
// 명시적인(explicit) 방법
%}
%token NUMBER
%left '+' '-'
%left '*' '/'
%%
Exp : Exp '+' Exp { $$ = $1 + $3;
printf("E(%d) -> E(%d) + E(%d)\n", $$, $1, $3); }
| Exp '-' Exp { $$ = $1 - $3;
printf("E(%d) -> E(%d) - E(%d)\n", $$, $1, $3); }
| Exp '*' Exp { $$ = $1 * $3;
printf("E(%d) -> E(%d) * E(%d)\n", $$, $1, $3); }
| Exp '/' Exp { if ($3 == 0) yyerror("divide by zero");
else $$ = $1 / $3;
printf("E(%d) -> E(%d) / E(%d)\n", $$, $1, $3); }
| '(' Exp ')' { $$ = $2;
printf("E(%d) -> (E(%d))\n", $$, $2); }
| '-' Exp { $$ = -$2;
printf("E(%d) -> -E(%d)\n", $$, $2); }
| NUMBER { $$ = $1;
printf("E(%d) -> n(%d)\n", $$, $1); }
;
%%
int main() {
yyparse();
}
int yyerror(char *s) {
printf("%s\n", s);
}