-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.y
74 lines (53 loc) · 1.03 KB
/
calc.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
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
%{
#define _CRT_SECURE_NO_WARNINGS
#define YYSTYPE double
YYSTYPE yylval;
#include <stdio.h>
#include <ctype.h>
%}
%token NUMBER
%%
expr: term expr_tail { $$ = $1; printf("Result is %4f\n", $$); }
;
expr_tail:
| '+' term expr_tail { $< = $< + $2; }
| '-' term expr_tail { $< = $< - $2; }
;
term: factor term_tail
;
term_tail:
| '*' factor term_tail { $< = $< * $2; }
| '/' factor term_tail { $< = $< / $2; }
;
factor: NUMBER
|'(' expr ')' { $$ = $2; }
;
%%
int lineno = 1;
int yylex()
{
int c;
yylval = 0.0;
while ((c=getchar()) == ' ' || c == '\t' || c == '\n')
;
if (c == EOF)
return 0;
if (c == '.' || isdigit(c))
{
ungetc(c, stdin);
scanf("%lf", &yylval);
return TS_NUMBER;
}
// if (c == '\n')
// lineno++;
return c;
}
int main(int argc, char *argv[])
{
calc parser(yylex);
// set to true to see parsing details
// parser.setDebug(true);
parser.yyparse();
printf("Succesful parse.\n");
return 0;
}