-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.y
More file actions
84 lines (72 loc) · 1.43 KB
/
basic.y
File metadata and controls
84 lines (72 loc) · 1.43 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
%{
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#ifndef YYSTYPE
#define YYSTYPE int
#endif
int yylex();
extern int yyparse();
FILE* yyin;
void yyerror(const char* s);
%}
%token ADD SUB MUL DIV NUMBER
%left ADD SUB
%left MUL DIV
%right UMINUS
%%
lines : lines expr ';' { printf("%d\n", $2); }
| lines ';'
|
;
expr : expr ADD expr { $$ = $1 + $3; }
| expr SUB expr { $$ = $1 - $3; }
| expr MUL expr { $$ = $1 * $3; }
| expr DIV expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
| SUB expr %prec UMINUS { $$ = -$2; }
| NUMBER { $$ = $1; }
;
%%
int yylex()
{
int t;
while(1){
t=getchar();
if(t==' '||t=='\t'||t=='\n'){
//do noting
}else if(isdigit(t)){
yylval = 0;
while(isdigit(t))
{
yylval = yylval * 10 + (t - '0');
t = getchar();
}
ungetc(t, stdin);
return NUMBER;
}else if(t=='+'){
return ADD;
}else if(t=='-'){
return SUB;
}else if(t=='*'){
return MUL;
}else if(t=='/'){
return DIV;
}
else{
return t;
}
}
}
int main(void)
{
yyin=stdin;
do{
yyparse();
}while(!feof(yyin));
return 0;
}
void yyerror(const char* s){
fprintf(stderr,"Parse error: %s\n",s);
exit(1);
}