Skip to content

Commit

Permalink
feat: add option to print last returned expression
Browse files Browse the repository at this point in the history
  • Loading branch information
LyonSyonII committed Jun 17, 2024
1 parent c24d26a commit bf0ed64
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 18 deletions.
17 changes: 16 additions & 1 deletion example/src/editor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function setupEditor(input: HTMLTextAreaElement) {
export function setupEditor(input: HTMLTextAreaElement, runButton: HTMLButtonElement) {
input.addEventListener("keydown", (e) => {
switch (e.key) {
case "Tab": {
Expand All @@ -8,6 +8,7 @@ export function setupEditor(input: HTMLTextAreaElement) {
input.setRangeText(" ", start, end, "end");
break;
}

case "Backspace": {
let [start, end] = [input.selectionStart, input.selectionEnd];
if (start !== end) {
Expand All @@ -22,6 +23,20 @@ export function setupEditor(input: HTMLTextAreaElement) {
}
start >= 0 && input.setRangeText("", start, end, "end");
input.dispatchEvent(new Event("input"))
break;
}

case "Enter": {
e.preventDefault();
e.stopPropagation();
if (e.ctrlKey) {
runButton.click();
} else {
// TODO: Add indentation based on previous line
input.setRangeText("\n" + " ".repeat(0), input.selectionStart, input.selectionEnd, "end");
}
input.dispatchEvent(new Event("input"));
break;
}
}
})
Expand Down
4 changes: 2 additions & 2 deletions example/src/interpreter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ export class Interpreter {
*
* @param code Code that will be interpreted.
*/
public run(code: string) {
public run(code: string, printLast: boolean = false) {
for (const ev of this.onrun) {
ev()
}
this.worker.postMessage(code);
this.worker.postMessage({code, printLast});
}

/**
Expand Down
16 changes: 14 additions & 2 deletions example/src/interpreter/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,17 @@ class Interpreter {
this.next_thread_id = 1;
}

async run(code: string): Promise<string> {
async run(code: string, printLast: boolean = false): Promise<string> {
this.stdin.clear();
this.stdout.clear();
this.stderr.clear();

// Set the contents of the `main.rs` file to the new code
this.fds[5].dir.get_file("main.rs")!.data = new TextEncoder().encode(`fn main() {\n${code}\n}`);
code = `let _code = (|| {\n${code}\n})();`;
if (printLast) {
code += '\nif std::any::Any::type_id(&_code) != std::any::TypeId::of::<()>() { println!("{_code:?}") }';
}
this.fds[5].dir.get_file("main.rs")!.data = encode(`fn main() {\n${code}\n}`);

// Instantiate Miri
const inst = await WebAssembly.instantiate(this.miri, {
Expand Down Expand Up @@ -219,4 +223,12 @@ async function buildSysroot(): Promise<PreopenDirectory> {
])],
])],
])
}

function encode(text: string): Uint8Array {
return new TextEncoder().encode(text);
}

function file(name: string, text: string): [string, File] {
return [name, new File(encode(text))]
}
7 changes: 5 additions & 2 deletions example/src/interpreter/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import { initInterpreter } from "./interpreter";

// When code is received run it
addEventListener("message", async (event) => {
const code = event.data;
const result = await interpreter.run(code);
const {
code,
printLast
} = event.data;
const result = await interpreter.run(code, printLast);
postMessage({ result });
});

Expand Down
26 changes: 15 additions & 11 deletions example/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const base = import.meta.env.BASE_URL === "/" ? "" : import.meta.env.BASE_URL;
<div id="live-edit-wrapper">
<input id="live-edit" type="checkbox" checked />
<label for="live-edit">Live Edit</label>
<input id="print-last" type="checkbox" checked />
<label for="print-last">Print last expression</label>
</div>
<textarea id="input" spellcheck="false" />
<button>RUN</button>
Expand Down Expand Up @@ -69,8 +71,9 @@ const base = import.meta.env.BASE_URL === "/" ? "" : import.meta.env.BASE_URL;
import { AnsiUp } from "ansi_up";

const input = document.body.querySelector<HTMLTextAreaElement>("textarea#input")!;
const button = document.body.querySelector<HTMLButtonElement>("button")!;
const runButton = document.body.querySelector<HTMLButtonElement>("button")!;
const liveEdit = document.body.querySelector<HTMLInputElement>("#live-edit")!;
const printLast = document.body.querySelector<HTMLInputElement>("#print-last")!;
const termElement = document.getElementById("terminal")!;

const ansiUp = new AnsiUp();
Expand All @@ -89,38 +92,39 @@ const base = import.meta.env.BASE_URL === "/" ? "" : import.meta.env.BASE_URL;
interpreter.onLoaded(() => {
input.readOnly = false;
input.value = 'println!("Hello from WASM!");';
interpreter.run(input.value);
runButton.click();
// interpreter.run(input.value);
});

// When Interpreter is running disable the "Run" button
interpreter.onRun(() => {
button.disabled = true;
runButton.disabled = true;
termElement.innerHTML = "Running...";
});

// When result is received from a running Interpreter write it to the terminal
interpreter.onResult(result => {
termElement.innerHTML = ansiUp.ansi_to_html(result.replaceAll("\n", "\r"));
button.disabled = false;
runButton.disabled = false;
if (lastInput && lastInput !== input.value) {
input.dispatchEvent(new Event("input"));
}
});

setupEditor(input);
setupEditor(input, runButton);

// Run the Interpreter when on "Live Edit" or the "Run" button is clicked
input.addEventListener("input", async () => {
if (!liveEdit.checked || button.disabled) {
if (!liveEdit.checked || runButton.disabled) {
return;
}
lastInput = input.value;
interpreter.run(input.value || "");
interpreter.run(input.value || "", printLast.checked);
});
button.addEventListener("click", async () => {
if (button.disabled) {
runButton.addEventListener("click", async () => {
if (runButton.disabled) {
return;
}
interpreter.run(input.value || "");
interpreter.run(input.value || "", printLast.checked)
});
</script>

0 comments on commit bf0ed64

Please sign in to comment.