Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VM sim & Page #200

Merged
merged 14 commits into from
Dec 18, 2023
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
19 changes: 13 additions & 6 deletions components/src/stores/asm.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,11 @@ class Translator {
this.lineNumbers = Array(lineNum);
let currentLine = 0;
for (const instruction of this.asm.instructions) {
if (instruction.type === "A" || instruction.type === "C") {
this.lineNumbers[instruction.lineNum] = currentLine;
if (
(instruction.type === "A" || instruction.type === "C") &&
instruction.span != undefined
) {
this.lineNumbers[instruction.span.line] = currentLine;
currentLine += 1;
}
}
Expand All @@ -101,12 +104,15 @@ class Translator {
highlightInfo.resultHighlight = {
start: this.current * 17,
end: (this.current + 1) * 17,
line: -1,
};

highlightInfo.highlightMap.set(
instruction.span,
highlightInfo.resultHighlight
);
if (highlightInfo.sourceHighlight) {
highlightInfo.highlightMap.set(
highlightInfo.sourceHighlight,
highlightInfo.resultHighlight
);
}

if (isAValueInstruction(instruction)) {
const variable = this.variables.get(instruction.value);
Expand Down Expand Up @@ -223,6 +229,7 @@ export function makeAsmStore(
state.resultHighlight = {
start: i * 17,
end: (i + 1) * 17,
line: -1,
};
return;
}
Expand Down
12 changes: 10 additions & 2 deletions components/src/stores/chip.store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,11 @@ describe("ChipStore", () => {

it("starts the cursor on the first instruction", () => {
expect(state.store.state.files.tst).toBe(not.tst);
expect(state.store.state.controls.span).toEqual({ start: 0, end: 33 });
expect(state.store.state.controls.span).toEqual({
start: 0,
end: 33,
line: 1,
});
});

it("leaves the cursor on the final character", async () => {
Expand All @@ -174,7 +178,11 @@ describe("ChipStore", () => {
// Past the end of the test
await state.store.actions.stepTest();

expect(state.store.state.controls.span).toEqual({ start: 81, end: 82 });
expect(state.store.state.controls.span).toEqual({
start: 81,
end: 82,
line: 4,
});
});
});
});
3 changes: 2 additions & 1 deletion components/src/stores/chip.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
CHIP_PROJECTS,
ChipProjects,
} from "@nand2tetris/projects/index.js";
import { ChipTest } from "@nand2tetris/simulator/tst.js";
import { ChipTest } from "@nand2tetris/simulator/test/chiptst.js";

import { ImmPin, reducePins } from "../pinout.js";
import { useImmerReducer } from "../react.js";
Expand Down Expand Up @@ -260,6 +260,7 @@ export function makeChipStore(
state.controls.span = {
start: end - 1,
end,
line: state.files.tst.split("\n").length,
};
}
}
Expand Down
18 changes: 2 additions & 16 deletions components/src/stores/cpu.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import {
MemoryAdapter,
MemoryKeyboard,
ROM,
SubMemory,
} from "@nand2tetris/simulator/cpu/memory.js";
import { Span } from "@nand2tetris/simulator/languages/base.js";
import { TST } from "@nand2tetris/simulator/languages/tst.js";
import { HACK } from "@nand2tetris/simulator/testing/mult.js";
import { CPUTest } from "@nand2tetris/simulator/tst.js";
import { CPUTest } from "@nand2tetris/simulator/test/cputst.js";
import { Dispatch, MutableRefObject, useContext, useMemo, useRef } from "react";
import { compare } from "../compare.js";
import { useImmerReducer } from "../react.js";
import { BaseContext } from "./base.context.js";
import { ImmMemory } from "./imm_memory.js";

function makeTst() {
return `repeat {
Expand Down Expand Up @@ -44,20 +44,6 @@ export interface CpuPageState {
test: CPUTestSim;
}

class ImmMemory extends SubMemory {
constructor(
parent: MemoryAdapter,
private dispatch: MutableRefObject<CpuStoreDispatch>
) {
super(parent, parent.size, 0);
}

override async load(fs: FileSystem, path: string): Promise<void> {
await super.load(fs, path);
this.dispatch.current({ action: "update" });
}
}

function reduceCPUTest(
cpuTest: CPUTest,
dispatch: MutableRefObject<CpuStoreDispatch>
Expand Down
20 changes: 20 additions & 0 deletions components/src/stores/imm_memory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { FileSystem } from "@davidsouther/jiffies/lib/esm/fs.js";
import { MemoryAdapter, SubMemory } from "@nand2tetris/simulator/cpu/memory.js";
import { MutableRefObject } from "react";

export class ImmMemory<
Action extends { action: "update" },
Dispatch extends (a: Action) => void
> extends SubMemory {
constructor(
parent: MemoryAdapter,
private dispatch: MutableRefObject<Dispatch>
) {
super(parent, parent.size, 0);
}

override async load(fs: FileSystem, path: string): Promise<void> {
await super.load(fs, path);
this.dispatch.current({ action: "update" } as Action);
}
}
135 changes: 135 additions & 0 deletions components/src/stores/vm.store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { FileSystem } from "@davidsouther/jiffies/lib/esm/fs.js";
// import { VM as multVM } from "@nand2tetris/simulator/testing/mult.js";
import { FIBONACCI } from "@nand2tetris/projects/samples/vm.js";
import { Dispatch, MutableRefObject, useContext, useMemo, useRef } from "react";
import { BaseContext } from "./base.context.js";
import { useImmerReducer } from "../react.js";
import {
KeyboardAdapter,
MemoryAdapter,
MemoryKeyboard,
} from "@nand2tetris/simulator/cpu/memory.js";
import { VMTest } from "@nand2tetris/simulator/test/vmtst.js";
import { VM, VmInstruction } from "@nand2tetris/simulator/languages/vm.js";
import { ImmMemory } from "./imm_memory.js";
import { unwrap } from "@davidsouther/jiffies/lib/esm/result.js";
import { VmFrame, Vm } from "@nand2tetris/simulator/vm/vm.js";
import { Span } from "@nand2tetris/simulator/languages/base.js";

export interface VmSim {
RAM: MemoryAdapter;
Screen: MemoryAdapter;
Keyboard: KeyboardAdapter;
Stack: VmFrame[];
Prog: VmInstruction[];
highlight: number;
}

export interface VMTestSim {
useTest: boolean;
highlight: Span | undefined;
}

export interface VmPageState {
vm: VmSim;
controls: ControlsState;
test: VMTestSim;
}

export interface ControlsState {
runningTest: boolean;
error: string;
}

export type VmStoreDispatch = Dispatch<{
action: keyof ReturnType<typeof makeVmStore>["reducers"];
payload?: unknown;
}>;

function reduceVMTest(
vmTest: VMTest,
dispatch: MutableRefObject<VmStoreDispatch>
): VmSim {
const RAM = new ImmMemory(vmTest.vm.RAM, dispatch);
const Screen = new ImmMemory(vmTest.vm.Screen, dispatch);
const Keyboard = new MemoryKeyboard(
new ImmMemory(vmTest.vm.Keyboard, dispatch)
);
const highlight = vmTest.vm.derivedLine();

return {
Keyboard,
RAM,
Screen,
Stack: vmTest.vm.vmStack().reverse(),
Prog: vmTest.vm.program,
highlight,
};
}

export function makeVmStore(
fs: FileSystem,
setStatus: (status: string) => void,
storage: Record<string, string>,
dispatch: MutableRefObject<VmStoreDispatch>
) {
const parsed = unwrap(VM.parse(FIBONACCI));
const vm = unwrap(Vm.build(parsed.instructions));
const test = new VMTest().with(vm);
let useTest = false;
const reducers = {
update(state: VmPageState) {
state.vm = reduceVMTest(test, dispatch);
state.test.useTest = useTest;
state.test.highlight = test.currentStep?.span;
},
};
const initialState: VmPageState = {
vm: reduceVMTest(test, dispatch),
controls: {
error: "",
runningTest: false,
},
test: {
useTest,
highlight: undefined,
},
};
const actions = {
step() {
if (useTest) {
test.step();
} else {
vm.step();
}
dispatch.current({ action: "update" });
},
reset() {
test.reset();
vm.reset();
dispatch.current({ action: "update" });
},
toggleUseTest() {
useTest = !useTest;
dispatch.current({ action: "update" });
},
};

return { initialState, reducers, actions };
}

export function useVmPageStore() {
const { fs, setStatus, storage } = useContext(BaseContext);

const dispatch = useRef<VmStoreDispatch>(() => undefined);

const { initialState, reducers, actions } = useMemo(
() => makeVmStore(fs, setStatus, storage, dispatch),
[fs, setStatus, storage, dispatch]
);

const [state, dispatcher] = useImmerReducer(reducers, initialState);
dispatch.current = dispatcher;

return { state, dispatch, actions };
}
2 changes: 1 addition & 1 deletion extension/src/commands/hardware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export async function hardware(fileUri: string) {
// The await eval() hack is for https://github.com/microsoft/TypeScript/issues/43329
const tst = await import("@nand2tetris/simulator/tst.js");
const tst = await import("@nand2tetris/simulator/test/chiptst.js");
console.log(`Hardware for ${fileUri}`);
console.log(new tst.ChipTest());
}
28 changes: 28 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading