Skip to content

Commit

Permalink
Merge branch 'main' into pvm-select
Browse files Browse the repository at this point in the history
  • Loading branch information
wkwiatek committed Oct 28, 2024
2 parents eb1d95b + 2faab7d commit 3d06960
Show file tree
Hide file tree
Showing 19 changed files with 307 additions and 137 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ module.exports = {
plugins: ["react-refresh"],
rules: {
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
"no-console": ["warn", { allow: ["warn", "error"] }],
},
};
13 changes: 13 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"react-json-view-compare": "^2.0.2",
"react-katex": "^3.0.1",
"react-redux": "^9.1.2",
"react-toastify": "^10.0.6",
"scale-codec": "^0.13.0",
"tailwind-merge": "^2.4.0",
"tailwindcss-animate": "^1.0.7",
Expand Down
18 changes: 11 additions & 7 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import "./App.css";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import { Button } from "@/components/ui/button";
import { useCallback, useEffect, useRef } from "react";
import { Instructions } from "./components/Instructions";
Expand Down Expand Up @@ -51,6 +54,7 @@ import {
setPvmInitialized,
} from "@/store/debugger/debuggerSlice.ts";
import { MemoryPreview } from "@/components/MemoryPreview";
import { logger } from "./utils/loggerService";

function App() {
const {
Expand Down Expand Up @@ -131,12 +135,12 @@ function App() {

try {
const result = disassemblify(new Uint8Array(newProgram));
console.info("Disassembly result:", result);
logger.info("Disassembly result:", result);
dispatch(setProgramPreviewResult(result));
dispatch(setAllWorkersCurrentInstruction(result?.[0]));
dispatch(setPvmInitialized(true));
} catch (e) {
console.log("Error disassembling program", e);
console.error("Error disassembling program", e);
}
},
[dispatch],
Expand Down Expand Up @@ -206,7 +210,7 @@ function App() {
};

const handlePvmTypeChange = async (selectedPvms: SelectedPvmWithPayload[]) => {
console.log("selectedPvms vs workers ", selectedPvms, workers);
logger.debug("selectedPvms vs workers ", selectedPvms, workers);

await Promise.all(
workers.map((worker: WorkerState) => {
Expand All @@ -216,13 +220,13 @@ function App() {

await Promise.all(
selectedPvms.map(async ({ id, type, params }) => {
console.log("Selected PVM type", id, type, params);
logger.info("Selected PVM type", id, type, params);

if (workers.find((worker: WorkerState) => worker.id === id)) {
console.log("Worker already initialized");
logger.info("Worker already initialized");
// TODO: for now just initialize the worker one more time
}
console.log("Worker not initialized");
logger.info("Worker not initialized");

if (id === AvailablePvms.POLKAVM) {
await dispatch(createWorker(AvailablePvms.POLKAVM)).unwrap();
Expand All @@ -246,7 +250,6 @@ function App() {
}),
).unwrap();
} else if (type === AvailablePvms.WASM_FILE) {
console.log("go wasm file!", id, type, params);
await dispatch(createWorker(id)).unwrap();
await dispatch(
loadWorker({
Expand Down Expand Up @@ -419,6 +422,7 @@ function App() {
</div>
</div>
</div>
<ToastContainer />
</>
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/KnowledgeBase/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const KnowledgeBase = ({ currentInstruction }: { currentInstruction: Curr
<div key={i}>
<p className="font-mono font-bold uppercase my-3">{instruction?.name}</p>
<div className="text-left">
<BlockMath math={currentInstructionFromKnowledgeBase?.latex as string} />
<BlockMath math={currentInstructionFromKnowledgeBase?.latex || ""} />
</div>
<p className="my-3">{currentInstructionFromKnowledgeBase?.description}</p>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/components/ProgramLoader/Assembly.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export const Assembly = ({
return;
}
}
console.log(e);
console.error(e);
onProgramLoad(undefined);
setError(`${e}`);
}
Expand Down
5 changes: 3 additions & 2 deletions src/components/ProgramTextLoader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const ProgramTextLoader = ({
setProgram(Array.prototype.slice.call(parsedBlob.buffer));
} catch (e) {
console.warn(e);
console.log("wrong binary file");
console.error("wrong binary file");
setIsInvalidProgram(true);
}
} else {
Expand All @@ -36,7 +36,8 @@ export const ProgramTextLoader = ({
setProgram(JSON.parse(newInput));
setIsInvalidProgram(false);
} catch (e) {
console.log("wrong json");
// TODO only validate on submit
console.error("wrong json");
setIsInvalidProgram(true);
setProgram();
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/PvmSelect/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const fetchWasmMetadata = async (url: string): Promise<WasmMetadata | undefined>
alert("Invalid URL");
}
} catch (error) {
console.log(error);
console.error(error);
alert("Invalid URL");
}
return;
Expand Down
5 changes: 2 additions & 3 deletions src/context/NumeralSystemProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { NumeralSystem } from "./NumeralSystem";

export const NumeralSystemContext = createContext({
numeralSystem: NumeralSystem.DECIMAL,
setNumeralSystem: (numeralSystem: NumeralSystem) => {
console.log(numeralSystem);
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setNumeralSystem: (_: NumeralSystem) => {},
});

export const NumeralSystemProvider = ({ children }: { children: ReactNode }) => {
Expand Down
2 changes: 2 additions & 0 deletions src/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;

--toastify-toast-width: 350px;
}

.dark {
Expand Down
9 changes: 9 additions & 0 deletions src/packages/web-worker/command-handlers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { runInit } from "./init";
import { runLoad } from "./load";
import { runStep } from "./step";

export default {
runInit,
runLoad,
runStep,
};
59 changes: 59 additions & 0 deletions src/packages/web-worker/command-handlers/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { InitialState } from "@/types/pvm";
import { initPvm } from "../pvm";
import { getState, isInternalPvm, regsAsUint8 } from "../utils";
import { CommandStatus, PvmApiInterface } from "../worker";
import { Pvm as InternalPvmInstance } from "@typeberry/pvm-debugger-adapter";
import { logger } from "@/utils/loggerService";

export type InitParams = {
pvm: PvmApiInterface | null;
program: Uint8Array;
initialState: InitialState;
};
export type InitResponse = {
initialState: InitialState;
status: CommandStatus;
error?: unknown;
};

const init = async ({ pvm, program, initialState }: InitParams) => {
if (!pvm) {
throw new Error("PVM is uninitialized.");
}
if (isInternalPvm(pvm)) {
logger.info("PVM init internal", pvm);
// TODO Fix type guards
initPvm(pvm as InternalPvmInstance, program, initialState);
} else {
logger.info("PVM init external", pvm);
const gas = initialState.gas || 10000;
pvm.reset(program, regsAsUint8(initialState.regs), BigInt(gas));
pvm.setNextProgramCounter(initialState.pc ?? 0);
pvm.setGasLeft(BigInt(gas));
}
};

export const runInit = async ({ pvm, program, initialState }: InitParams): Promise<InitResponse> => {
if (program.length === 0) {
console.warn("Skipping init, no program yet.");
return {
status: CommandStatus.SUCCESS,
initialState: {},
};
}

try {
await init({ pvm, program, initialState });

return {
status: CommandStatus.SUCCESS,
initialState: pvm ? getState(pvm) : {},
};
} catch (error) {
return {
status: CommandStatus.ERROR,
error,
initialState: pvm ? getState(pvm) : {},
};
}
};
50 changes: 50 additions & 0 deletions src/packages/web-worker/command-handlers/load.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { logger } from "@/utils/loggerService";
import { loadArrayBufferAsWasm, SupportedLangs } from "../utils";
import { CommandStatus, PvmApiInterface, PvmTypes } from "../worker";
import { Pvm as InternalPvmInstance } from "@typeberry/pvm-debugger-adapter";

export type LoadParams = { type: PvmTypes; params: { url?: string; file?: Blob; lang?: SupportedLangs } };
export type LoadResponse = { pvm: PvmApiInterface | null; status: CommandStatus; error?: unknown };

const load = async (args: LoadParams): Promise<PvmApiInterface | null> => {
if (args.type === PvmTypes.BUILT_IN) {
return new InternalPvmInstance();
} else if (args.type === PvmTypes.WASM_FILE) {
const file = args.params.file;
if (!file) {
throw new Error("No PVM file");
}

logger.info("Load WASM from file", file);
const bytes = await file.arrayBuffer();
return await loadArrayBufferAsWasm(bytes);
} else if (args.type === PvmTypes.WASM_URL) {
const url = args.params.url ?? "";
const isValidUrl = Boolean(new URL(url));

if (!isValidUrl) {
throw new Error("Invalid PVM URL");
}

logger.info("Load WASM from URL", url);
const response = await fetch(url);
const bytes = await response.arrayBuffer();

return await loadArrayBufferAsWasm(bytes, args.params.lang);
}

return null;
};

export const runLoad = async (args: LoadParams): Promise<LoadResponse> => {
try {
const pvm = await load(args);
if (pvm) {
return { pvm, status: CommandStatus.SUCCESS };
}
} catch (error) {
return { pvm: null, status: CommandStatus.ERROR, error };
}

return { pvm: null, status: CommandStatus.ERROR, error: new Error("Unknown PVM type") };
};
40 changes: 40 additions & 0 deletions src/packages/web-worker/command-handlers/step.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { CurrentInstruction, ExpectedState, Status } from "@/types/pvm";
import { nextInstruction } from "../pvm";
import { isInternalPvm, getState } from "../utils";
import { CommandStatus, PvmApiInterface } from "../worker";

export type StepParams = { program: number[]; pvm: PvmApiInterface | null };
export type StepResponse = {
status: CommandStatus;
error?: unknown;
result: CurrentInstruction | object;
state: ExpectedState;
isFinished: boolean;
};

const step = ({ pvm, program }: StepParams) => {
if (!pvm) {
throw new Error("PVM is uninitialized.");
}

let isFinished: boolean;
if (isInternalPvm(pvm)) {
isFinished = pvm.nextStep() !== Status.OK;
} else {
isFinished = !pvm.nextStep();
}

const state = getState(pvm);
const result = nextInstruction(state.pc ?? 0, program) as unknown as CurrentInstruction;

return { result, state, isFinished };
};

export const runStep = ({ pvm, program }: StepParams): StepResponse => {
try {
const data = step({ pvm, program });
return { status: CommandStatus.SUCCESS, ...data };
} catch (error) {
return { status: CommandStatus.ERROR, error, isFinished: true, result: {}, state: {} };
}
};
3 changes: 1 addition & 2 deletions src/packages/web-worker/pvm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createResults, instructionArgumentTypeMap, ProgramDecoder } from "@type
import { ArgsDecoder, Registers } from "@typeberry/pvm-debugger-adapter";
import { byteToOpCodeMap } from "../../packages/pvm/pvm/assemblify";
import { Pvm as InternalPvmInstance, MemoryBuilder as InternalPvmMemoryBuilder } from "@typeberry/pvm-debugger-adapter";
export const initPvm = (pvm: InternalPvmInstance, program: number[], initialState: InitialState) => {
export const initPvm = (pvm: InternalPvmInstance, program: Uint8Array, initialState: InitialState) => {
const initialMemory = initialState.memory ?? [];
const pageMap = initialState.pageMap ?? [];

Expand Down Expand Up @@ -32,7 +32,6 @@ export const initPvm = (pvm: InternalPvmInstance, program: number[], initialStat
const registers = new Registers();
registers.copyFrom(new Uint32Array(initialState.regs!));
pvm.reset(new Uint8Array(program), initialState.pc ?? 0, initialState.gas ?? 0, registers, memory);
return pvm;
};

export const runAllInstructions = (pvm: InternalPvm, program: number[]) => {
Expand Down
7 changes: 3 additions & 4 deletions src/packages/web-worker/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { createWasmPvmShell } from "@/packages/web-worker/wasmPvmShell.ts";
import "./goWasmExec.js";
import "./goWasmExec.d.ts";
import { createGoWasmPvmShell } from "@/packages/web-worker/wasmGoPvmShell.ts";
import { logger } from "@/utils/loggerService.tsx";

export enum SupportedLangs {
Go = "Go",
Expand Down Expand Up @@ -66,28 +67,26 @@ export async function loadArrayBufferAsWasm(bytes: ArrayBuffer, lang?: Supported
const go = new Go();
const wasmModule = await WebAssembly.instantiate(bytes, go.importObject);
go.run(wasmModule.instance);
console.log("Go WASM module loaded", wasmModule.instance.exports);
logger.info("Go WASM module loaded", wasmModule.instance.exports);
const wasmPvmShell = createGoWasmPvmShell();
wasmPvmShell.__wbg_set_wasm(wasmModule.instance.exports);
return wasmPvmShell;
} else {
const wasmModule = await WebAssembly.instantiate(bytes, {});
console.log("Rust WASM module loaded", wasmModule.instance.exports);
logger.info("Rust WASM module loaded", wasmModule.instance.exports);
const wasmPvmShell = createWasmPvmShell();
wasmPvmShell.__wbg_set_wasm(wasmModule.instance.exports);
return wasmPvmShell;
}
}

export function getMemoryPage(pageNumber: number, pvm: PvmApiInterface | null) {
console.log("getMemoryPage", pageNumber, pvm);
if (!pvm) {
return [];
}

if (isInternalPvm(pvm)) {
return pvm.getMemoryPage(pageNumber) || [];
}
console.log("getpagedump", pageNumber, pvm.getPageDump(pageNumber));
return pvm.getPageDump(pageNumber) || [];
}
Loading

0 comments on commit 3d06960

Please sign in to comment.