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
|
#!/usr/bin/awk -f
@include "vm.awk"
# Complex test program
BEGIN {
# Test program to calculate factorial of 5
i = 0
# Push 5 onto stack
image[i++] = pack_opcodes(OP_LIT, 0, 0, 0)
image[i++] = 5
# Push 1 onto stack (accumulator)
image[i++] = pack_opcodes(OP_LIT, 0, 0, 0)
image[i++] = 1
# Start of multiplication loop
loop_start = i
# Duplicate top number (counter)
image[i++] = pack_opcodes(OP_DUP, 0, 0, 0)
# Test if counter is zero
image[i++] = pack_opcodes(OP_ZERO_EXIT, 0, 0, 0)
# Multiply accumulator by counter
image[i++] = pack_opcodes(OP_MUL, 0, 0, 0)
# Decrement counter
image[i++] = pack_opcodes(OP_LIT, 0, 0, 0)
image[i++] = 1
image[i++] = pack_opcodes(OP_SUB, 0, 0, 0)
# Jump back to start of loop
image[i++] = pack_opcodes(OP_LIT, 0, 0, 0)
image[i++] = loop_start
image[i++] = pack_opcodes(OP_JUMP, 0, 0, 0)
# Halt
image[i++] = pack_opcodes(OP_HALT, 0, 0, 0)
# Execute program
execute(0)
# Print result (should be 120 - factorial of 5)
print "Factorial of 5:", stack_tos("data")
}
function pack_opcodes(op1, op2, op3, op4) {
return op1 + (op2 * 256) + (op3 * 65536) + (op4 * 16777216)
}
|