-
Notifications
You must be signed in to change notification settings - Fork 0
/
fb3-1.c
105 lines (98 loc) · 1.61 KB
/
fb3-1.c
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "fb3-1.h"
struct ast *
newast(int nodetype, struct ast *l, struct ast *r)
{
struct ast *a = malloc(sizeof(struct ast));
if(!a) {
yyerror("out of memory");
exit(0);
}
a->nodetype = nodetype;
a->l = l;
a->r = r;
return a;
}
struct ast *
newnum(double d)
{
struct numval *n = malloc(sizeof(struct ast));
if(!n) {
yyerror("out of memory");
exit(0);
}
n->nodetype = 'K';
n->number = d;
return (struct ast *)n;
}
double
eval(struct ast *a)
{
double v; // calculated value of this subtree
switch(a->nodetype) {
case 'K':
v = ((struct numval *)a)->number;
break;
case '+':
v = eval(a->l) + eval(a->r);
break;
case '-':
v = eval(a->l) - eval(a->r);
break;
case '*':
v = eval(a->l) * eval(a->r);
break;
case '/':
v = eval(a->l) / eval(a->r);
break;
case '|':
v = eval(a->l);
if(v < 0) v = -v;
break;
case 'M':
v = -eval(a->l);
break;
default:
printf("internal error: bad node %c\n",a->nodetype);
}
return v;
}
void
treefree(struct ast *a)
{
switch(a->nodetype) {
/* two subtrees */
case '+':
case '-':
case '*':
case '/':
treefree(a->r);
/* one subtree */
case '|':
case 'M':
treefree(a->l);
/* no subtree */
case 'K':
free(a);
break;
default:
printf("internal error: free bad node %c\n",a->nodetype);
}
}
void
yyerror(char *s, ...)
{
va_list ap;
va_start(ap,s);
fprintf(stderr,"%d: error: ",yylineno);
vfprintf(stderr,s,ap);
fprintf(stderr,"\n");
}
int
main()
{
printf("> ");
return yyparse();
}