-
Notifications
You must be signed in to change notification settings - Fork 0
/
Eval.php
65 lines (64 loc) · 1.83 KB
/
Eval.php
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
<?php
function evalExp(Exp $e)
{
if ($e instanceof ExpNum) {
return $e->val;
}
elseif ($e instanceof ExpVar) {
return $e->val;
}
elseif ($e instanceof ExpPlus) {
return evalExp($e->left) + evalExp($e->right);
}
elseif ($e instanceof ExpSub) {
return evalExp($e->left) - evalExp($e->right);
}
elseif ($e instanceof ExpMul) {
return evalExp($e->left) * evalExp($e->right);
}
elseif ($e instanceof ExpDiv) {
return floor(evalExp($e->left) / evalExp($e->right));
}
elseif ($e instanceof ExpLT) {
return evalExp($e->left) < evalExp($e->right);
}
elseif ($e instanceof ExpGT) {
return evalExp($e->left) > evalExp($e->right);
}
elseif ($e instanceof ExpAnd) {
return evalExp($e->left) && evalExp($e->right);
}
elseif ($e instanceof ExpOr) {
return evalExp($e->left) || evalExp($e->right);
}
elseif ($e instanceof ExpBoolLiteral) {
return evalExp($e->val);
}
}
function evalProgram($p)
{
if ($p instanceof ProgramAssign) { // 执行赋值语句
$p->lhs->val = evalExp($p->rhs);
}
elseif ($p instanceof ProgramIfElse) { // 执行if语句
if (evalExp($p->pred)) {
evalProgram($p->conseq);
}
else {
evalProgram($p->alter);
}
}
elseif ($p instanceof ProgramWhile) { // 执行while语句
while (evalExp($p->pred)) {
evalProgram($p->body);
}
}
elseif ($p instanceof ProgramStmts) { // 执行语句块
foreach ($p->stmts as &$stmt) {
evalProgram($stmt);
}
}
elseif ($p instanceof ProgramPrint) { // 执行print语句
echo $p->val->val . "\n";
}
}