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 12 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 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
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.

23 changes: 23 additions & 0 deletions projects/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import * as project_02 from "./project_02/index.js";
import * as project_03 from "./project_03/index.js";
import * as project_04 from "./project_04/index.js";
import * as project_05 from "./project_05/index.js";
import * as project_07 from "./project_07/index.js";
import * as project_08 from "./project_08/index.js";

/**
* Duplicated for web from node:path.
Expand Down Expand Up @@ -32,6 +34,11 @@ export const ChipProjects = {
"05": project_05,
};

export const VmProjects = {
"07": project_07,
"08": project_08,
};

let reset = false;
export const resetFiles = async (fs: FileSystem) => {
if (reset) return; // React will double-render a call to resetFiles in useEffect.
Expand All @@ -41,6 +48,8 @@ export const resetFiles = async (fs: FileSystem) => {
await project_03.resetFiles(fs);
await project_04.resetFiles(fs);
await project_05.resetFiles(fs);
await project_07.resetFiles(fs);
await project_08.resetFiles(fs);
reset = false;
};

Expand Down Expand Up @@ -102,9 +111,23 @@ export const ASM_PROJECTS: Record<"06", string[]> = {
"06": ["Add", "Max", "Rectangle", "Pong"],
};

export const VM_PROJECTS: Record<"07" | "08", string[]> = {
"07": ["SimpleAdd", "StackTest", "BasicTest", "PointerTest", "StaticTest"],
"08": [
"BasicLoop",
"FibonacciSeries",
"SimpleFunction",
"NestedCall",
"FibonacciElement",
"StaticsTest",
],
};

export const Assignments = {
...project_01.CHIPS,
...project_02.CHIPS,
...project_03.CHIPS,
...project_05.CHIPS,
...project_07.VMS,
...project_08.VMS,
};
14 changes: 14 additions & 0 deletions projects/src/project_05/make_samples.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/bin/bash

# write FileName.ts varname SourceFile

function write () {
echo -n "export const $2 = \`" >> $1
cat $3 >> $1
echo "\`;\n\n" >> $1
}

# write_all ts_name ProjName
function write_all() {
for e in vm vm_tst hdl_tst cmp ; do write $1 $e $2.$e ; done
}
Loading
Loading