-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate.c
116 lines (111 loc) · 2.47 KB
/
evaluate.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
106
107
108
109
110
111
112
113
114
115
#include "evaluate.h"
extern symnode *root;
int evaluate(node *ptr)
{
int op=ptr->op,temp;
char buf[30];
symnode *symentry;
switch(op)
{
case CH_CONST:
return ptr->value;
case CH_ADD:
return evaluate(ptr->left)+evaluate(ptr->right);
case CH_SUB:
return evaluate(ptr->left)-evaluate(ptr->right);
case CH_MUL:
return evaluate(ptr->left)*evaluate(ptr->right);
case CH_DIV:
return evaluate(ptr->left)/evaluate(ptr->right);
case CH_UMINUS:
return -evaluate(ptr->left);
case CH_IDENT:
symentry=lookup(ptr->name,root);
return *(symentry->binding);
case CH_IDENTARR:
temp=evaluate(ptr->left);
symentry=lookup(ptr->name,root);
return *(symentry->binding+temp);
case CH_IF:
if(evaluate(ptr->left)!=0)
return evaluate(ptr->right);
return 0;
case CH_IFELSE:
if(evaluate(ptr->left)!=0)
return evaluate(ptr->right);
else
return evaluate(ptr->middle);
case CH_STMNT:
evaluate(ptr->left);
return evaluate(ptr->right);
case CH_READ:
printf("enter ");
scanf("%d",&temp);
return temp;
case CH_WRITE:
printf("%d\n",evaluate(ptr->left));
return 0;
case CH_ASSIGN:
symentry=lookup(ptr->name,root);
*(symentry->binding)=evaluate(ptr->right);
return 0;
case CH_ASSIGNARR:
symentry=lookup(ptr->name,root);
temp=evaluate(ptr->left);
*(symentry->binding+temp)=evaluate(ptr->right);
return 0;
case CH_RELOP:
switch(ptr->value)
{
case CH_GE:
if(evaluate(ptr->left)>=evaluate(ptr->right))
return 1;
return 0;
case CH_LE:
if(evaluate(ptr->left)<=evaluate(ptr->right))
return 1;
return 0;
case CH_EQ:
if(evaluate(ptr->left)==evaluate(ptr->right))
return 1;
return 0;
case CH_NE:
if(evaluate(ptr->left)!=evaluate(ptr->right))
return 1;
return 0;
case CH_GT:
if(evaluate(ptr->left)>evaluate(ptr->right))
return 1;
return 0;
case CH_LT:
if(evaluate(ptr->left)<evaluate(ptr->right))
return 1;
return 0;
default:
return 0;
}
case CH_LOGOP:
switch(ptr->value)
{
case CH_LOGAND:
if(evaluate(ptr->left)&&evaluate(ptr->right))
return 1;
return 0;
case CH_LOGOR:
if(evaluate(ptr->left)||evaluate(ptr->right))
return 1;
return 0;
default:
return 0;
}
case CH_WHILE:
while(evaluate(ptr->left)!=0)
{
evaluate(ptr->right);
}
return 0;
default:
sprintf(buf,"Syntax error %d",op);
yyerror(buf);
}
}