Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion projects/src/samples/vm/vm.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const SIMPLE_FUNCTION = `
export const BRANCHING_FUNCTION = `
// __implicit
push constant 3
push constant 4
Expand Down
28 changes: 18 additions & 10 deletions simulator/src/vm/vm.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { unwrap } from "@davidsouther/jiffies/lib/esm/result.js";
import { vm as SIMPLE_FUNCTION } from "@nand2tetris/projects/project_08/20_simple_function.js";
import { FIBONACCI } from "@nand2tetris/projects/samples/vm/fibonnaci.js";
import {
BRANCHING_FUNCTION,
NESTED_FUNCTION,
SIMPLE_FUNCTION,
STATIC,
} from "@nand2tetris/projects/samples/vm/vm.js";
import { VM } from "../languages/vm.js";
Expand Down Expand Up @@ -207,6 +208,20 @@ test("07 / Memory Access / Pointer Test", () => {
expect(test).toEqual([6084, 3030, 3040, 32, 46]);
});

test("08 / Branching Function", () => {
const { instructions } = unwrap(VM.parse(BRANCHING_FUNCTION));
const vm = unwrap(Vm.build(instructions));

vm.write([]);

for (let i = 0; i < 100; i++) {
vm.step();
}

const test = vm.read([0, 256]);
expect(test).toEqual([257, 12]);
});

const LOOP_TEST = `
push constant 0
pop local 0 // initializes sum = 0
Expand Down Expand Up @@ -309,18 +324,11 @@ test("08 / Program Flow / Fibonacci Series", () => {
expect(test).toEqual([0, 1, 1, 2, 3, 5]);
});

test("08 / Simple Function / Simple Function", () => {
test("08 / Functions / SimpleFunction", () => {
const { instructions } = unwrap(VM.parse(SIMPLE_FUNCTION));
const vm = unwrap(Vm.build(instructions));

vm.write([]);

for (let i = 0; i < 100; i++) {
vm.step();
}

const test = vm.read([0, 256]);
expect(test).toEqual([257, 12]);
expect(() => vm.vmStack()).not.toThrow("Assertion failed");
});

test("08 / Functions / NestedCall", () => {
Expand Down
8 changes: 6 additions & 2 deletions simulator/src/vm/vm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,7 @@ export class Vm {
const nArg = this.segmentInitializations["argument"].n;
const nLocal = this.segmentInitializations["local"].n;
const nThis = this.invocation.thisN ?? 0;
const stackCount = frameEnd - stackBase;
return {
fn,
args: {
Expand All @@ -861,8 +862,11 @@ export class Vm {
},
stack: {
base: 256,
count: frameEnd - stackBase,
values: [...this.memory.map((_, v) => v, stackBase, frameEnd)],
count: Math.max(0, stackCount),
values:
stackCount > 0
? [...this.memory.map((_, v) => v, stackBase, frameEnd)]
: [],
},
this: {
base: THIS,
Expand Down