-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest2.php
66 lines (54 loc) · 1.83 KB
/
test2.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
66
<?php
require 'ast/Exp.php';
require 'ast/Program.php';
require 'Eval.php';
/**
代码
fact := 1 ;
val := 10000 ;
cur := val ;
mod := 1000000007 ;
while ( cur > 1 )
do
{
fact := fact * cur ;
fact := fact - fact / mod * mod ;
cur := cur - 1
} ;
cur := 0
*/
// 语法树
$fact = new ExpVar('fact');
$assignStmt1 = new ProgramAssign($fact, new ExpNum(1)); // fact := 1 ;
$val = new ExpVar('val');
$assignStmt2 = new ProgramAssign($val, new ExpNum(10000)); // val := 10000 ;
$cur = new ExpVar('cur');
$assignStmt3 = new ProgramAssign($cur, $val); // cur := val ;
$mod = new ExpVar('mod');
$assignStmt4 = new ProgramAssign($mod, new ExpNum(1000000007)); // mod := 1000000007 ;
$plusStmt = new ProgramAssign($fact, new ExpSub($fact, new ExpMul(new ExpDiv($fact, $mod), $mod)));
$pred = new ExpGT($cur, new ExpNum(1)); // cur > 1
$body1 = new ProgramAssign($fact, new ExpMul($fact, $cur)); // fact := fact * cur ;
$body2 = new ProgramAssign($fact, new ExpSub($fact, new ExpMul(new ExpDiv($fact, $mod), $mod))); // fact := fact - fact / mod * mod ;
$body3 = new ProgramAssign($cur, new ExpSub($cur, new ExpNum(1))); // cur := cur - 1
$body = new ProgramStmts([$body1, $body2, $body3]);
$whileStmt = new ProgramWhile($pred, $body); // while ...
$assignStmt5 = new ProgramAssign($cur, new ExpNum(0)); // cur := 0
$print_cur = new ProgramPrint($cur); // print cur
$print_fact = new ProgramPrint($fact); // print fact
$print_mod = new ProgramPrint($mod); // print mod
$print_val = new ProgramPrint($val); // print val
// 解释执行
$stmts = [
$assignStmt1,
$assignStmt2,
$assignStmt3,
$assignStmt4,
$whileStmt,
$assignStmt5,
$print_cur,
$print_fact,
$print_mod,
$print_val
];
evalProgram(new ProgramStmts($stmts));