about summary refs log tree commit diff stats
path: root/awk/retro/test.awk
diff options
context:
space:
mode:
Diffstat (limited to 'awk/retro/test.awk')
-rwxr-xr-xawk/retro/test.awk52
1 files changed, 52 insertions, 0 deletions
diff --git a/awk/retro/test.awk b/awk/retro/test.awk
new file mode 100755
index 0000000..191fa5b
--- /dev/null
+++ b/awk/retro/test.awk
@@ -0,0 +1,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)
+}
\ No newline at end of file