From c1544e755062d8f3a848f125ac396e3150472194 Mon Sep 17 00:00:00 2001 From: Alex Maldonado Date: Mon, 5 Oct 2026 05:12:49 +0000 Subject: [PATCH] Separate what the sources mean (Workspace) from how the app keeps them (Session) The engines are moving into their own project. Session mixed the two jobs: deciding what a program means (the hub's cascade, parsing every language, diagnostics, the run, the proof, the fuzzer) and app concerns (the area, saving to localStorage, versions, compile history, the best-practices helper, change events). Tests of meaning could only reach it through the app's state. src/core/workspace.ts is the first job alone, with no DOM, storage or areas: Workspace reads a WorkState (sources, sync, lang, call, input, setup, machine), and edit() returns whether anything changed. Session now extends it, keeps every app concern, and overrides only what the app changes: the Bridge's Mojo is derived (derivesMojo), and the Mojo diagnostics come from the compiler's answer and the helper when there is one. No behavior changes; every test passes unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ --- src/core/session.ts | 258 ++++------------------------------------ src/core/workspace.ts | 266 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 290 insertions(+), 234 deletions(-) create mode 100644 src/core/workspace.ts diff --git a/src/core/session.ts b/src/core/session.ts index 292754a..79a3ee0 100644 --- a/src/core/session.ts +++ b/src/core/session.ts @@ -1,17 +1,14 @@ /** - * A session: the state plus everything derived from it, memoized by the - * inputs it depends on. Views read from here and never call an engine. + * A session: the app's state plus everything derived from it. What the sources mean (the hub, parsing, runs, + * proofs, the fuzzer) is the Workspace's (core); a session adds the area the work is open in, where edits are + * saved, the saved versions, the real compiler's answers and the best-practices helper. Views read from here and + * never call an engine. */ -import type { Diagnostic, LangId, Lowered, Parsed, ProofReport, PropertyReport, Trace, ViewId } from './types.js'; +import type { Diagnostic, LangId, ViewId } from './types.js'; import { AREAS, type AreaId } from './areas.js'; import { type PlayState, type Layout, emptyState, saveLocal, clearLocal, editsFingerprint, editedFrom } from './state.js'; -import { SERVICES } from '../services/index.js'; -import { proveAgainst, type SpecoProgram } from '../services/speco.js'; -import type { MathoProgram } from '../services/matho.js'; -import { provePseudo, studyOf, defaultCall } from '../services/pseudo.js'; -import { mojoReadsInput, type MojoProgram } from '../services/mojo.js'; import { runMojo } from '../mojo/interp.js'; -import { fuzzPseudo, fuzzMojo, type FuzzReport, type FuzzOptions } from './fuzz.js'; +import { Workspace } from './workspace.js'; import { compilerDiagnostics, listingFunctions, type BuildLevel, type CompileOptions, type CompileOutcome, type ListingFunction } from '../services/godbolt.js'; import { compileBackend } from '../services/compile-backend.js'; import { keepCompile, keptCompiles, compiledStatus, type CompiledStatus, type KeptCompile } from './compiles.js'; @@ -21,7 +18,7 @@ import { versionKey, listVersions, saveVersion, renameVersion, deleteVersion, re import { findPractices, findingsToDiagnostics, applyPractices, type PracticeFinding } from '../mojo/practices.js'; import { checkMojo } from '../mojo/check.js'; import { GENERATED_HEADER } from '../sync/header.js'; -import { SyncHub, LINKED, isLinked, mojoFromPseudo, type HubMaps, type Linked, type MojoDerived, type Sources } from '../sync/hub.js'; +import { SyncHub, isLinked, type Linked } from '../sync/hub.js'; /** One answer from godbolt, kept with exactly what it answered. */ export interface CompileRecord { @@ -40,12 +37,9 @@ export interface CompileRecord { type Listener = (what: 'state' | 'source' | 'run') => void; -export class Session { - state: PlayState; - private memo = new Map(); +export class Session extends Workspace { + declare state: PlayState; private listeners = new Set(); - /** The last run error (a call that could not be resolved, a listing that did not assemble). */ - runError: string | null = null; /** * `storageId` says where edits are saved: by default the problem's own save @@ -56,8 +50,9 @@ export class Session { */ // `original` is copied: the session edits its state in place, and the problem's own version must not move with it constructor(state: PlayState = emptyState(), opts: { storageId?: string | null; keep?: (state: PlayState) => boolean; original?: PlayState; stale?: boolean; area?: AreaId; practices?: typeof findPractices } = {}) { + super(state); this.finder = opts.practices ?? findPractices; - this.state = state; this.area = opts.area ?? null; this.storageId = opts.storageId; this.keep = opts.keep; this.original = opts.original ? structuredClone(opts.original) : null; this.stale = !!opts.stale; + this.area = opts.area ?? null; this.storageId = opts.storageId; this.keep = opts.keep; this.original = opts.original ? structuredClone(opts.original) : null; this.stale = !!opts.stale; } /** * The area the work is open in (from the route); the layout is kept per area. Null for a session that is not @@ -82,13 +77,8 @@ export class Session { notifyStep(t: number): void { for (const fn of this.stepListeners) fn(t); } private emit(what: 'state' | 'source' | 'run') { for (const fn of this.listeners) fn(what); } - private cached(name: string, key: string, make: () => T): T { - const hit = this.memo.get(name); - if (hit && hit.key === key) return hit.value as T; - const value = make(); - this.memo.set(name, { key, value }); - return value; - } + /** In the Bridge the Mojo pane is always the literal translation of the pseudo, computed and never stored. */ + protected override derivesMojo(): boolean { return this.area === 'bridge'; } /* ---------- mutation ---------- */ @@ -98,20 +88,10 @@ export class Session { * text is what the pane already shows (a stale pane the student chose to edit becomes the authority). */ setSource(lang: LangId, text: string, force = false): void { - if (isLinked(lang)) { - if (!force && this.source(lang) === text) return; - const r = new SyncHub(this.linkedSources(), this.state.sync, { call: this.state.call ?? null }).edit(lang, text); - // a pane that was absent and is still empty stays absent, so editing a program back to the problem's own text is no edit - for (const l of LINKED) if (r.sources[l] !== undefined && (r.sources[l] !== '' || this.state.sources[l] !== undefined)) this.state.sources[l] = r.sources[l]; - this.state.sync = { authority: r.authority, stale: r.stale, names: r.names }; - this.maps = r.maps; - this.persist(); this.emit('source'); - return; - } - if (this.state.sources[lang] === text) return; // Mojo the student started from a generated program is theirs once they change it, and says so - if (lang === 'mojo' && this.state.mojoOrigin === 'generated') this.state.mojoOrigin = 'generated-edited'; - this.state.sources[lang] = text; + const wasGenerated = lang === 'mojo' && this.state.mojoOrigin === 'generated' && this.state.sources.mojo !== text; + if (!this.edit(lang, text, force)) return; + if (wasGenerated) this.state.mojoOrigin = 'generated-edited'; this.persist(); this.emit('source'); } @@ -154,44 +134,11 @@ export class Session { /** Make a stale pane the authority without changing its text: the others are regenerated from it. */ takeAuthority(lang: Linked): void { this.setSource(lang, this.source(lang), true); } - /** The linked panes as shown: what is written, with an empty one generated from the pseudo until the first edit. */ - private fill(): { sources: Sources; stale: Partial>; maps: HubMaps } { - if (this.state.sync) return { sources: this.state.sources, stale: {}, maps: this.maps }; - const key = JSON.stringify(LINKED.map((l) => this.state.sources[l] ?? '')); - return this.cached('fill', key, () => new SyncHub(this.state.sources).fill()); - } - private linkedSources(): Sources { return { ...this.state.sources, ...this.fill().sources }; } - /** Line maps between the linked panes and the pseudo, from the last cascade (or the fill that opened the problem). */ - private maps: HubMaps = { up: {}, down: {} }; - lineMaps(): HubMaps { - const base: HubMaps = this.state.sync ? this.maps : (() => { const f = this.fill().maps; return { up: f.up, down: { ...f.down, ...this.maps.down } }; })(); - return { up: base.up, down: { ...base.down, mojo: this.derivedMojo().map } }; - } - /** Where a pane stands against the others: as authored (never synced), in step, or stale with the reason. */ - linkState(lang: Linked): { kind: 'authored' | 'sync' | 'stale' | 'authority'; reason?: string } { - const sync = this.state.sync; - const reason = sync ? sync.stale?.[lang] : this.fill().stale[lang]; - if (reason) return { kind: 'stale', reason }; - if (!sync) return { kind: 'authored' }; - return { kind: sync.authority === lang ? 'authority' : 'sync' }; - } - - /** The literal Mojo for the pseudo now in play, labeled as generated by every view that shows it. Memoized by the pseudo and the call. */ - derivedMojo(): MojoDerived { - const pseudo = this.source('pseudo'); - const call = this.state.call ?? null; - return this.cached('mojo.derived', JSON.stringify([pseudo, call]), () => mojoFromPseudo(pseudo, call)); - } - setLang(lang: LangId): void { if (this.state.lang !== lang) { this.state.lang = lang; this.persist(); this.emit('state'); } } setView(view: ViewId): void { if (this.state.view !== view) { this.state.view = view; this.persist(); this.emit('state'); } } setCall(call: string | null): void { this.state.call = call; this.persist(); this.emit('run'); } setSetup(setup: string): void { this.state.setup = setup; this.persist(); this.emit('run'); } setInput(input: string): void { this.state.input = input; this.persist(); this.emit('run'); } - /** The INPUT lines of a run: one per line of the input box, trailing blank lines dropped. */ - inputLines(): string[] { const lines = (this.state.input || '').split('\n'); while (lines.length && lines[lines.length - 1].trim() === '') lines.pop(); return lines; } - /** Whether the program that will run reads INPUT, which is when the input box is shown. */ - readsInput(): boolean { if (this.state.lang === 'mojo') return mojoReadsInput(this.source('mojo')); const l = this.traceLang(); const src = l === 'lingo' ? this.source('lingo') : l === 'matho' ? '' : this.source('pseudo'); return l !== 'asm' && /^\s*INPUT\b/mi.test(src.replace(/\/\/.*$/gm, '')); } setMachine(machine: string): void { this.state.machine = machine; this.persist(); this.emit('run'); } setT(t: number): void { this.state.t = t; this.persist(); this.emit('state'); } /** The workspace arrangement for the area that is open. */ @@ -267,52 +214,12 @@ export class Session { /* ---------- derived ---------- */ - /** - * The text of a pane as shown. The linked panes may be generated from the pseudo until the first edit (fill); - * in the Bridge the Mojo pane is always the literal translation of the pseudo, computed here and never stored, - * so every view of it (stepping, the checker, Compile & run) reads the generated Mojo. - */ - source(lang: LangId): string { - if (lang === 'mojo' && this.area === 'bridge') return this.derivedMojo().source; - return isLinked(lang) ? (this.fill().sources[lang] ?? '') : (this.state.sources[lang] ?? ''); - } - /** What pane `lang` would show if this work were open in `area` (the Bridge's Mojo is the pseudo's translation; everywhere else it is the state's). */ shownIn(area: AreaId, lang: LangId): string { if (lang === 'mojo') return area === 'bridge' ? this.derivedMojo().source : (this.state.sources.mojo ?? ''); return isLinked(lang) ? (this.fill().sources[lang] ?? '') : (this.state.sources[lang] ?? ''); } - parsedLingo(): Parsed | null { - const src = this.source('lingo'); - if (!src.trim()) return null; - return this.cached('lingo', src, () => SERVICES.lingo.parse(src)); - } - - parsedMatho(): Parsed | null { - const src = this.source('matho'); - if (!src.trim()) return null; - return this.cached('matho', src, () => SERVICES.matho.parse(src) as Parsed); - } - - parsedPseudo(): Parsed | null { - const source = this.source('pseudo'); - if (!source.trim()) return null; - return this.cached('pseudo', source, () => studyOf(source)); - } - - parsedSpeco(): Parsed | null { - const src = this.source('speco'); - if (!src.trim()) return null; - return this.cached('speco', src, () => SERVICES.speco.parse(src) as Parsed); - } - - parsedMojo(): Parsed | null { - const src = this.source('mojo'); - if (!src.trim()) return null; - return this.cached('mojo', src, () => SERVICES.mojo.parse(src) as Parsed); - } - /* ---------- the real compiler ---------- */ private compiles: CompileRecord[] = []; @@ -437,136 +344,19 @@ export class Session { }); } - parsedAsm(): Parsed | null { - const src = this.source('asm'); - if (!src.trim()) return null; - return this.cached('asm', src, () => SERVICES.asm.parse(src)); - } - setViewsCollapsed(c: boolean): void { this.state.viewsCollapsed = c; this.persist(); this.emit('state'); } - diagnostics(lang: LangId): Diagnostic[] { - switch (lang) { - case 'lingo': return this.parsedLingo()?.diagnostics ?? []; - case 'matho': return this.parsedMatho()?.diagnostics ?? []; - case 'pseudo': { - return this.parsedPseudo()?.diagnostics ?? []; - } - case 'speco': { const m = this.parsedSpeco(); const w = this.proof(); return [...(m?.diagnostics ?? []), ...(w?.wovenDiagnostics ?? [])]; } - case 'mojo': { - // the compiler's answer for this exact source replaces what Programming+ found by itself - const rec = this.compileForSource(); - const base = rec?.outcome.answer ? rec.diagnostics : this.parsedMojo()?.diagnostics ?? []; - // in the Developer area the helper's findings are notes on the student's own lines (never errors or warnings) - return this.area === 'dev' && this.practicesOn() && !base.some((d) => d.severity === 'error') ? [...base, ...findingsToDiagnostics(this.practices())] : base; - } - case 'asm': return this.parsedAsm()?.diagnostics ?? []; - } + override diagnostics(lang: LangId): Diagnostic[] { + if (lang !== 'mojo') return super.diagnostics(lang); + // the compiler's answer for this exact source replaces what Programming+ found by itself + const rec = this.compileForSource(); + const base = rec?.outcome.answer ? rec.diagnostics : this.parsedMojo()?.diagnostics ?? []; + // in the Developer area the helper's findings are notes on the student's own lines (never errors or warnings) + return this.area === 'dev' && this.practicesOn() && !base.some((d) => d.severity === 'error') ? [...base, ...findingsToDiagnostics(this.practices())] : base; } - allDiagnostics(): Diagnostic[] { + override allDiagnostics(): Diagnostic[] { return (this.area ? AREAS[this.area].panes : (['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'] as LangId[])).flatMap((l) => this.diagnostics(l)); } - /** Which language the trace view steps: the active pane's, or the pseudocode behind it. */ - traceLang(): LangId { - const l = this.state.lang; - if (l === 'asm') return 'asm'; - if (l === 'mojo') return 'mojo'; - // a pane that is not in step holds text the other panes have moved on from: step the pseudo instead - if (l === 'lingo' && this.linkState('lingo').kind !== 'stale' && this.parsedLingo()?.ok) return 'lingo'; - if (l === 'matho' && this.linkState('matho').kind !== 'stale' && this.parsedMatho()?.ok) return 'matho'; - return 'pseudo'; - } - - callText(): string | null { - if (this.state.call !== undefined && this.state.call !== null && this.state.call !== '') return this.state.call; - if (this.traceLang() === 'matho') { const r = this.parsedMatho(); return r && SERVICES.matho.defaultCall ? SERVICES.matho.defaultCall(r) : null; } - const p = this.parsedPseudo(); - return p ? defaultCall(p.program) : null; - } - - trace(): Trace | null { - this.runError = null; - const lang = this.traceLang(); - try { - if (lang === 'mojo') { - const p = this.parsedMojo(); - if (!p) return null; - if (!p.ok) { this.runError = 'Fix the problems in the Mojo pane first; the Problems view lists them.'; return null; } - const key = JSON.stringify([this.source('mojo'), this.state.input]); - return this.cached('trace.mojo', key, () => runMojo(p.program!.module, this.source('mojo'), { input: this.inputLines(), maxSteps: 20000 }).trace); - } - if (lang === 'asm') { - const p = this.parsedAsm(); - if (!p || !p.ok) return null; - const key = JSON.stringify([this.source('asm'), this.state.setup, this.state.machine]); - return this.cached('trace.asm', key, () => SERVICES.asm.run!(p, { setup: this.state.setup, machine: this.state.machine, maxSteps: 20000 })); - } - if (lang === 'matho') { - const r = this.parsedMatho(); - if (!r || !r.ok) return null; - const key = JSON.stringify([this.source('matho'), this.state.call, this.state.input]); - return this.cached('trace.matho', key, () => SERVICES.matho.run!(r, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 })); - } - if (lang === 'lingo') { - const r = this.parsedLingo(); - if (!r || !r.ok) return null; - const key = JSON.stringify([this.source('lingo'), this.state.call, this.state.input]); - return this.cached('trace.lingo', key, () => SERVICES.lingo.run!(r, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 })); - } - const p = this.parsedPseudo(); - if (!p || !p.ok) return null; - const key = JSON.stringify([this.source('pseudo'), this.state.call, this.state.input]); - return this.cached('trace.pseudo', key, () => SERVICES.pseudo.run!(p, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 })); - } catch (e: any) { - this.runError = e?.message || String(e); - return null; - } - } - - proof(): { report: ProofReport; wovenSource: string | null; wovenDiagnostics: Diagnostic[]; study: Parsed | null } | null { - const p = this.parsedPseudo(); - if (!p || !p.ok) return null; - const m = this.parsedSpeco(); - const key = JSON.stringify([this.source('pseudo'), this.source('speco')]); - return this.cached('proof', key, () => { - if (m && m.ok && m.program!.spec.units.length) { - const r = proveAgainst(m, this.source('pseudo')); - return { report: r.report, wovenSource: r.woven.source, wovenDiagnostics: [...r.woven.diagnostics, ...r.study.diagnostics.filter((d) => d.severity === 'error').map((d) => ({ ...d, lang: 'speco' as LangId, message: `In the woven pseudocode, line ${d.line}: ${d.message}` }))], study: r.study }; - } - return { report: provePseudo(p), wovenSource: null, wovenDiagnostics: [], study: p }; - }); - } - - /** - * The fuzzer's report for each routine of the program that runs (core/fuzz.ts): the Mojo pane's functions other - * than main, or the pseudo's routines with the speco woven in. Memoized by the source, the seed and the budget. - */ - fuzz(opts: FuzzOptions = {}): FuzzReport[] { - const o = { seed: opts.seed ?? 1, budget: opts.budget ?? 300 }; - if (this.state.lang === 'mojo') { - const m = this.parsedMojo(); - if (!m || !m.ok || !m.program || m.program.module.unread) return []; - const src = this.source('mojo'); - const mod = m.program.module; - return this.cached('fuzz.mojo', JSON.stringify([src, o]), () => mod.body.filter((x: any) => x.k === 'def' && x.name !== 'main').map((d: any) => fuzzMojo(mod, src, d.name, o))); - } - const study = this.proof()?.study ?? this.parsedPseudo(); - if (!study || !study.ok || !study.program) return []; - const program = (study.program as any).program; - return this.cached('fuzz.pseudo', JSON.stringify([this.source('pseudo'), this.source('speco'), o]), () => [...program.subs.values()].map((sub: any) => fuzzPseudo(program, sub.name, o))); - } - - /** The fuzzer's reports in brief: per routine, the inputs checked and each way of failing (the home page, the tab's readiness). */ - tests(): PropertyReport[] { - return this.fuzz().map((r) => ({ - name: r.name, - checked: r.cases.filter((c) => c.strategy !== 'shrink' && c.strategy !== 'repeat' && c.outcome !== 'skip').length, - failures: [...r.failures.map((f) => ({ call: f.call, message: f.message, line: f.line, kind: f.kind })), - ...r.cases.filter((c) => c.outcome === 'raises').slice(0, 3).map((c) => ({ call: c.call, message: c.message ?? '', line: c.line, kind: 'raises-declared' }))], - ...(r.problem ? { problem: r.problem } : {}), - })); - } - } diff --git a/src/core/workspace.ts b/src/core/workspace.ts new file mode 100644 index 0000000..b8aced5 --- /dev/null +++ b/src/core/workspace.ts @@ -0,0 +1,266 @@ +/** + * A workspace: the sources of one piece of work and everything they mean, memoized by the inputs it depends on. + * The linked panes kept in step by the hub (sync/hub.ts), each language parsed, the diagnostics, the run, the proof + * and the fuzzer's report. No DOM, no storage, no areas: what a program means is decided here, and a front end (the + * app's Session) adds where it is kept and how it is shown. + */ +import type { Diagnostic, LangId, Parsed, ProofReport, PropertyReport, Trace } from './types.js'; +import { SERVICES } from '../services/index.js'; +import { proveAgainst, type SpecoProgram } from '../services/speco.js'; +import type { MathoProgram } from '../services/matho.js'; +import { provePseudo, studyOf, defaultCall } from '../services/pseudo.js'; +import { mojoReadsInput, type MojoProgram } from '../services/mojo.js'; +import { runMojo } from '../mojo/interp.js'; +import { fuzzPseudo, fuzzMojo, type FuzzReport, type FuzzOptions } from './fuzz.js'; +import { SyncHub, LINKED, isLinked, mojoFromPseudo, type HubMaps, type Linked, type MojoDerived, type Sources, type SyncInfo } from '../sync/hub.js'; + +/** What a workspace reads: the sources and how to run them. The app's saved state is a superset of this. */ +export interface WorkState { + sources: Sources; + /** The hub's bookkeeping: which linked pane is the authority, which are stale, the student's spelling of names. */ + sync?: SyncInfo; + /** The pane that is active, which decides what runs. */ + lang: LangId; + /** The call to run, such as COUNT_BASE('A', "GATTACA"); absent: the program's own default. */ + call?: string | null; + /** The run's input, one value per line. */ + input?: string; + /** For x86-64: the setup block, and the machine model. */ + setup?: string; + machine?: string; +} + +export interface ProofResult { report: ProofReport; wovenSource: string | null; wovenDiagnostics: Diagnostic[]; study: Parsed | null } + +export class Workspace { + state: WorkState; + protected memo = new Map(); + /** The last run error (a call that could not be resolved, a listing that did not assemble). */ + runError: string | null = null; + /** Line maps between the linked panes and the pseudo, from the last cascade (or the fill that opened the problem). */ + protected maps: HubMaps = { up: {}, down: {} }; + + constructor(state: WorkState) { this.state = state; } + + protected cached(name: string, key: string, make: () => T): T { + const hit = this.memo.get(name); + if (hit && hit.key === key) return hit.value as T; + const value = make(); + this.memo.set(name, { key, value }); + return value; + } + + /** Whether the Mojo pane shows the pseudo's literal translation instead of its own text (the app's Bridge). */ + protected derivesMojo(): boolean { return false; } + + /* ---------- editing ---------- */ + + /** + * Pane `lang` now holds `text`. For the four linked languages the hub makes the other panes follow in the same + * change; Mojo and x86-64 are stored as they are. `force` runs the cascade even when the text is what the pane + * already shows (a stale pane chosen to edit becomes the authority). Returns whether anything changed. + */ + edit(lang: LangId, text: string, force = false): boolean { + if (isLinked(lang)) { + if (!force && this.source(lang) === text) return false; + const r = new SyncHub(this.linkedSources(), this.state.sync, { call: this.state.call ?? null }).edit(lang, text); + // a pane that was absent and is still empty stays absent, so editing a program back to the problem's own text is no edit + for (const l of LINKED) if (r.sources[l] !== undefined && (r.sources[l] !== '' || this.state.sources[l] !== undefined)) this.state.sources[l] = r.sources[l]; + this.state.sync = { authority: r.authority, stale: r.stale, names: r.names }; + this.maps = r.maps; + return true; + } + if (this.state.sources[lang] === text) return false; + this.state.sources[lang] = text; + return true; + } + + /** The linked panes as shown: what is written, with an empty one generated from the pseudo until the first edit. */ + protected fill(): { sources: Sources; stale: Partial>; maps: HubMaps } { + if (this.state.sync) return { sources: this.state.sources, stale: {}, maps: this.maps }; + const key = JSON.stringify(LINKED.map((l) => this.state.sources[l] ?? '')); + return this.cached('fill', key, () => new SyncHub(this.state.sources).fill()); + } + protected linkedSources(): Sources { return { ...this.state.sources, ...this.fill().sources }; } + + lineMaps(): HubMaps { + const base: HubMaps = this.state.sync ? this.maps : (() => { const f = this.fill().maps; return { up: f.up, down: { ...f.down, ...this.maps.down } }; })(); + return { up: base.up, down: { ...base.down, mojo: this.derivedMojo().map } }; + } + /** Where a pane stands against the others: as authored (never synced), in step, or stale with the reason. */ + linkState(lang: Linked): { kind: 'authored' | 'sync' | 'stale' | 'authority'; reason?: string } { + const sync = this.state.sync; + const reason = sync ? sync.stale?.[lang] : this.fill().stale[lang]; + if (reason) return { kind: 'stale', reason }; + if (!sync) return { kind: 'authored' }; + return { kind: sync.authority === lang ? 'authority' : 'sync' }; + } + + /** The literal Mojo for the pseudo now in play, labeled as generated by every view that shows it. Memoized by the pseudo and the call. */ + derivedMojo(): MojoDerived { + const pseudo = this.source('pseudo'); + const call = this.state.call ?? null; + return this.cached('mojo.derived', JSON.stringify([pseudo, call]), () => mojoFromPseudo(pseudo, call)); + } + + /** The INPUT lines of a run: one per line of the input box, trailing blank lines dropped. */ + inputLines(): string[] { const lines = (this.state.input || '').split('\n'); while (lines.length && lines[lines.length - 1].trim() === '') lines.pop(); return lines; } + /** Whether the program that will run reads INPUT. */ + readsInput(): boolean { if (this.state.lang === 'mojo') return mojoReadsInput(this.source('mojo')); const l = this.traceLang(); const src = l === 'lingo' ? this.source('lingo') : l === 'matho' ? '' : this.source('pseudo'); return l !== 'asm' && /^\s*INPUT\b/mi.test(src.replace(/\/\/.*$/gm, '')); } + + /* ---------- derived ---------- */ + + /** The text of a pane as shown: a linked pane may be generated from the pseudo until the first edit (fill). */ + source(lang: LangId): string { + if (lang === 'mojo' && this.derivesMojo()) return this.derivedMojo().source; + return isLinked(lang) ? (this.fill().sources[lang] ?? '') : (this.state.sources[lang] ?? ''); + } + + parsedLingo(): Parsed | null { + const src = this.source('lingo'); + if (!src.trim()) return null; + return this.cached('lingo', src, () => SERVICES.lingo.parse(src)); + } + parsedMatho(): Parsed | null { + const src = this.source('matho'); + if (!src.trim()) return null; + return this.cached('matho', src, () => SERVICES.matho.parse(src) as Parsed); + } + parsedPseudo(): Parsed | null { + const source = this.source('pseudo'); + if (!source.trim()) return null; + return this.cached('pseudo', source, () => studyOf(source)); + } + parsedSpeco(): Parsed | null { + const src = this.source('speco'); + if (!src.trim()) return null; + return this.cached('speco', src, () => SERVICES.speco.parse(src) as Parsed); + } + parsedMojo(): Parsed | null { + const src = this.source('mojo'); + if (!src.trim()) return null; + return this.cached('mojo', src, () => SERVICES.mojo.parse(src) as Parsed); + } + parsedAsm(): Parsed | null { + const src = this.source('asm'); + if (!src.trim()) return null; + return this.cached('asm', src, () => SERVICES.asm.parse(src)); + } + + /** What each language's own reader says about its pane. */ + diagnostics(lang: LangId): Diagnostic[] { + switch (lang) { + case 'lingo': return this.parsedLingo()?.diagnostics ?? []; + case 'matho': return this.parsedMatho()?.diagnostics ?? []; + case 'pseudo': return this.parsedPseudo()?.diagnostics ?? []; + case 'speco': { const m = this.parsedSpeco(); const w = this.proof(); return [...(m?.diagnostics ?? []), ...(w?.wovenDiagnostics ?? [])]; } + case 'mojo': return this.parsedMojo()?.diagnostics ?? []; + case 'asm': return this.parsedAsm()?.diagnostics ?? []; + } + } + + allDiagnostics(): Diagnostic[] { + return (['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'] as LangId[]).flatMap((l) => this.diagnostics(l)); + } + + /** Which language a run steps: the active pane's, or the pseudocode behind it. */ + traceLang(): LangId { + const l = this.state.lang; + if (l === 'asm') return 'asm'; + if (l === 'mojo') return 'mojo'; + // a pane that is not in step holds text the other panes have moved on from: step the pseudo instead + if (l === 'lingo' && this.linkState('lingo').kind !== 'stale' && this.parsedLingo()?.ok) return 'lingo'; + if (l === 'matho' && this.linkState('matho').kind !== 'stale' && this.parsedMatho()?.ok) return 'matho'; + return 'pseudo'; + } + + callText(): string | null { + if (this.state.call !== undefined && this.state.call !== null && this.state.call !== '') return this.state.call; + if (this.traceLang() === 'matho') { const r = this.parsedMatho(); return r && SERVICES.matho.defaultCall ? SERVICES.matho.defaultCall(r) : null; } + const p = this.parsedPseudo(); + return p ? defaultCall(p.program) : null; + } + + trace(): Trace | null { + this.runError = null; + const lang = this.traceLang(); + try { + if (lang === 'mojo') { + const p = this.parsedMojo(); + if (!p) return null; + if (!p.ok) { this.runError = 'Fix the problems in the Mojo pane first; the Problems view lists them.'; return null; } + const key = JSON.stringify([this.source('mojo'), this.state.input]); + return this.cached('trace.mojo', key, () => runMojo(p.program!.module, this.source('mojo'), { input: this.inputLines(), maxSteps: 20000 }).trace); + } + if (lang === 'asm') { + const p = this.parsedAsm(); + if (!p || !p.ok) return null; + const key = JSON.stringify([this.source('asm'), this.state.setup, this.state.machine]); + return this.cached('trace.asm', key, () => SERVICES.asm.run!(p, { setup: this.state.setup, machine: this.state.machine, maxSteps: 20000 })); + } + if (lang === 'matho') { + const r = this.parsedMatho(); + if (!r || !r.ok) return null; + const key = JSON.stringify([this.source('matho'), this.state.call, this.state.input]); + return this.cached('trace.matho', key, () => SERVICES.matho.run!(r, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 })); + } + if (lang === 'lingo') { + const r = this.parsedLingo(); + if (!r || !r.ok) return null; + const key = JSON.stringify([this.source('lingo'), this.state.call, this.state.input]); + return this.cached('trace.lingo', key, () => SERVICES.lingo.run!(r, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 })); + } + const p = this.parsedPseudo(); + if (!p || !p.ok) return null; + const key = JSON.stringify([this.source('pseudo'), this.state.call, this.state.input]); + return this.cached('trace.pseudo', key, () => SERVICES.pseudo.run!(p, { call: this.state.call ?? null, input: this.inputLines(), maxSteps: 20000 })); + } catch (e: any) { + this.runError = e?.message || String(e); + return null; + } + } + + proof(): ProofResult | null { + const p = this.parsedPseudo(); + if (!p || !p.ok) return null; + const m = this.parsedSpeco(); + const key = JSON.stringify([this.source('pseudo'), this.source('speco')]); + return this.cached('proof', key, () => { + if (m && m.ok && m.program!.spec.units.length) { + const r = proveAgainst(m, this.source('pseudo')); + return { report: r.report, wovenSource: r.woven.source, wovenDiagnostics: [...r.woven.diagnostics, ...r.study.diagnostics.filter((d) => d.severity === 'error').map((d) => ({ ...d, lang: 'speco' as LangId, message: `In the woven pseudocode, line ${d.line}: ${d.message}` }))], study: r.study }; + } + return { report: provePseudo(p), wovenSource: null, wovenDiagnostics: [], study: p }; + }); + } + + /** + * The fuzzer's report for each routine of the program that runs (fuzz.ts): the Mojo pane's functions other than + * main, or the pseudo's routines with the speco woven in. Memoized by the source, the seed and the budget. + */ + fuzz(opts: FuzzOptions = {}): FuzzReport[] { + const o = { seed: opts.seed ?? 1, budget: opts.budget ?? 300 }; + if (this.state.lang === 'mojo') { + const m = this.parsedMojo(); + if (!m || !m.ok || !m.program || m.program.module.unread) return []; + const src = this.source('mojo'); + const mod = m.program.module; + return this.cached('fuzz.mojo', JSON.stringify([src, o]), () => mod.body.filter((x: any) => x.k === 'def' && x.name !== 'main').map((d: any) => fuzzMojo(mod, src, d.name, o))); + } + const study = this.proof()?.study ?? this.parsedPseudo(); + if (!study || !study.ok || !study.program) return []; + const program = (study.program as any).program; + return this.cached('fuzz.pseudo', JSON.stringify([this.source('pseudo'), this.source('speco'), o]), () => [...program.subs.values()].map((sub: any) => fuzzPseudo(program, sub.name, o))); + } + + /** The fuzzer's reports in brief: per routine, the inputs checked and each way of failing. */ + tests(): PropertyReport[] { + return this.fuzz().map((r) => ({ + name: r.name, + checked: r.cases.filter((c) => c.strategy !== 'shrink' && c.strategy !== 'repeat' && c.outcome !== 'skip').length, + failures: [...r.failures.map((f) => ({ call: f.call, message: f.message, line: f.line, kind: f.kind })), + ...r.cases.filter((c) => c.outcome === 'raises').slice(0, 3).map((c) => ({ call: c.call, message: c.message ?? '', line: c.line, kind: 'raises-declared' }))], + ...(r.problem ? { problem: r.problem } : {}), + })); + } +}