Trim comments to the non-obvious why
Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,25 +1,15 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Route `/automata` — an interactive Turing machine / mobile automaton
|
||||
* simulator, rendered to a <canvas>.
|
||||
*
|
||||
* A machine is described by a transition table: each `delta` line is
|
||||
* "<read>,<write>,<L|R>" over single characters, so the whole configuration is
|
||||
* editable as plain text and shareable. Configuration is kept in localStorage
|
||||
* under STORAGE_KEY.
|
||||
*
|
||||
* The canvas draws colours literally rather than via CSS variables — this is
|
||||
* the one place in the codebase exempt from the "always use a design token"
|
||||
* rule, because canvas has no access to CSS custom properties.
|
||||
* Route `/automata`: a mobile automaton simulator on a <canvas>. Each `delta`
|
||||
* line is "<read>,<write>,<L|R>". Canvas can't read CSS variables, so colours
|
||||
* here are literal.
|
||||
*/
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
|
||||
import InlineLink from "@/components/text/InlineLink.vue";
|
||||
import Header from "@/components/text/Header.vue";
|
||||
import Paragraph from "@/components/text/Paragraph.vue";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Presets
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Presets ----
|
||||
const PRESETS = [
|
||||
{
|
||||
id: "chaos",
|
||||
@@ -59,10 +49,8 @@ const PRESETS = [
|
||||
].join("\n"),
|
||||
},
|
||||
{
|
||||
// The 5-state Busy Beaver champion Turing Machine, converted to a
|
||||
// Mobile Automaton with the construction from the dissertation:
|
||||
// each cell holds (symbol, state-or-κ); lowercase = state over a 0,
|
||||
// uppercase = state over a 1. Halts (after ~47M steps!) on z/Z words.
|
||||
// The 5-state Busy Beaver as a mobile automaton: lowercase = state
|
||||
// over a 0, uppercase = state over a 1. Halts after ~47M steps.
|
||||
id: "busybeaver",
|
||||
name: "Busy Beaver — a 5-state Turing Machine, converted",
|
||||
tape: "a",
|
||||
@@ -125,9 +113,7 @@ const PRESETS = [
|
||||
|
||||
const STORAGE_KEY = "mobile-automata-config";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Editable configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Editable configuration ----
|
||||
const tapeStr = ref(PRESETS[0].tape);
|
||||
const headStr = ref(String(PRESETS[0].head));
|
||||
const blankSym = ref(PRESETS[0].blank);
|
||||
@@ -143,9 +129,7 @@ const derivedF = ref("");
|
||||
|
||||
const errorMsg = ref("");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Machine state
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Machine state ----
|
||||
let machine = null; // { n, delta: Map(word -> [outputChars, dir]), blank, gamma, accepting: Set }
|
||||
let tape = []; // array of single-char symbols
|
||||
let origin = 0; // cell index of tape[0]
|
||||
@@ -157,8 +141,7 @@ const terminated = ref(false);
|
||||
const accepted = ref(false);
|
||||
const speed = ref(55); // slider 0..100, log scale
|
||||
|
||||
// The slider is 0..100 but useful speeds span 1 to ~2000 steps/sec, so map it
|
||||
// logarithmically: 10^(slider*3.3/100) gives 1 at 0 and ~10^3.3 (~2000) at 100.
|
||||
// Logarithmic: slider 0..100 maps to 1..~2000 steps/sec.
|
||||
const stepsPerSecond = computed(() =>
|
||||
Math.max(1, Math.round(10 ** ((speed.value * 3.3) / 100))),
|
||||
);
|
||||
@@ -169,9 +152,7 @@ const statusText = computed(() => {
|
||||
return running.value ? "Running" : "Paused";
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Parsing (same formats as the original simulator)
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Parsing ----
|
||||
function parseDelta(str) {
|
||||
if (str.trim() === "")
|
||||
throw new Error("Transition function cannot be empty");
|
||||
@@ -202,8 +183,7 @@ function parseDelta(str) {
|
||||
return { delta, n };
|
||||
}
|
||||
|
||||
/** Every word of length n over the alphabet `gamma` (|gamma|^n of them) —
|
||||
* used to list the inputs that have NO transition, i.e. the halting words. */
|
||||
/** Every word of length n over `gamma`: the candidate halting words. */
|
||||
function allWords(gamma, n) {
|
||||
let words = [""];
|
||||
for (let i = 0; i < n; i++) {
|
||||
@@ -262,8 +242,7 @@ function loadMachine() {
|
||||
derivedN.value = n;
|
||||
derivedSigma.value = [...sigma].join(",");
|
||||
derivedGamma.value = machine.gamma.join(",");
|
||||
// |gamma|^n halting words: only enumerate when the count is small,
|
||||
// otherwise a wide alphabet would hang the page building the list.
|
||||
// Only when small, or a wide alphabet hangs the page.
|
||||
if (machine.gamma.length ** n <= 4096) {
|
||||
derivedF.value = allWords(machine.gamma, n)
|
||||
.filter((w) => !delta.has(w))
|
||||
@@ -298,16 +277,12 @@ function loadMachine() {
|
||||
}
|
||||
}
|
||||
|
||||
// The tape is conceptually infinite in both directions but stored as a finite
|
||||
// array. `origin` is the absolute cell index of tape[0], so absolute index i
|
||||
// lives at tape[i - origin]; anything outside the array reads as blank.
|
||||
// The tape is unbounded; absolute cell i lives at tape[i - origin].
|
||||
function cellAt(i) {
|
||||
const j = i - origin;
|
||||
return j >= 0 && j < tape.length ? tape[j] : machine.blank;
|
||||
}
|
||||
|
||||
/** Write to absolute cell `i`, growing the tape (and shifting `origin` when
|
||||
* growing leftwards) so the array always covers every written cell. */
|
||||
function setCell(i, v) {
|
||||
let j = i - origin;
|
||||
while (j < 0) {
|
||||
@@ -320,15 +295,9 @@ function setCell(i, v) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one transition: read the n-cell window starting at the head, look it up
|
||||
* in delta, write the output back and move the head one cell.
|
||||
*
|
||||
* No matching transition means the machine halts. Whether that counts as
|
||||
* accepting is decided by the word under the head, not by a separate state —
|
||||
* this is the mobile-automaton formulation, where state is encoded in the tape
|
||||
* symbols themselves (see the Busy Beaver preset above).
|
||||
*
|
||||
* @returns {boolean} true if a step was taken, false if the machine halted.
|
||||
* One transition. No match halts; acceptance is decided by the word under the
|
||||
* head, since state lives in the tape symbols.
|
||||
* @returns {boolean} false if the machine halted.
|
||||
*/
|
||||
function stepMachine() {
|
||||
if (!machine || terminated.value) return false;
|
||||
@@ -348,9 +317,7 @@ function stepMachine() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rendering
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Rendering ----
|
||||
const historyCanvas = ref(null);
|
||||
const tapeCanvas = ref(null);
|
||||
const canvasWrap = ref(null);
|
||||
@@ -370,9 +337,7 @@ const HEAD_COLOR = "#ffffff";
|
||||
|
||||
let colorOf = {};
|
||||
|
||||
// One palette colour per non-blank symbol, assigned in alphabet order and
|
||||
// wrapping round. Blank stays background-coloured so the history plot shows
|
||||
// only the written cells.
|
||||
// Blank stays background-coloured so the plot shows only written cells.
|
||||
function assignColors() {
|
||||
colorOf = {};
|
||||
let k = 0;
|
||||
@@ -391,14 +356,7 @@ let viewLeft = 0;
|
||||
let hctx = null;
|
||||
let tctx = null;
|
||||
|
||||
/**
|
||||
* Size both canvases to the wrapper and clear them.
|
||||
*
|
||||
* Canvas bitmaps are sized in device pixels (cssWidth * devicePixelRatio) so
|
||||
* the drawing is sharp on HiDPI screens; CSS sizes the elements back down.
|
||||
* Every constant below (cell size, 420px history, 56px tape strip) is therefore
|
||||
* multiplied by `dpr`.
|
||||
*/
|
||||
/** Bitmaps are sized in device pixels, so every constant is scaled by `dpr`. */
|
||||
function resetCanvases() {
|
||||
const hc = historyCanvas.value;
|
||||
const tc = tapeCanvas.value;
|
||||
@@ -425,13 +383,8 @@ function resetCanvases() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw one row of the space-time diagram: the tape at this instant, one pixel
|
||||
* block per cell, appended below the previous row.
|
||||
*
|
||||
* History is never re-rendered from scratch — old rows are scrolled by blitting
|
||||
* the canvas onto itself (drawImage(canvas, dx, dy)) and repainting only the
|
||||
* strip that scrolled in. That keeps the cost per step constant no matter how
|
||||
* long the machine has been running.
|
||||
* Appends one row of the space-time diagram. Old rows are scrolled by blitting
|
||||
* the canvas onto itself, so each step costs the same however long it runs.
|
||||
*/
|
||||
function drawHistoryRow() {
|
||||
if (!hctx || !machine) return;
|
||||
@@ -473,9 +426,7 @@ function drawHistoryRow() {
|
||||
rowY += cell;
|
||||
}
|
||||
|
||||
/** Redraw the close-up tape strip, centred on the head, with the n cells the
|
||||
* next transition will read highlighted. Fully repainted each time — it is
|
||||
* only ~40 cells wide. */
|
||||
/** The close-up strip around the head, with the next read window highlighted. */
|
||||
function drawTapeStrip() {
|
||||
if (!tctx || !machine) return;
|
||||
const tc = tapeCanvas.value;
|
||||
@@ -509,21 +460,14 @@ function drawTapeStrip() {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Animation loop
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- Animation loop ----
|
||||
let rafId = 0;
|
||||
let lastTime = 0;
|
||||
let stepDebt = 0;
|
||||
|
||||
/**
|
||||
* Animation loop. Steps are decoupled from frames: `stepDebt` accumulates
|
||||
* elapsed-time * stepsPerSecond and whole steps are drained each frame, so the
|
||||
* simulation runs at the requested rate regardless of display refresh rate.
|
||||
*
|
||||
* dt is clamped to 0.25s so a backgrounded tab does not come back and try to
|
||||
* run thousands of steps at once, and `budget` is capped at 64 steps per frame
|
||||
* so a fast setting cannot freeze the page.
|
||||
* Steps accumulate as debt from elapsed time, so the rate is independent of
|
||||
* refresh rate. dt is clamped (backgrounded tabs) and steps capped per frame.
|
||||
*/
|
||||
function frame(now) {
|
||||
rafId = requestAnimationFrame(frame);
|
||||
@@ -545,9 +489,7 @@ function frame(now) {
|
||||
if (moved) drawTapeStrip();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI actions
|
||||
// ---------------------------------------------------------------------------
|
||||
// ---- UI actions ----
|
||||
function onToggleRun() {
|
||||
if (!machine || terminated.value) return;
|
||||
running.value = !running.value;
|
||||
|
||||
Reference in New Issue
Block a user