nothing's falsity can unwind the unwary

This commit is contained in:
mehbark 2023-04-17 16:44:10 -04:00
parent 4cb13e0a16
commit 855e55bff7

View file

@ -246,7 +246,6 @@ function parse_op(op: string): Option<Op> {
case "swp": case "swp":
return op; return op;
} }
console.log(op);
} }
type State = { type State = {
@ -262,7 +261,7 @@ const INITIAL_STATE: State = {
}; };
function steps(state: State, ops: Op[], limit = 300, num_steps = 0): State[] { function steps(state: State, ops: Op[], limit = 300, num_steps = 0): State[] {
if (!ops[state.ip] || num_steps > limit) { if (typeof ops[state.ip] == "undefined" || num_steps > limit) {
return [state]; return [state];
} }
return cons( return cons(
@ -288,55 +287,56 @@ function step(state: State, op: Op): State {
if (typeof op == "number") { if (typeof op == "number") {
ns.stack.push(op); ns.stack.push(op);
} else { return ns;
switch (op) { }
case "add":
binary_op(0, 0, (a, b) => a + b); switch (op) {
break; case "add":
case "sub": binary_op(0, 0, (a, b) => a + b);
binary_op(0, 0, (a, b) => a - b); break;
break; case "sub":
case "mul": binary_op(0, 0, (a, b) => a - b);
binary_op(0, 1, (a, b) => a * b); break;
break; case "mul":
case "div": binary_op(0, 1, (a, b) => a * b);
binary_op(0, 1, (a, b) => a / b); break;
break; case "div":
case "put": { binary_op(0, 1, (a, b) => a / b);
let popped = ns.stack.pop(); break;
if (typeof popped != "undefined") { case "put": {
ns.output.push(popped); let popped = ns.stack.pop();
} if (typeof popped != "undefined") {
break; ns.output.push(popped);
} }
case "jmp": break;
ns.ip--; }
ns.ip += ns.stack.pop() ?? 1; case "jmp":
break; ns.ip--;
case "dup": { ns.ip += ns.stack.pop() ?? 1;
let popped = ns.stack.pop(); break;
if (typeof popped != "undefined") { case "dup": {
ns.stack.push(popped, popped); let popped = ns.stack.pop();
} if (typeof popped != "undefined") {
break; ns.stack.push(popped, popped);
} }
case "del": break;
ns.stack.pop(); }
break; case "del":
case "cmp": { ns.stack.pop();
let [a, b] = [ns.stack.pop() ?? 0, ns.stack.pop() ?? 0]; break;
// matter of taste case "cmp": {
ns.stack.push(cmp(b, a)); let [a, b] = [ns.stack.pop() ?? 0, ns.stack.pop() ?? 0];
break; // matter of taste
} ns.stack.push(cmp(b, a));
case "swp": { break;
let [a, b] = [ns.stack.pop(), ns.stack.pop()]; }
if (typeof a == "undefined" || typeof b == "undefined") { case "swp": {
break; let [a, b] = [ns.stack.pop(), ns.stack.pop()];
} if (typeof a == "undefined" || typeof b == "undefined") {
ns.stack.push(a, b);
break; break;
} }
ns.stack.push(a, b);
break;
} }
} }