improve REPL feedback.
This commit is contained in:
parent
1df9eda02a
commit
29ea9dd356
81
src/repl.mjs
81
src/repl.mjs
|
@ -1,29 +1,72 @@
|
|||
import Line from "./Line.mjs";
|
||||
import Expr from "./Expr.mjs";
|
||||
|
||||
import { parse_line } from "./parse.mjs";
|
||||
import { compile_line } from "./compile.mjs";
|
||||
import { execute } from "./execute.mjs";
|
||||
|
||||
import readline from "node:readline";
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
|
||||
|
||||
let running = true;
|
||||
|
||||
let env = new Map();
|
||||
|
||||
function print (str) {
|
||||
console.log(str);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const specials = new Map();
|
||||
|
||||
specials.set("!.exit", _ => running = false);
|
||||
|
||||
specials.set("!.env", _ => {
|
||||
print(env);
|
||||
});
|
||||
|
||||
|
||||
|
||||
function run (line) {
|
||||
if (specials.has(line)) {
|
||||
specials.get(line)();
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = parse_line(line);
|
||||
const type = parsed.type;
|
||||
|
||||
const compiled = compile_line(env, parsed);
|
||||
|
||||
if (!compiled.valid) {
|
||||
console.log("invalid line!");
|
||||
print("invalid line!");
|
||||
return;
|
||||
}
|
||||
|
||||
env = compiled.env;
|
||||
|
||||
if (type === Line.Expression) {
|
||||
console.log(prettify(evaluate(compiled.value)));
|
||||
const expr_type = parsed.value.type;
|
||||
|
||||
if (expr_type === Expr.Token || expr_type === Expr.Fn) {
|
||||
print(prettify(compiled.value));
|
||||
} else if (expr_type === Expr.Application) {
|
||||
const result = evaluate(compiled.value);
|
||||
if (typeof result === "function") {
|
||||
print(prettify(compiled.value));
|
||||
} else {
|
||||
print(prettify(result));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log(env);
|
||||
print(parsed.name + " = " + prettify(compiled.fn));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -32,14 +75,30 @@ function evaluate (fn) {
|
|||
}
|
||||
|
||||
function prettify (code) {
|
||||
if (Array.isArray(code)) {
|
||||
return prettify(code[0]).concat(" ", prettify(code[1]));
|
||||
if (typeof code === "number") {
|
||||
return code.toString();
|
||||
} else if (code[0] === 0) {
|
||||
return "(λ" + prettify(code[1]) + ")";
|
||||
} else {
|
||||
return prettify(code[0]) + " " + prettify(code[1]);
|
||||
}
|
||||
if (code === 0) {
|
||||
return "λ";
|
||||
}
|
||||
return code.toString();
|
||||
}
|
||||
|
||||
run("id = a → a");
|
||||
run("id id");
|
||||
function read (callback) {
|
||||
rl.question("> ", callback);
|
||||
}
|
||||
|
||||
function repl () {
|
||||
read(line => {
|
||||
run(line);
|
||||
if (running) {
|
||||
setImmediate(repl);
|
||||
} else {
|
||||
rl.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
print("welcome to catgirl calculus!");
|
||||
print("uwu");
|
||||
repl();
|
||||
|
|
Loading…
Reference in New Issue