From 6daee2be9e93a180af0aa17f139df4e335fe5e0f Mon Sep 17 00:00:00 2001 From: Terence Parr Date: Tue, 14 Apr 2015 17:14:59 -0700 Subject: [PATCH] add the function that tests the local variable allocation; update CALL so that it allocates space for locals --- src/vm/Test.java | 38 +++++++++++++++++++++++++++++++++++--- src/vm/VM.java | 4 ++-- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/vm/Test.java b/src/vm/Test.java index d23a744..4cc9c7f 100644 --- a/src/vm/Test.java +++ b/src/vm/Test.java @@ -14,6 +14,7 @@ import static vm.Bytecode.LOAD; import static vm.Bytecode.PRINT; import static vm.Bytecode.RET; +import static vm.Bytecode.STORE; public class Test { static int[] hello = { @@ -85,14 +86,45 @@ public class Test { PRINT, // 25 HALT // 26 }; - - static FuncMetaData[] metadata = { + static FuncMetaData[] factorial_metadata = { //.def factorial: ARGS=1, LOCALS=0 ADDRESS new FuncMetaData("factorial", 1, 0, FACTORIAL_ADDRESS) }; + + static int[] f = { + // ADDRESS + //.def main() { print f(10); } + ICONST, 10, // 0 + CALL, 0, // 2 + PRINT, // 4 + HALT, // 5 + //.def f(x): ARGS=1, LOCALS=1 + // a = x; + LOAD, 0, // 6 <-- start of f + STORE, 1, + // return 2*a + LOAD, 1, + ICONST, 2, + IMUL, + RET + }; + static FuncMetaData[] f_metadata = { + //.def factorial: ARGS=1, LOCALS=0 ADDRESS + new FuncMetaData("f", 1, 1, 6) + }; + + public static void main(String[] args) { - VM vm = new VM(factorial, MAIN_ADDRESS, 0, metadata); + VM vm = new VM(factorial, MAIN_ADDRESS, 0, factorial_metadata); + vm.trace = true; + vm.exec(); + + vm = new VM(f, 0, 2, f_metadata); + vm.trace = true; + vm.exec(); + + vm = new VM(loop, 0, 2, null); vm.trace = true; vm.exec(); } diff --git a/src/vm/VM.java b/src/vm/VM.java index e1d58b3..008204c 100644 --- a/src/vm/VM.java +++ b/src/vm/VM.java @@ -140,14 +140,14 @@ protected void cpu() { // expects all args on stack int findex = code[ip++]; // index of target function int nargs = metadata[findex].nargs; // how many args got pushed - callstack[++callsp] = new Context(ip,nargs); + int nlocals = metadata[findex].nlocals; + callstack[++callsp] = new Context(ip,nargs+nlocals); // copy args into new context for (int i=0; i