#!/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) }