Baseline: tree as shared
This commit is contained in:
1679 files changed
+1024562
No files matched your search
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* The three areas (restructure plan, section 2.1). A problem is one `PlayState` shared by all three, so moving
|
||||
* from the Bridge to the Developer area to Hardware carries the work along; the area comes from the route, not
|
||||
* the state. The names are placeholders in this one table: the owner renames an area with a one-line change
|
||||
* here (and nowhere else), and the routes, which are ids, stay.
|
||||
*/
|
||||
import type { LangId } from './types.js';
|
||||
import type { DockTab, PlayState } from './state.js';
|
||||
import { LINKED } from '../sync/hub.js';
|
||||
|
||||
export type AreaId = 'bridge' | 'dev' | 'hw';
|
||||
|
||||
/** The tabs beside the editor: the views that read a run. */
|
||||
export type InspectId = 'trace' | 'table' | 'flow' | 'data' | 'life' | 'proof' | 'tests';
|
||||
|
||||
export interface AreaDef {
|
||||
id: AreaId;
|
||||
/** The path segment: `#/<route>/p/<problem>`. */
|
||||
route: AreaId;
|
||||
/** What the area is called on screen. */
|
||||
name: string;
|
||||
tagline: string;
|
||||
/** The panes it offers, in tab order. */
|
||||
panes: LangId[];
|
||||
/** The inspect tabs it may offer (each also has to apply to the open pane). `trace` is the Run view: the run top to bottom, with the variables followed and their lifetimes. */
|
||||
inspect: InspectId[];
|
||||
/** The dock tabs it may offer. */
|
||||
dock: DockTab[];
|
||||
/** What the toolbar's main button does for the pane that is open: run it as written, or build it with the real compiler. */
|
||||
primary: 'run' | 'compile';
|
||||
/**
|
||||
* How the workspace is laid out: `ide`, the code with the inspect panel beside it and the dock below; `board`, two
|
||||
* panes only, the code on the left and on the right a board of cards the student arranges (src/ui/hw/board.ts),
|
||||
* which holds what the dock and the inspect panel would (setup, output, problems, the compiler, the Run view).
|
||||
*/
|
||||
workspace: 'ide' | 'board';
|
||||
}
|
||||
|
||||
export const AREAS: Record<AreaId, AreaDef> = {
|
||||
bridge: {
|
||||
id: 'bridge', route: 'bridge', name: 'Bridge',
|
||||
tagline: 'Take a written problem or idea into Mojo: lingo, matho and pseudo, with Mojo generated from the pseudo.',
|
||||
panes: ['lingo', 'matho', 'pseudo', 'speco', 'mojo'],
|
||||
inspect: ['trace', 'flow', 'data', 'proof', 'tests'],
|
||||
dock: ['setup', 'output', 'problems', 'compiler', 'practices'],
|
||||
primary: 'run', workspace: 'ide',
|
||||
},
|
||||
dev: {
|
||||
id: 'dev', route: 'dev', name: 'Developer',
|
||||
tagline: 'Write Mojo: the checker, the stepper, lifetimes, tests, and the real compiler.',
|
||||
panes: ['mojo'],
|
||||
inspect: ['trace', 'flow', 'data', 'tests'],
|
||||
dock: ['setup', 'output', 'problems', 'compiler'],
|
||||
primary: 'compile', workspace: 'ide',
|
||||
},
|
||||
hw: {
|
||||
id: 'hw', route: 'hw', name: 'Hardware',
|
||||
tagline: 'See the machine: Mojo and the x86-64 it compiles to, with registers, memory and the chip in view.',
|
||||
panes: ['mojo', 'asm'],
|
||||
// no inspect panel and no dock: their views are cards on the board
|
||||
inspect: [],
|
||||
dock: [],
|
||||
primary: 'compile', workspace: 'board',
|
||||
},
|
||||
};
|
||||
|
||||
export const AREA_ORDER: AreaId[] = ['bridge', 'dev', 'hw'];
|
||||
|
||||
export const isAreaId = (x: unknown): x is AreaId => typeof x === 'string' && Object.prototype.hasOwnProperty.call(AREAS, x);
|
||||
|
||||
/** The area an exercise opens in when it does not say: Hardware for assembly problems, Developer for Mojo-only ones, Bridge for the rest. */
|
||||
export function defaultAreaFor(e: { id: string; sources: Partial<Record<LangId, string>>; area?: AreaId; mojoProgram?: string }): AreaId {
|
||||
if (e.area) return e.area;
|
||||
const has = (l: LangId) => !!(e.sources[l] ?? '').trim();
|
||||
if (e.id.startsWith('asm-')) return 'hw';
|
||||
if ((has('mojo') || e.mojoProgram) && !has('pseudo') && !has('lingo') && !has('matho')) return 'dev';
|
||||
return 'bridge';
|
||||
}
|
||||
|
||||
/** Whether a pane is one of the area's. */
|
||||
export const areaHasPane = (area: AreaDef, lang: LangId): boolean => area.panes.includes(lang);
|
||||
|
||||
/**
|
||||
* The pane to show when a state opens in an area. A pane that belongs to the area is kept (a shared link points
|
||||
* at one view on purpose); otherwise the area's own first choice. `fresh` is for a catalog problem opening: its
|
||||
* authored default pane is Mojo for most, but the Bridge begins with the idea, not the generated code.
|
||||
*/
|
||||
export function paneForArea(area: AreaDef, state: PlayState, fresh = false): LangId {
|
||||
const has = (l: LangId) => !!(state.sources[l] ?? '').trim();
|
||||
switch (area.id) {
|
||||
case 'dev': return 'mojo';
|
||||
case 'hw': return areaHasPane(area, state.lang) ? state.lang : has('asm') ? 'asm' : 'mojo';
|
||||
case 'bridge': {
|
||||
if ((LINKED as readonly string[]).includes(state.lang)) return state.lang;
|
||||
if (!fresh && areaHasPane(area, state.lang)) return state.lang;
|
||||
return (['pseudo', 'lingo', 'matho', 'speco'] as LangId[]).find(has) ?? 'pseudo';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The areas the work can move to from `from` without changing what is on screen: the open pane exists there, and it
|
||||
* shows the same text. In practice that is Developer and Hardware on the same Mojo; the Bridge's Mojo is the
|
||||
* translation of its pseudo, so it matches the others only when the student's Mojo is that translation. The
|
||||
* toolbar offers only these; every area is its own page in the nav and on the home page, so a learner moving
|
||||
* between them never finds the work changed under them by the move itself.
|
||||
*/
|
||||
export function safeSwitches(from: AreaId, lang: LangId, shown: (area: AreaId, lang: LangId) => string): AreaId[] {
|
||||
if (!areaHasPane(AREAS[from], lang)) return [];
|
||||
const here = shown(from, lang);
|
||||
// an empty pane carries nothing across: "the same" would be true of any area, and the move would show other work
|
||||
if (!here.trim()) return [];
|
||||
return AREA_ORDER.filter((to) => to !== from && areaHasPane(AREAS[to], lang) && shown(to, lang) === here);
|
||||
}
|
||||
|
||||
/**
|
||||
* The areas a catalog problem has something to show in, its own area first: the Bridge when it has an idea to
|
||||
* translate (lingo, matho, pseudo or speco), Developer when it has Mojo, Hardware when it has x86-64. The home
|
||||
* page's problem cards link to each and filter by them.
|
||||
*/
|
||||
export function areasFor(p: { area: AreaId; sources: Partial<Record<LangId, string>>; mojo?: { source?: string } | null }): AreaId[] {
|
||||
const has = (l: LangId) => !!(p.sources[l] ?? '').trim();
|
||||
const fits: Record<AreaId, boolean> = {
|
||||
bridge: has('pseudo') || has('lingo') || has('matho') || has('speco'),
|
||||
dev: has('mojo') || !!p.mojo?.source?.trim(),
|
||||
hw: has('asm'),
|
||||
};
|
||||
return [p.area, ...AREA_ORDER.filter((a) => a !== p.area && fits[a])];
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The problem catalog, built from the exercise registry (src/exercises/).
|
||||
* Each exercise carries whichever layers the course wrote for it; a speco
|
||||
* spec is extracted from the pseudocode's own contracts when none is given.
|
||||
*/
|
||||
import { EXERCISES, type Exercise } from '../exercises/index.js';
|
||||
import type { LangId } from './types.js';
|
||||
import { defaultAreaFor, type AreaId } from './areas.js';
|
||||
import { emptyState, type PlayState } from './state.js';
|
||||
import { extractSpec } from '../services/speco.js';
|
||||
import { MOJO_PROGRAMS, type MojoProgram } from '../mojo/generated/programs.js';
|
||||
import { MOJO_LISTINGS } from '../mojo/generated/listings.js';
|
||||
|
||||
export interface Problem extends Exercise {
|
||||
lang: LangId;
|
||||
/** The area it opens in from the problem list. */
|
||||
area: AreaId;
|
||||
/** The exercise's Mojo program and godbolt's verdict on it, when it names one. */
|
||||
mojo?: MojoProgram & { id: string };
|
||||
}
|
||||
|
||||
function problem(e: Exercise): Problem {
|
||||
const sources = { ...e.sources };
|
||||
const mojo = e.mojoProgram ? MOJO_PROGRAMS[e.mojoProgram] : undefined;
|
||||
if (e.mojoProgram && !mojo) throw new Error(`exercise ${e.id} names Mojo program ${e.mojoProgram}, which is not in mojo/local/`);
|
||||
if (mojo && !sources.mojo) sources.mojo = mojo.source;
|
||||
// the compiler's listing for the program, when `pixi run play` has stored one, fills an x86-64 pane the exercise left empty
|
||||
const listing = e.mojoProgram ? MOJO_LISTINGS[e.mojoProgram] : undefined;
|
||||
const fromListing = !!listing && !sources.asm;
|
||||
if (listing && fromListing) sources.asm = listing.asm;
|
||||
if (sources.pseudo && !sources.speco) {
|
||||
const spec = extractSpec(sources.pseudo);
|
||||
if (spec) sources.speco = spec;
|
||||
}
|
||||
return { ...e, sources, area: defaultAreaFor({ id: e.id, sources: e.sources, area: e.area, mojoProgram: e.mojoProgram }), setup: e.setup ?? (fromListing ? listing!.setup : undefined), mojo: mojo && { ...mojo, id: e.mojoProgram! }, lang: e.lang ?? (sources.mojo ? 'mojo' : sources.pseudo ? 'pseudo' : sources.lingo ? 'lingo' : 'asm') };
|
||||
}
|
||||
|
||||
export const PROBLEMS: Problem[] = EXERCISES.map(problem);
|
||||
|
||||
export function problemById(id: string): Problem | undefined {
|
||||
return PROBLEMS.find((p) => p.id === id);
|
||||
}
|
||||
|
||||
export function stateForProblem(p: Problem): PlayState {
|
||||
const s = emptyState();
|
||||
s.problem = p.id;
|
||||
s.title = p.title;
|
||||
s.sources = { ...p.sources };
|
||||
s.lang = p.lang;
|
||||
s.call = p.call ?? null;
|
||||
s.setup = p.setup;
|
||||
s.machine = p.machine;
|
||||
s.view = p.view ?? 'trace';
|
||||
return s;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* godbolt's answers, kept across everything that rebuilds the page: switching panes or problems, following a
|
||||
* link, reloading. An answer is only ever shown for exactly the source, input and build it answered, so a
|
||||
* kept one is as good as a new one; asking again costs a network round trip and a slot in godbolt's rate limit.
|
||||
*
|
||||
* Kept in memory for this tab, and in localStorage (the newest few, smallest first to go when space runs out)
|
||||
* so a reload or a new tab finds them too. A browser that refuses storage still keeps them for the tab.
|
||||
*/
|
||||
import type { BuildLevel, CompileOutcome } from '../services/godbolt.js';
|
||||
|
||||
export interface KeptCompile { source: string; stdin: string; level: BuildLevel; at: number; outcome: CompileOutcome }
|
||||
|
||||
const KEY = 'pplus.compiles';
|
||||
const KEEP = 16;
|
||||
let memory: KeptCompile[] | null = null;
|
||||
|
||||
function load(): KeptCompile[] {
|
||||
if (memory) return memory;
|
||||
memory = [];
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
if (Array.isArray(parsed)) memory = parsed.filter((r) => r && typeof r.source === 'string' && typeof r.stdin === 'string' && (r.level === 'O0' || r.level === 'default') && r.outcome);
|
||||
} catch { /* storage blocked or the entry is damaged: start empty */ }
|
||||
return memory;
|
||||
}
|
||||
|
||||
function save(list: KeptCompile[]): void {
|
||||
// drop the oldest until it fits; a browser that refuses storage keeps them in memory only
|
||||
for (let n = list.length; n > 0; n--) {
|
||||
try { localStorage.setItem(KEY, JSON.stringify(list.slice(0, n))); return; } catch { /* over quota: keep fewer */ }
|
||||
}
|
||||
try { localStorage.removeItem(KEY); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
/* ---------- the summary index: what the godbolt badge reads ---------- */
|
||||
|
||||
/** What godbolt said about a build, in the few words a badge needs. */
|
||||
export type CompiledOutcome = 'ran' | 'did-not-compile' | 'timed-out' | 'not-run';
|
||||
export interface CompiledSummary { hash: string; level: BuildLevel; outcome: CompiledOutcome; exit: number | null; at: number }
|
||||
export interface CompiledStatus { outcome: CompiledOutcome; exit: number | null; at: number; level: BuildLevel }
|
||||
|
||||
const INDEX_KEY = 'pplus.compiled';
|
||||
const INDEX_KEEP = 300;
|
||||
let index: CompiledSummary[] | null = null;
|
||||
|
||||
/** A content hash of exactly what was sent: the source, the input, and the build level (cyrb53, 53 bits, as hex). */
|
||||
export function compileHash(source: string, stdin: string, level: BuildLevel): string {
|
||||
const str = JSON.stringify([source, stdin, level]);
|
||||
let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const c = str.charCodeAt(i);
|
||||
h1 = Math.imul(h1 ^ c, 2654435761);
|
||||
h2 = Math.imul(h2 ^ c, 1597334677);
|
||||
}
|
||||
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
||||
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
||||
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0') + str.length.toString(16);
|
||||
}
|
||||
|
||||
function loadIndex(): CompiledSummary[] {
|
||||
if (index) return index;
|
||||
index = [];
|
||||
try {
|
||||
const raw = localStorage.getItem(INDEX_KEY);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
if (Array.isArray(parsed)) index = parsed.filter((r) => r && typeof r.hash === 'string' && (r.level === 'O0' || r.level === 'default') && typeof r.at === 'number'
|
||||
&& (r.outcome === 'ran' || r.outcome === 'did-not-compile' || r.outcome === 'timed-out' || r.outcome === 'not-run'));
|
||||
} catch { /* storage blocked or damaged: start empty */ }
|
||||
return index;
|
||||
}
|
||||
|
||||
function saveIndex(list: CompiledSummary[]): void {
|
||||
for (let n = list.length; n > 0; n = Math.floor(n / 2)) {
|
||||
try { localStorage.setItem(INDEX_KEY, JSON.stringify(list.slice(0, n))); return; } catch { /* over quota: keep fewer */ }
|
||||
}
|
||||
try { localStorage.removeItem(INDEX_KEY); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
function summarize(rec: KeptCompile): CompiledSummary | null {
|
||||
const a = rec.outcome.answer;
|
||||
if (!a) return null;
|
||||
const outcome: CompiledOutcome = !a.compiled ? 'did-not-compile' : a.timedOut ? 'timed-out' : !a.executed ? 'not-run' : 'ran';
|
||||
return { hash: compileHash(rec.source, rec.stdin, rec.level), level: rec.level, outcome, exit: a.executed ? a.exitCode : null, at: rec.at };
|
||||
}
|
||||
|
||||
/**
|
||||
* What godbolt last said about exactly this source, input and build level, or null when this browser never
|
||||
* asked. Only this browser's own compiles are in the index, never anything from a link or a file.
|
||||
*/
|
||||
export function compiledStatus(source: string, stdin: string, level: BuildLevel): CompiledStatus | null {
|
||||
if (!source.trim()) return null;
|
||||
const hash = compileHash(source, stdin, level);
|
||||
const r = loadIndex().find((x) => x.hash === hash);
|
||||
return r ? { outcome: r.outcome, exit: r.exit, at: r.at, level: r.level } : null;
|
||||
}
|
||||
|
||||
/** Keep an answer (a network failure is not worth keeping: asking again may well work). */
|
||||
export function keepCompile(rec: KeptCompile): void {
|
||||
if (!rec.outcome.answer) return;
|
||||
const sum = summarize(rec);
|
||||
if (sum) { index = [sum, ...loadIndex().filter((r) => r.hash !== sum.hash)].slice(0, INDEX_KEEP); saveIndex(index); }
|
||||
const list = load().filter((r) => !(r.source === rec.source && r.stdin === rec.stdin && r.level === rec.level));
|
||||
list.unshift({ source: rec.source, stdin: rec.stdin, level: rec.level, at: rec.at, outcome: rec.outcome });
|
||||
memory = list.slice(0, KEEP);
|
||||
save(memory);
|
||||
}
|
||||
|
||||
/** Every kept answer for this exact source, newest first. */
|
||||
export function keptCompiles(source: string): KeptCompile[] {
|
||||
return load().filter((r) => r.source === source);
|
||||
}
|
||||
|
||||
/** Forget every kept answer (the tests use this). */
|
||||
export function forgetCompiles(): void {
|
||||
memory = []; index = [];
|
||||
try { localStorage.removeItem(KEY); localStorage.removeItem(INDEX_KEY); } catch { /* ignore */ }
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
/**
|
||||
* Generated-input testing, as a fuzzer that shows its work (the Tests view). For one routine it says exactly what
|
||||
* it tries and what it checks:
|
||||
*
|
||||
* how the inputs are made edge cases in combination; every short DNA string (when a routine reads one);
|
||||
* seeded random values; and mutations of the inputs that reached lines nothing else
|
||||
* had reached (coverage-guided, as a fuzzer does)
|
||||
* what each input must do the checks (`checks`): finish, raise no error, keep every contract, give the same
|
||||
* answer twice
|
||||
* what happened every case, with its strategy, input, outcome and steps; the lines the inputs
|
||||
* reached and the ones none did; the answers it gave and how often; for each way of
|
||||
* failing, the input that found it and every step of shrinking it to the smallest
|
||||
*
|
||||
* Seeded, so a report is the same on every run until the seed changes. DOM-free: the engines run the inputs
|
||||
* (pseudo: src/engines/pseudo/interp.js; Mojo: src/mojo/interp.ts), and src/ui/views/tests.ts draws the report.
|
||||
*/
|
||||
import { run } from '../engines/pseudo/interp.js';
|
||||
import { formatValue, cloneValue, PArray } from '../engines/pseudo/lang.js';
|
||||
import type { Module, Stmt } from '../mojo/parse.js';
|
||||
import { probeMojo } from '../mojo/interp.js';
|
||||
import { generator, literal, rng, typeText as mojoType, type Gen } from '../mojo/properties.js';
|
||||
import { show as showMojo, type V } from '../mojo/values.js';
|
||||
|
||||
export type Strategy = 'edge' | 'exhaustive' | 'random' | 'mutate' | 'shrink' | 'repeat';
|
||||
export type Outcome = 'pass' | 'fail' | 'skip' | 'raises';
|
||||
|
||||
export const STRATEGY: Record<Strategy, { label: string; how: string }> = {
|
||||
edge: { label: 'edge cases', how: 'the values most likely to break code, for each parameter, in combination: zero, one and negative numbers, the empty string and list, a single element, repeated letters' },
|
||||
exhaustive: { label: 'every short string', how: 'every DNA string up to three letters long (85 of them), with each choice of the other parameter' },
|
||||
random: { label: 'random', how: 'values drawn at random from the seed, so the same seed always makes the same inputs' },
|
||||
mutate: { label: 'mutations', how: 'small changes (a letter added, removed or replaced; a number nudged, doubled or negated; an element dropped) to inputs that reached a line nothing earlier had reached' },
|
||||
shrink: { label: 'shrinking', how: 'after a failure, smaller and smaller inputs that still fail the same way, down to one that cannot be made smaller' },
|
||||
repeat: { label: 'repeats', how: 'inputs run a second time, to check the answer does not change' },
|
||||
};
|
||||
|
||||
export interface FuzzParam { name: string; type: string; how: string }
|
||||
export interface FuzzCase { n: number; strategy: Strategy; call: string; args: string[]; outcome: Outcome; result?: string; message?: string; kind?: string; line?: number; steps: number; newLines?: number[] }
|
||||
export interface FuzzFailure { kind: string; message: string; line?: number; call: string; found: string; shrink: string[]; n: number }
|
||||
export interface FuzzReport {
|
||||
name: string;
|
||||
signature: string;
|
||||
lang: 'pseudo' | 'mojo';
|
||||
params: FuzzParam[];
|
||||
seed: number;
|
||||
budget: number;
|
||||
/** What every input is checked for. */
|
||||
checks: string[];
|
||||
strategies: Array<{ id: Strategy; label: string; how: string; count: number }>;
|
||||
/** Every case run, in order (shrinking and repeats included). */
|
||||
cases: FuzzCase[];
|
||||
failures: FuzzFailure[];
|
||||
counts: Record<Outcome, number>;
|
||||
/** The routine's lines: how many inputs reached each, and how often it ran. */
|
||||
coverage: Array<{ line: number; inputs: number; hits: number }>;
|
||||
/** The answers given, most common first. */
|
||||
results: Array<{ value: string; count: number }>;
|
||||
/** Why the routine could not be fuzzed, or why fuzzing stopped. */
|
||||
problem?: string;
|
||||
}
|
||||
export interface FuzzOptions { seed?: number; budget?: number }
|
||||
|
||||
export const BUDGETS = [100, 300, 1000, 3000] as const;
|
||||
|
||||
interface Exec { outcome: Outcome | 'declined'; result?: string; message?: string; kind?: string; line?: number; steps: number; hits: Map<number, number> }
|
||||
|
||||
interface Driver<T> {
|
||||
name: string;
|
||||
signature: string;
|
||||
lang: 'pseudo' | 'mojo';
|
||||
params: FuzzParam[];
|
||||
checks: string[];
|
||||
lines: number[];
|
||||
edges(): T[][];
|
||||
exhaustive(): T[][];
|
||||
random(r: () => number): T[];
|
||||
mutate(args: T[], r: () => number): T[];
|
||||
smaller(args: T[]): Iterable<T[]>;
|
||||
call(args: T[]): string;
|
||||
arg(v: T, i: number): string;
|
||||
exec(args: T[]): Exec;
|
||||
}
|
||||
|
||||
/** The loop every language shares. */
|
||||
function fuzz<T>(d: Driver<T>, opts: FuzzOptions): FuzzReport {
|
||||
const seed = opts.seed ?? 1;
|
||||
const budget = opts.budget ?? 300;
|
||||
const r = rng(seed * 2654435761);
|
||||
const cases: FuzzCase[] = [];
|
||||
const failures: FuzzFailure[] = [];
|
||||
const counts: Record<Outcome, number> = { pass: 0, fail: 0, skip: 0, raises: 0 };
|
||||
const cover = new Map<number, { inputs: number; hits: number }>();
|
||||
const results = new Map<string, number>();
|
||||
const corpus: T[][] = [];
|
||||
const seen = new Set<string>();
|
||||
const used: Record<Strategy, number> = { edge: 0, exhaustive: 0, random: 0, mutate: 0, shrink: 0, repeat: 0 };
|
||||
const failKeys = new Set<string>();
|
||||
/** The arguments behind each call shown, for the repeat check. */
|
||||
const byCall = new Map<string, T[]>();
|
||||
let problem: string | undefined;
|
||||
const report = (): FuzzReport => ({
|
||||
name: d.name, signature: d.signature, lang: d.lang, params: d.params, seed, budget, checks: d.checks,
|
||||
strategies: (Object.keys(STRATEGY) as Strategy[]).filter((s) => used[s]).map((s) => ({ id: s, ...STRATEGY[s], count: used[s] })),
|
||||
cases, failures, counts,
|
||||
coverage: d.lines.map((line) => ({ line, inputs: cover.get(line)?.inputs ?? 0, hits: cover.get(line)?.hits ?? 0 })),
|
||||
results: [...results].sort((a, b) => b[1] - a[1]).map(([value, count]) => ({ value, count })),
|
||||
...(problem ? { problem } : {}),
|
||||
});
|
||||
|
||||
/** Run one input and keep everything about it. Returns null when the engine cannot run it at all. */
|
||||
let declined = 0;
|
||||
const tryOne = (args: T[], strategy: Strategy): { c: FuzzCase; x: Exec } | null => {
|
||||
const raw = d.exec(args);
|
||||
// an input the interpreter cannot follow is listed as skipped, with why; when most are, fuzzing stops and says so
|
||||
if (raw.outcome === 'declined' && ++declined >= 20 && declined > cases.length / 2) { problem = raw.message; return null; }
|
||||
const x = (raw.outcome === 'declined' ? { ...raw, outcome: 'skip', kind: 'declined' } : raw) as Exec & { outcome: Outcome };
|
||||
used[strategy]++;
|
||||
const fresh: number[] = [];
|
||||
for (const [line, n] of x.hits) {
|
||||
const e = cover.get(line);
|
||||
if (!e) { if (d.lines.includes(line)) fresh.push(line); cover.set(line, { inputs: 1, hits: n }); }
|
||||
else { e.inputs++; e.hits += n; }
|
||||
}
|
||||
const c: FuzzCase = { n: cases.length + 1, strategy, call: d.call(args), args: args.map((v, i) => d.arg(v, i)), outcome: x.outcome, steps: x.steps,
|
||||
...(x.result !== undefined ? { result: x.result } : {}), ...(x.message ? { message: x.message } : {}), ...(x.kind ? { kind: x.kind } : {}), ...(x.line ? { line: x.line } : {}), ...(fresh.length ? { newLines: fresh.sort((a, b) => a - b) } : {}) };
|
||||
cases.push(c);
|
||||
byCall.set(c.call, args);
|
||||
counts[x.outcome]++;
|
||||
if (x.outcome === 'pass' && x.result !== undefined && strategy !== 'shrink' && strategy !== 'repeat') results.set(x.result, (results.get(x.result) ?? 0) + 1);
|
||||
if (fresh.length && x.outcome !== 'skip') corpus.push(args);
|
||||
return { c, x };
|
||||
};
|
||||
|
||||
/** A failure: shrink it, keeping every step, while the smaller input still fails the same way. */
|
||||
const shrink = (args: T[], first: { c: FuzzCase; x: Exec }) => {
|
||||
const key = `${first.x.kind}@${first.x.line ?? ''}`;
|
||||
if (failKeys.has(key)) return;
|
||||
failKeys.add(key);
|
||||
let best = args, bestC = first.c;
|
||||
const path = [first.c.call];
|
||||
for (let rounds = 0; rounds < 60; rounds++) {
|
||||
let improved = false;
|
||||
for (const cand of d.smaller(best)) {
|
||||
const k = d.call(cand);
|
||||
if (seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
const t = tryOne(cand, 'shrink');
|
||||
if (!t) return;
|
||||
if (t.x.outcome === 'fail' && t.x.kind === first.x.kind) { best = cand; bestC = t.c; path.push(t.c.call); improved = true; break; }
|
||||
}
|
||||
if (!improved) break;
|
||||
}
|
||||
failures.push({ kind: first.x.kind ?? 'error', message: bestC.message ?? first.c.message ?? '', line: bestC.line, call: bestC.call, found: first.c.call, shrink: path, n: first.c.n });
|
||||
};
|
||||
|
||||
const consider = (args: T[], strategy: Strategy): boolean => {
|
||||
const k = d.call(args);
|
||||
if (seen.has(k)) return true;
|
||||
seen.add(k);
|
||||
const t = tryOne(args, strategy);
|
||||
if (!t) return false;
|
||||
if (t.x.outcome === 'fail' && failures.length < 5) shrink(args, t);
|
||||
return true;
|
||||
};
|
||||
|
||||
const room = () => cases.length < budget && !problem;
|
||||
// 1. edge cases, in combination (a quarter of the budget at most)
|
||||
for (const a of d.edges()) { if (!room() || used.edge >= budget / 4) break; if (!consider(a, 'edge')) return report(); }
|
||||
// 2. every short string, when the routine reads one
|
||||
for (const a of d.exhaustive()) { if (!room() || used.exhaustive >= budget * 0.3) break; if (!consider(a, 'exhaustive')) return report(); }
|
||||
// 3. random values, and mutations of the inputs that found new lines
|
||||
let misses = 0;
|
||||
while (room() && misses < budget * 4) {
|
||||
const mutate = corpus.length > 0 && r() < 0.4;
|
||||
const args = mutate ? d.mutate(corpus[Math.floor(r() * corpus.length)], r) : d.random(r);
|
||||
const before = cases.length;
|
||||
if (!consider(args, mutate ? 'mutate' : 'random')) return report();
|
||||
if (cases.length === before) misses++;
|
||||
}
|
||||
// 4. the same answer twice: a few passing inputs again
|
||||
const again = cases.filter((c) => c.outcome === 'pass' && c.strategy !== 'shrink').slice(0, 8);
|
||||
for (const c of again) {
|
||||
const args = findArgs(c);
|
||||
if (!args) continue;
|
||||
const x = d.exec(args);
|
||||
used.repeat++;
|
||||
const same = x.outcome === 'pass' && x.result === c.result;
|
||||
const rc: FuzzCase = { n: cases.length + 1, strategy: 'repeat', call: c.call, args: c.args, outcome: same ? 'pass' : 'fail', steps: x.steps, ...(x.result !== undefined ? { result: x.result } : {}) };
|
||||
if (!same) { rc.kind = 'nondeterministic'; rc.message = `gave ${c.result} the first time and ${x.result ?? x.message} the second`; failures.push({ kind: 'nondeterministic', message: rc.message, call: c.call, found: c.call, shrink: [c.call], n: rc.n }); }
|
||||
cases.push(rc);
|
||||
counts[rc.outcome]++;
|
||||
}
|
||||
return report();
|
||||
|
||||
function findArgs(c: FuzzCase): T[] | null { return byCall.get(c.call) ?? null; }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* pseudo */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const DNA = ['A', 'C', 'G', 'T'];
|
||||
|
||||
interface PGen { edges: any[]; random(r: () => number): any; mutate(v: any, r: () => number): any; smaller(v: any): Iterable<any>; how: string }
|
||||
|
||||
function pseudoGen(t: any): PGen | null {
|
||||
const pick = <X>(xs: X[], r: () => number) => xs[Math.floor(r() * xs.length)];
|
||||
const int = (lo: number, hi: number, r: () => number) => lo + Math.floor(r() * (hi - lo + 1));
|
||||
switch (t?.k) {
|
||||
case 'INTEGER': return {
|
||||
edges: [0, 1, -1, 2, 10, -10, 100], how: 'whole numbers: 0, 1, -1, 2, 10, -10, 100 first, then mostly -3 to 12',
|
||||
random: (r) => (r() < 0.3 ? pick([0, 1, 2, -1], r) : int(-3, 12, r)),
|
||||
mutate: (v, r) => pick([v + 1, v - 1, v * 2, -v, 0], r),
|
||||
*smaller(v) { if (v !== 0) { yield 0; yield v > 0 ? v - 1 : v + 1; if (Math.abs(v) > 2) yield Math.trunc(v / 2); } },
|
||||
};
|
||||
case 'FLOAT': return {
|
||||
edges: [0, 1, -1, 0.5, -2.5, 100.25], how: 'decimals: 0, 1, -1, 0.5, -2.5, 100.25 first, then -2 to 10 in hundredths',
|
||||
random: (r) => Math.round((r() * 12 - 2) * 100) / 100, mutate: (v, r) => pick([v * 2, -v, v + 0.5, 0], r),
|
||||
*smaller(v) { if (v !== 0) { yield 0; yield Math.trunc(v); } },
|
||||
};
|
||||
case 'BOOL': return { edges: [false, true], how: 'TRUE and FALSE', random: (r) => r() < 0.5, mutate: (v) => !v, *smaller(v) { if (v) yield false; } };
|
||||
case 'CHAR': return {
|
||||
edges: [...DNA, 'N'], how: 'a DNA letter (A, C, G, T), sometimes N',
|
||||
random: (r) => (r() < 0.08 ? 'N' : pick(DNA, r)), mutate: (v, r) => pick([...DNA, 'N'].filter((c) => c !== v), r),
|
||||
*smaller(v) { if (v !== 'A') yield 'A'; },
|
||||
};
|
||||
case 'STRING': return {
|
||||
edges: ['', 'A', 'AA', 'AC', 'GATTACA', 'NNN', 'ACGTACGTAC'], how: 'DNA letters (A, C, G, T, sometimes N), 0 to 9 long: "", "A", "AA", "AC", "GATTACA", "NNN", "ACGTACGTAC" first',
|
||||
random: (r) => { const n = r() < 0.12 ? int(0, 1, r) : int(0, 9, r); let s = ''; for (let i = 0; i < n; i++) s += r() < 0.06 ? 'N' : pick(DNA, r); return s; },
|
||||
mutate: (v, r) => {
|
||||
const cs = [...v]; const i = int(0, cs.length, r);
|
||||
const how = cs.length ? Math.floor(r() * 4) : 0;
|
||||
if (how === 0) cs.splice(i, 0, pick(DNA, r)); else if (how === 1) cs.splice(Math.min(i, cs.length - 1), 1); else if (how === 2) cs[Math.min(i, cs.length - 1)] = pick(DNA, r); else cs.push(...cs.slice(0, 2));
|
||||
return cs.join('');
|
||||
},
|
||||
*smaller(v) { const cs = [...v]; for (let i = 0; i < cs.length; i++) yield cs.slice(0, i).concat(cs.slice(i + 1)).join(''); for (let i = 0; i < cs.length; i++) if (cs[i] !== 'A') yield cs.slice(0, i).concat(['A'], cs.slice(i + 1)).join(''); },
|
||||
};
|
||||
case 'LIST': case 'ARRAY': case 'SET': {
|
||||
const el = pseudoGen(t.of);
|
||||
if (!el) return null;
|
||||
const make = (xs: any[]) => (t.k === 'ARRAY' ? Object.assign(new PArray([xs.length]), { data: xs }) : t.k === 'SET' ? new Set(xs) : xs);
|
||||
const items = (v: any): any[] => (v instanceof PArray ? [...(v as any).data] : v instanceof Set ? [...v] : [...v]);
|
||||
return {
|
||||
edges: [make([]), make([el.edges[0]]), make([el.edges[0], el.edges[0]]), make(el.edges.slice(0, 3))],
|
||||
how: `${t.k === 'SET' ? 'sets' : t.k === 'ARRAY' ? 'arrays' : 'lists'} of 0 to 6 elements, each ${el.how.split(':')[0].split(',')[0]}`,
|
||||
random: (r) => make(Array.from({ length: int(0, 6, r) }, () => el.random(r))),
|
||||
mutate: (v, r) => { const xs = items(v); const i = int(0, Math.max(0, xs.length - 1), r); const how = xs.length ? Math.floor(r() * 3) : 0; if (how === 0) xs.splice(i, 0, el.random(r)); else if (how === 1) xs.splice(i, 1); else xs[i] = el.mutate(xs[i], r); return make(xs); },
|
||||
*smaller(v) { const xs = items(v); for (let i = 0; i < xs.length; i++) yield make(xs.slice(0, i).concat(xs.slice(i + 1))); for (let i = 0; i < xs.length; i++) for (const s of el.smaller(xs[i])) { const c = xs.slice(); c[i] = s; yield make(c); } },
|
||||
};
|
||||
}
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every line a routine's statements are on (its coverage denominator). */
|
||||
function pseudoLines(node: any): number[] {
|
||||
const out = new Set<number>();
|
||||
const seen = new WeakSet<object>();
|
||||
const walk = (x: any, depth: number) => {
|
||||
if (!x || typeof x !== 'object' || depth > 60 || seen.has(x)) return;
|
||||
seen.add(x);
|
||||
if (Array.isArray(x)) { for (const y of x) walk(y, depth + 1); return; }
|
||||
if (typeof x.line === 'number') out.add(x.line);
|
||||
for (const [k, v] of Object.entries(x)) if (k !== 'type' && k !== 'scope' && k !== 'symbols' && v && typeof v === 'object') walk(v, depth + 1);
|
||||
};
|
||||
walk(node?.body ?? [], 0);
|
||||
return [...out].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
export function fuzzPseudo(program: any, name: string, opts: FuzzOptions = {}): FuzzReport {
|
||||
const sub = program.subs.get(String(name).toUpperCase());
|
||||
const empty = (problem: string): FuzzReport => ({ name, signature: name, lang: 'pseudo', params: [], seed: opts.seed ?? 1, budget: opts.budget ?? 300, checks: [], strategies: [], cases: [], failures: [], counts: { pass: 0, fail: 0, skip: 0, raises: 0 }, coverage: [], results: [], problem });
|
||||
if (!sub) return empty(`No routine called ${name}.`);
|
||||
const typeWord = (t: any): string => (!t ? '' : t.k === 'LIST' || t.k === 'SET' ? `${t.k} OF ${typeWord(t.of)}` : t.k === 'ARRAY' ? `ARRAY OF ${typeWord(t.of)}` : t.k);
|
||||
const signature = `${sub.name}(${sub.params.map((p: any) => `${p.name} : ${typeWord(p.type)}`).join(', ')})${sub.returns ? ` RETURNS ${typeWord(sub.returns)}` : ''}`;
|
||||
const gens = sub.params.map((p: any) => pseudoGen(p.type));
|
||||
const missing = sub.params.findIndex((_: any, i: number) => !gens[i]);
|
||||
if (missing >= 0) return { ...empty(`No generator for ${sub.params[missing].name}'s type (${typeWord(sub.params[missing].type)}): whole numbers, decimals, booleans, characters, strings, and lists, arrays and sets of those are generated.`), signature };
|
||||
const g = gens as PGen[];
|
||||
const fmt = (v: any, t: any) => formatValue(v, t);
|
||||
const contracts = (sub.requires?.length ? 1 : 0) + (sub.ensures?.length ? 1 : 0);
|
||||
const checks = [
|
||||
'It runs to the end without a runtime error: an index out of range, a value used before it is set, a division by zero, a value of the wrong type.',
|
||||
sub.requires?.length ? `Inputs that break a REQUIRE (${sub.requires.length} written) are skipped, not failed: the caller promised never to pass them.` : 'There is no REQUIRE, so every input counts.',
|
||||
sub.ensures?.length ? `Every ENSURE (${sub.ensures.length} written) holds when it returns, and every INVARIANT, DECREASES and ASSERT holds on the way.` : 'Every INVARIANT, DECREASES and ASSERT written in it holds on the way (it has no ENSURE to check the answer against).',
|
||||
'It finishes within 50,000 steps.',
|
||||
'Run again on the same input, it gives the same answer.',
|
||||
];
|
||||
void contracts;
|
||||
const driver: Driver<any> = {
|
||||
name: sub.name, signature, lang: 'pseudo', checks,
|
||||
params: sub.params.map((p: any, i: number) => ({ name: p.name, type: typeWord(p.type), how: g[i].how })),
|
||||
lines: pseudoLines(sub.node),
|
||||
edges() {
|
||||
const out: any[][] = [];
|
||||
const combine = (i: number, acc: any[]) => { if (out.length >= 400) return; if (i === g.length) { out.push(acc); return; } for (const v of g[i].edges) combine(i + 1, [...acc, v]); };
|
||||
combine(0, []);
|
||||
return out;
|
||||
},
|
||||
exhaustive() {
|
||||
const strs = sub.params.map((p: any, i: number) => (p.type?.k === 'STRING' ? i : -1)).filter((i: number) => i >= 0);
|
||||
if (strs.length !== 1 || sub.params.length > 2) return [];
|
||||
const all: string[] = [''];
|
||||
let layer = [''];
|
||||
for (let n = 1; n <= 3; n++) { const next: string[] = []; for (const s of layer) for (const c of DNA) next.push(s + c); all.push(...next); layer = next; }
|
||||
const other = sub.params.findIndex((_: any, i: number) => i !== strs[0]);
|
||||
const others = other < 0 ? [null] : g[other].edges.slice(0, 5);
|
||||
const out: any[][] = [];
|
||||
for (const s of all) for (const o of others) { const a: any[] = []; a[strs[0]] = s; if (other >= 0) a[other] = o; out.push(a); }
|
||||
return out;
|
||||
},
|
||||
random: (r) => g.map((x) => x.random(r)),
|
||||
mutate(args, r) { const i = Math.floor(r() * args.length); const a = args.slice(); if (a.length) a[i] = g[i].mutate(cloneValue(a[i]), r); return a; },
|
||||
*smaller(args) { for (let i = 0; i < args.length; i++) for (const s of g[i].smaller(args[i])) { const a = args.slice(); a[i] = s; yield a; } },
|
||||
call: (args) => `${sub.name}(${args.map((a, i) => fmt(a, sub.params[i].type)).join(', ')})`,
|
||||
arg: (v, i) => fmt(v, sub.params[i].type),
|
||||
exec(args) {
|
||||
const tr: any = run(program, { call: { name: sub.name, args: args.map(cloneValue) }, record: false, maxSteps: 50000 });
|
||||
const hits: Map<number, number> = tr.hits ?? new Map();
|
||||
const steps = tr.work?.steps ?? 0;
|
||||
if (tr.error?.kind === 'require') return { outcome: 'skip', message: tr.error.message, kind: 'require', line: tr.error.line, steps, hits };
|
||||
if (tr.error) return { outcome: 'fail', message: tr.error.message, kind: tr.error.kind, line: tr.error.line, steps, hits };
|
||||
return { outcome: 'pass', result: sub.returns ? fmt(tr.result, sub.returns) : tr.output?.length ? `prints ${tr.output.map((x: string) => JSON.stringify(x)).join(', ')}` : '(no answer)', steps, hits };
|
||||
},
|
||||
};
|
||||
return fuzz(driver, opts);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mojo */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
type DefStmt = Extract<Stmt, { k: 'def' }>;
|
||||
|
||||
function mojoMutate(v: V, r: () => number): V {
|
||||
const pick = <X>(xs: X[]) => xs[Math.floor(r() * xs.length)];
|
||||
switch (v.k) {
|
||||
case 'int': { const n = pick([v.v + 1n, v.v - 1n, v.v * 2n, -v.v, 0n]); return { ...v, v: n }; }
|
||||
case 'float': return { ...v, v: pick([v.v * 2, -v.v, v.v + 0.5, 0]) };
|
||||
case 'bool': return { ...v, v: !v.v };
|
||||
case 'str': {
|
||||
const cs = [...v.v]; const i = Math.floor(r() * (cs.length + 1)); const how = cs.length ? Math.floor(r() * 3) : 0; const alphabet = [...'abcAGCT 0é'];
|
||||
if (how === 0) cs.splice(i, 0, pick(alphabet)); else if (how === 1) cs.splice(Math.min(i, cs.length - 1), 1); else cs[Math.min(i, cs.length - 1)] = pick(alphabet);
|
||||
return { ...v, v: cs.join('') };
|
||||
}
|
||||
case 'list': {
|
||||
const items = v.items.slice(); const i = Math.floor(r() * Math.max(1, items.length)); const how = items.length ? Math.floor(r() * 3) : 0;
|
||||
if (how === 0) items.splice(i, 0, items[0] ?? { k: 'int', v: 0n, width: 64, signed: true, type: 'Int' } as V); else if (how === 1) items.splice(i, 1); else items[i] = mojoMutate(items[i], r);
|
||||
return { ...v, items, cap: items.length };
|
||||
}
|
||||
default: return v;
|
||||
}
|
||||
}
|
||||
|
||||
function* mojoSmaller(v: V): Iterable<V> {
|
||||
if (v.k === 'int' && v.v !== 0n) { yield { ...v, v: 0n }; yield { ...v, v: v.v > 0n ? v.v - 1n : v.v + 1n }; if (v.v > 2n || v.v < -2n) yield { ...v, v: v.v / 2n }; }
|
||||
if (v.k === 'float' && v.v !== 0) { yield { ...v, v: 0 }; yield { ...v, v: Math.trunc(v.v) }; }
|
||||
if (v.k === 'bool' && v.v) yield { ...v, v: false };
|
||||
if (v.k === 'str') { const cs = [...v.v]; for (let i = 0; i < cs.length; i++) yield { ...v, v: cs.slice(0, i).concat(cs.slice(i + 1)).join('') }; for (let i = 0; i < cs.length; i++) if (cs[i] !== 'a') yield { ...v, v: cs.slice(0, i).concat(['a'], cs.slice(i + 1)).join('') }; }
|
||||
if (v.k === 'list') { for (let i = 0; i < v.items.length; i++) { const items = v.items.slice(0, i).concat(v.items.slice(i + 1)); yield { ...v, items, cap: items.length }; } }
|
||||
}
|
||||
|
||||
function mojoLines(d: DefStmt): number[] {
|
||||
const out = new Set<number>();
|
||||
const seen = new WeakSet<object>();
|
||||
const walk = (x: any, depth: number) => {
|
||||
if (!x || typeof x !== 'object' || depth > 80 || seen.has(x)) return;
|
||||
seen.add(x);
|
||||
if (Array.isArray(x)) { for (const y of x) walk(y, depth + 1); return; }
|
||||
if (x.k === 'def' && depth > 0) return; // a nested function is its own routine
|
||||
if (typeof x.pos?.line === 'number' && typeof x.k === 'string' && !('value' in x && x.k === 'name')) out.add(x.pos.line);
|
||||
for (const [k, v] of Object.entries(x)) if (k !== 'pos' && v && typeof v === 'object') walk(v, depth + 1);
|
||||
};
|
||||
walk(d.body, 1);
|
||||
return [...out].filter((l) => l > d.pos.line).sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
export function fuzzMojo(mod: Module, source: string, name: string, opts: FuzzOptions = {}): FuzzReport {
|
||||
const d = mod.body.find((s): s is DefStmt => s.k === 'def' && s.name === name);
|
||||
const empty = (problem: string, signature = name): FuzzReport => ({ name, signature, lang: 'mojo', params: [], seed: opts.seed ?? 1, budget: opts.budget ?? 300, checks: [], strategies: [], cases: [], failures: [], counts: { pass: 0, fail: 0, skip: 0, raises: 0 }, coverage: [], results: [], problem });
|
||||
if (!d) return empty(`No function called ${name}.`);
|
||||
const params = d.params.filter((p) => p.star !== 'marker' && p.star !== 'positional-marker');
|
||||
const signature = `${d.name}(${params.map((p) => `${p.name}: ${mojoType(p.type)}`).join(', ')})${d.raises ? ' raises' : ''}${d.ret ? ` -> ${mojoType(d.ret as any)}` : ''}`;
|
||||
if (d.typeParams.length) return empty('This function has compile-time parameters; generated inputs cover plain arguments only.', signature);
|
||||
const gens: Gen[] = [];
|
||||
for (const p of params) {
|
||||
if (p.star || p.convention === 'mut' || p.convention === 'out' || p.convention === 'ref' || p.convention === 'inout') return empty(`${p.name} is passed as ${p.star ? 'a variadic' : p.convention}: generated inputs cover arguments passed by value only.`, signature);
|
||||
const g = generator(mojoType(p.type));
|
||||
if (!g) return empty(`No generator for ${p.name}'s type (${mojoType(p.type) || 'none written'}): Int, the sized integers, Float64, Bool, String, and a List of those are generated.`, signature);
|
||||
gens.push(g);
|
||||
}
|
||||
const HOW: Record<string, string> = { String: 'text from the letters a b c A G C T, a space, 0 and é, 0 to 6 long: "", "a", "A", "ab", "aa", "ba", "GATTACA", " ", "é", "0" first', Bool: 'True and False', Float64: 'decimals: 0, 1, -1, 0.5, -0.5, 2.5, 1e10, -1e10 first, then -100 to 100 in hundredths', Float32: 'decimals, as Float64 but 32-bit' };
|
||||
const how = (t: string): string => HOW[t] ?? (/^List\[/.test(t) ? `lists of 0 to 5 elements of ${t.slice(5, -1)}` : `whole numbers of ${t}: 0, 1, -1, 2, 3, 10, 100 and the type's extremes first, then mostly -100 to 100, sometimes up to ±1e9`);
|
||||
const driver: Driver<V> = {
|
||||
name: d.name, signature, lang: 'mojo',
|
||||
params: params.map((p) => ({ name: p.name, type: mojoType(p.type), how: how(mojoType(p.type)) })),
|
||||
checks: [
|
||||
'It does not abort: an index out of bounds stops a compiled Mojo program (exit 132).',
|
||||
d.raises ? 'It says raises, so what it raises is listed, not failed.' : 'It raises nothing that nobody catches (it does not say raises).',
|
||||
'It finishes within 5,000 steps of Programming+\'s interpreter.',
|
||||
'Run again on the same input, it gives the same answer.',
|
||||
'Integers that wrap and an Int division by zero (which is 0) are Mojo\'s behavior, not failures.',
|
||||
],
|
||||
lines: mojoLines(d),
|
||||
edges() {
|
||||
const out: V[][] = [];
|
||||
const combine = (i: number, acc: V[]) => { if (out.length >= 400) return; if (i === gens.length) { out.push(acc); return; } for (const v of gens[i].edges) combine(i + 1, [...acc, v]); };
|
||||
combine(0, []);
|
||||
return out;
|
||||
},
|
||||
exhaustive: () => [],
|
||||
random: (r) => gens.map((g) => g.random(r)),
|
||||
mutate(args, r) { if (!args.length) return args; const i = Math.floor(r() * args.length); const a = args.slice(); a[i] = mojoMutate(a[i], r); return a; },
|
||||
*smaller(args) { for (let i = 0; i < args.length; i++) for (const s of mojoSmaller(args[i])) { const a = args.slice(); a[i] = s; yield a; } },
|
||||
call: (args) => `${d.name}(${args.map(literal).join(', ')})`,
|
||||
arg: (v) => literal(v),
|
||||
exec(args) {
|
||||
const { outcome: o, hits, steps } = probeMojo(mod, source, d.name, args);
|
||||
switch (o.kind) {
|
||||
case 'declined': return { outcome: 'declined', message: `Programming+ cannot run ${d.name} yet: ${o.reason}.`, steps, hits };
|
||||
case 'returned': return { outcome: 'pass', result: o.value ? showMojo(o.value) : 'None', steps, hits };
|
||||
case 'aborted': return { outcome: 'fail', kind: 'bounds', message: `aborts: ${o.message}`, line: o.line, steps, hits };
|
||||
case 'limit': return { outcome: 'fail', kind: 'limit', message: 'ran past the 5,000-step limit: an endless loop or recursion, or a lot of work (the compiled program may finish; this says Programming+ stopped waiting)', steps, hits };
|
||||
case 'raised': return d.raises
|
||||
? { outcome: 'raises', kind: 'raises-declared', message: `raises ${o.message} (it says raises, so this may be intended)`, line: o.line ?? undefined, steps, hits }
|
||||
: { outcome: 'fail', kind: 'raise', message: `raises ${o.message}, which nothing catches`, line: o.line ?? undefined, steps, hits };
|
||||
}
|
||||
},
|
||||
};
|
||||
return fuzz(driver, opts);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* The Hardware area's machine board, without the DOM (restructure plan, Stage 15). The views themselves are the
|
||||
* course's (`src/engines/asm86/views.js` and `hwviews.js`), mounted by `src/ui/hw/board.ts`; this module decides
|
||||
* what they are given: which views a preset shows and with what options, and the frame each one draws. Everything
|
||||
* here runs under `node --test`, so the board's data steps are tested without a browser.
|
||||
*/
|
||||
import { REGS } from '../engines/asm86/interp.js';
|
||||
import { PRESETS } from '../engines/asm86/machine.js';
|
||||
|
||||
/* ---------- the machine ---------- */
|
||||
|
||||
/** The machine models a run can use: `teaching` (small caches, so misses happen on small data), `realistic` (shaped like a desktop core), `ideal`. */
|
||||
export const MACHINE_PRESETS: readonly string[] = Object.keys(PRESETS);
|
||||
|
||||
/** A machine as the state names it: a preset, with virtual memory (paging and a TLB) on or off. `teaching+paging` is the teaching machine with paging on. */
|
||||
export interface MachineChoice { preset: string; paging: boolean }
|
||||
|
||||
const PAGING = '+paging';
|
||||
|
||||
export function parseMachine(name: string | null | undefined): MachineChoice {
|
||||
const raw = String(name ?? '').trim();
|
||||
const paging = raw.endsWith(PAGING);
|
||||
const preset = paging ? raw.slice(0, -PAGING.length) : raw;
|
||||
return { preset: MACHINE_PRESETS.includes(preset) ? preset : 'teaching', paging };
|
||||
}
|
||||
|
||||
export const machineName = (c: MachineChoice): string => `${c.preset}${c.paging ? PAGING : ''}`;
|
||||
|
||||
/** What the engine's hardware model is given (`trace.spec.machine`): the preset's name, or the preset with paging switched on. */
|
||||
export function machineSpec(name: string | null | undefined): string | { preset: string; paging: { enabled: true } } {
|
||||
const c = parseMachine(name);
|
||||
return c.paging ? { preset: c.preset, paging: { enabled: true } } : c.preset;
|
||||
}
|
||||
|
||||
/** The machine in a few words, for captions. */
|
||||
export const machineLabel = (name: string | null | undefined): string => { const c = parseMachine(name); return c.paging ? `${c.preset}, with virtual memory` : c.preset; };
|
||||
|
||||
/* ---------- the board ---------- */
|
||||
|
||||
/**
|
||||
* Everything the Hardware area's board can show, one card each. Course views are mounted by name with options
|
||||
* (`course`); the others are the app's own: the run setup, the output, the problems, the compiler, the Run view,
|
||||
* the counters, and the cache-line view. `needs` is the pane whose run a view reads: the machine views read the
|
||||
* x86-64 pane's run, the Run view and the compiler the Mojo pane's; a card whose pane is not open says so.
|
||||
*/
|
||||
export type BoardViewId =
|
||||
| 'registers' | 'flags' | 'address' | 'memory' | 'stack' | 'explain' | 'dataflow' | 'bits' | 'branches' | 'vectors'
|
||||
| 'lines' | 'cache' | 'hierarchy' | 'paging'
|
||||
| 'pipeline' | 'uops' | 'timeline' | 'bottleneck' | 'core' | 'machine' | 'encoding' | 'code'
|
||||
| 'setup' | 'output' | 'problems' | 'compiler' | 'run' | 'counters';
|
||||
|
||||
export interface BoardViewDef {
|
||||
id: BoardViewId;
|
||||
label: string;
|
||||
group: string;
|
||||
/** What it shows, in a line (the add menu, the card's tooltip). */
|
||||
blurb: string;
|
||||
needs: 'asm' | 'mojo' | 'any';
|
||||
/** Takes the board's whole width unless the student narrows it. */
|
||||
wide: boolean;
|
||||
/** A course view: its name in views.js / hwviews.js and its options for a run. */
|
||||
course?: { name: string; options?: (trace: any, machine: MachineChoice) => Record<string, unknown> };
|
||||
}
|
||||
|
||||
export const BOARD_GROUPS = ['Program', 'Registers and memory', 'Memory system', 'Time', 'The chip'] as const;
|
||||
|
||||
export const BOARD_VIEWS: BoardViewDef[] = [
|
||||
{ id: 'setup', label: 'Setup', group: 'Program', needs: 'any', wide: false, blurb: 'The run setup: registers, memory and input for x86-64; the build and input for Mojo; the machine.' },
|
||||
{ id: 'output', label: 'Output', group: 'Program', needs: 'any', wide: false, blurb: 'What the run has printed so far.' },
|
||||
{ id: 'problems', label: 'Problems', group: 'Program', needs: 'any', wide: false, blurb: 'Every message on the open pane, with its one-click fixes.' },
|
||||
{ id: 'compiler', label: 'Compiler', group: 'Program', needs: 'mojo', wide: true, blurb: 'The real Mojo compiler on godbolt: its messages, the output, and the listing, with Open in Hardware for a function.' },
|
||||
{ id: 'run', label: 'Run', group: 'Program', needs: 'mojo', wide: true, blurb: 'The Mojo run top to bottom, with the variables you follow and their lifetimes.' },
|
||||
{ id: 'code', label: 'Machine code listing', group: 'Program', needs: 'asm', wide: false, blurb: 'Every instruction with its address and bytes, the one about to run marked.', course: { name: 'code', options: () => ({ addresses: true, bytes: true, heat: true }) } },
|
||||
{ id: 'explain', label: 'What it did', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'The last instruction in words: what it read, computed and wrote.', course: { name: 'explain' } },
|
||||
{ id: 'registers', label: 'Registers', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'A card per register the program touches, with the value before and every narrower name it uses.', course: { name: 'registers', options: (trace) => ({ widths: subRegisterWidths(trace.program) }) } },
|
||||
{ id: 'flags', label: 'Flags', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'ZF, SF, CF, OF, PF, with the ones the last instruction set and read.', course: { name: 'flags' } },
|
||||
{ id: 'address', label: 'Address arithmetic', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'base + index × scale + displacement, part by part.', course: { name: 'address' } },
|
||||
{ id: 'memory', label: 'Memory', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'Each memory region byte by byte, the load (blue) or store (purple) highlighted.', course: { name: 'memory' } },
|
||||
{ id: 'stack', label: 'Stack', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'Eight-byte slots with rsp and rbp marked, and what put each there.', course: { name: 'stack' } },
|
||||
{ id: 'dataflow', label: 'Data flow', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'Where the last instruction\'s values came from and went.', course: { name: 'dataflow' } },
|
||||
{ id: 'bits', label: 'Inside the ALU', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'The arithmetic unit at bit level for the last instruction.', course: { name: 'bits' } },
|
||||
{ id: 'branches', label: 'Branches', group: 'Registers and memory', needs: 'asm', wide: false, blurb: 'Each branch: taken or not, and whether the predictor guessed right.', course: { name: 'branches' } },
|
||||
{ id: 'vectors', label: 'Vector registers', group: 'Registers and memory', needs: 'asm', wide: true, blurb: 'The xmm registers lane by lane.', course: { name: 'vectors' } },
|
||||
{ id: 'lines', label: 'Cache lines', group: 'Memory system', needs: 'asm', wide: true, blurb: 'The cache line each load and store touched, and how many of its bytes the program uses.' },
|
||||
{ id: 'cache', label: 'L1d cache', group: 'Memory system', needs: 'asm', wide: true, blurb: 'The L1 data cache as sets and ways: a hit green, a miss red, the evicted line named.', course: { name: 'cache', options: () => ({ level: 'L1d' }) } },
|
||||
{ id: 'hierarchy', label: 'Memory hierarchy', group: 'Memory system', needs: 'asm', wide: false, blurb: 'L1, L2, L3 and memory: the path each access took, and running totals.', course: { name: 'hierarchy' } },
|
||||
{ id: 'paging', label: 'Virtual memory', group: 'Memory system', needs: 'asm', wide: true, blurb: 'The page walk and the TLB, with virtual memory on.', course: { name: 'paging' } },
|
||||
{ id: 'pipeline', label: 'Five-stage pipeline', group: 'Time', needs: 'asm', wide: true, blurb: 'Cycle by cycle: stalls amber, wrong-path fetches red.', course: { name: 'pipeline' } },
|
||||
{ id: 'uops', label: 'Micro-ops and ports', group: 'Time', needs: 'asm', wide: false, blurb: 'The micro-ops the last instruction became, and the ports each can run on.', course: { name: 'uops' } },
|
||||
{ id: 'timeline', label: 'Out-of-order timeline', group: 'Time', needs: 'asm', wide: true, blurb: 'When each instruction entered the core, ran and retired.', course: { name: 'timeline' } },
|
||||
{ id: 'bottleneck', label: 'What limits the speed', group: 'Time', needs: 'asm', wide: false, blurb: 'The dependency chain, the busiest ports and the front end, against the time taken.', course: { name: 'bottleneck' } },
|
||||
{ id: 'counters', label: 'Counters', group: 'Time', needs: 'asm', wide: false, blurb: 'The run as totals, in the style of perf stat, and what each Mojo line cost.' },
|
||||
{ id: 'machine', label: 'The whole core', group: 'The chip', needs: 'asm', wide: true, blurb: 'From the branch predictor to memory, the parts the last instruction used lit up.', course: { name: 'machine' } },
|
||||
{ id: 'core', label: 'Inside the out-of-order core', group: 'The chip', needs: 'asm', wide: true, blurb: 'The reorder buffer, the ports, and which physical register each name points at.', course: { name: 'core' } },
|
||||
{ id: 'encoding', label: 'Instruction encoding', group: 'The chip', needs: 'asm', wide: false, blurb: 'The bytes of the last instruction, broken into prefix, REX, opcode, ModRM, SIB, displacement and immediate.', course: { name: 'encoding' } },
|
||||
];
|
||||
|
||||
export const boardView = (id: string): BoardViewDef | undefined => BOARD_VIEWS.find((v) => v.id === id);
|
||||
|
||||
/** One card on the board: which view, and its width when the student changed it. */
|
||||
export interface BoardItem { id: BoardViewId; wide?: boolean }
|
||||
|
||||
export interface BoardPreset { id: string; label: string; blurb: string; items: BoardItem[] }
|
||||
|
||||
const items = (...ids: BoardViewId[]): BoardItem[] => ids.map((id) => ({ id }));
|
||||
|
||||
/** Arrangements that make sense to see at once; the student can change any of them. */
|
||||
export const BOARD_PRESETS: BoardPreset[] = [
|
||||
{ id: 'regs', label: 'Registers and memory', blurb: 'What each instruction does: the registers it writes, the flags, the address it computes, the bytes of memory it reads or writes, the stack.', items: items('registers', 'flags', 'address', 'memory', 'stack', 'output', 'setup') },
|
||||
{ id: 'caches', label: 'Caches', blurb: 'What memory costs: the cache line each access touches and how much of it is used, the L1 data cache, the hierarchy.', items: items('lines', 'cache', 'hierarchy', 'memory', 'output') },
|
||||
{ id: 'pipeline', label: 'Pipeline', blurb: 'Time: the five-stage pipeline, the micro-ops and ports, what limits the speed, the out-of-order timeline.', items: items('pipeline', 'uops', 'bottleneck', 'timeline') },
|
||||
// The listing and the encoding of the instruction it marks sit side by side; the out-of-order core, whose table
|
||||
// grows and shrinks with what is in flight, goes last so that nothing below it moves while stepping.
|
||||
{ id: 'chip', label: 'Whole chip', blurb: 'The whole core with the parts each instruction uses lit up, the machine code beside the encoding of the instruction it marks, and inside the out-of-order core.', items: items('machine', 'code', 'encoding', 'core') },
|
||||
{ id: 'mojo', label: 'Mojo and the compiler', blurb: 'The Mojo side: the run with its variables and lifetimes, the real compiler\'s answer and listing, the output.', items: items('run', 'compiler', 'output', 'problems') },
|
||||
];
|
||||
|
||||
export const boardPreset = (id: string | undefined | null): BoardPreset => BOARD_PRESETS.find((p) => p.id === id) ?? BOARD_PRESETS[0];
|
||||
|
||||
/** A saved arrangement, cleaned: known views only, each once, at most 24. */
|
||||
export function normalizeBoard(x: unknown): BoardItem[] | undefined {
|
||||
if (!Array.isArray(x)) return undefined;
|
||||
const out: BoardItem[] = [];
|
||||
for (const it of x) {
|
||||
const id = typeof it === 'string' ? it : it && typeof it === 'object' ? (it as any).id : null;
|
||||
if (typeof id !== 'string' || !boardView(id) || out.some((o) => o.id === id)) continue;
|
||||
const wide = it && typeof it === 'object' && typeof (it as any).wide === 'boolean' ? (it as any).wide : undefined;
|
||||
out.push(wide === undefined ? { id: id as BoardViewId } : { id: id as BoardViewId, wide });
|
||||
if (out.length >= 24) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether a card is drawn at the board's whole width. */
|
||||
export const isWide = (it: BoardItem): boolean => it.wide ?? boardView(it.id)!.wide;
|
||||
|
||||
/** The preset an arrangement is, or null when the student has made it their own. */
|
||||
export function presetOf(list: BoardItem[]): string | null {
|
||||
const same = (a: BoardItem[], b: BoardItem[]) => a.length === b.length && a.every((x, i) => x.id === b[i].id && isWide(x) === isWide(b[i]));
|
||||
return BOARD_PRESETS.find((p) => same(p.items, list))?.id ?? null;
|
||||
}
|
||||
|
||||
/** The arrangement with the card at `from` moved to position `to` (drag and drop, or the move buttons). */
|
||||
export function moveItem(list: BoardItem[], from: number, to: number): BoardItem[] {
|
||||
if (from < 0 || from >= list.length) return list.slice();
|
||||
const out = list.slice();
|
||||
const [it] = out.splice(from, 1);
|
||||
out.splice(Math.max(0, Math.min(to, out.length)), 0, it);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function addItem(list: BoardItem[], id: BoardViewId, at = list.length): BoardItem[] {
|
||||
if (!boardView(id) || list.some((x) => x.id === id)) return list.slice();
|
||||
const out = list.slice();
|
||||
out.splice(Math.max(0, Math.min(at, out.length)), 0, { id });
|
||||
return out;
|
||||
}
|
||||
|
||||
export const removeItem = (list: BoardItem[], id: BoardViewId): BoardItem[] => list.filter((x) => x.id !== id);
|
||||
|
||||
export const toggleWide = (list: BoardItem[], id: BoardViewId): BoardItem[] => list.map((x) => (x.id === id ? { id, wide: !isWide(x) } : x));
|
||||
|
||||
/** The course views a set of cards mounts, with their options for this run (the board's data step). Paging only with virtual memory on. */
|
||||
export function courseViews(list: BoardItem[], trace: any, machine: MachineChoice): Array<{ id: BoardViewId; name: string; options: Record<string, unknown> }> {
|
||||
return list.flatMap((it) => {
|
||||
const v = boardView(it.id)!;
|
||||
if (!v.course) return [];
|
||||
if (v.id === 'paging' && !machine.paging) return [];
|
||||
return [{ id: v.id, name: v.course.name, options: v.course.options ? v.course.options(trace, machine) : {} }];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The 64-bit registers the program also uses under a narrower name (`eax`, `al`, `r8b`): their card shows every
|
||||
* width, so `mov al, …` visibly changes only the low byte of `rax`. `rax` always does, since it holds the answer.
|
||||
*/
|
||||
export function subRegisterWidths(program: any): string[] {
|
||||
const out = new Set<string>(['rax']);
|
||||
for (const ins of program?.instrs ?? []) {
|
||||
for (const o of ins.operands ?? []) {
|
||||
const names = o.kind === 'reg' ? [o.name] : o.kind === 'mem' ? [o.base, o.index] : [];
|
||||
for (const n of names) {
|
||||
const r = n && (REGS as any)[n];
|
||||
if (r && !r.vector && r.base !== n) out.add(r.base);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** A frame is everything a course view needs to draw one moment (the same shape as `frameAt` in views.js). */
|
||||
export interface BoardFrame { t: number; trace: any; state: any; last: any; next: any }
|
||||
|
||||
export function boardFrame(trace: any, t: number): BoardFrame {
|
||||
const clamped = Math.max(0, Math.min(Math.floor(Number(t) || 0), trace.count));
|
||||
const state = trace.states[clamped];
|
||||
const last = clamped > 0 ? trace.steps[clamped - 1] : null;
|
||||
const next = state.pc < trace.program.instrs.length && !state.halted ? trace.program.instrs[state.pc] : null;
|
||||
return { t: clamped, trace, state, last, next };
|
||||
}
|
||||
|
||||
/* ---------- cache lines ---------- */
|
||||
|
||||
/** One cache line touched by one memory access of the step that just ran. */
|
||||
export interface LineTouch {
|
||||
kind: 'read' | 'write';
|
||||
/** The access: its address as the program wrote it, the physical address the caches saw (the same without virtual memory), and its size in bytes. */
|
||||
vaddr: number;
|
||||
addr: number;
|
||||
size: number;
|
||||
/** The line: its address and size, and the bytes of it this access covered, as offsets [from, to). */
|
||||
lineAddr: number;
|
||||
lineSize: number;
|
||||
from: number;
|
||||
to: number;
|
||||
/** Where the line was found: L1d (a hit), L2, L3, or memory. */
|
||||
level: string;
|
||||
hit: boolean;
|
||||
/** Bytes of this line the program has used so far (this access included), and in the whole run, as sorted offsets. */
|
||||
usedSoFar: number[];
|
||||
usedInRun: number[];
|
||||
/** What put the access there when it was not an instruction's own operand: a push, a call's return address, the kernel. */
|
||||
stack: string | null;
|
||||
kernel: boolean;
|
||||
}
|
||||
|
||||
/** For each line, the step at which each of its bytes was first used. Computed once per hardware model. */
|
||||
const firstUse = new WeakMap<object, Map<number, Map<number, number>>>();
|
||||
|
||||
function usesOf(hw: any): Map<number, Map<number, number>> {
|
||||
const hit = firstUse.get(hw);
|
||||
if (hit) return hit;
|
||||
const mem = hw.memory();
|
||||
const L: number = mem.hierarchy.line;
|
||||
const lines = new Map<number, Map<number, number>>();
|
||||
mem.steps.forEach((rec: any, k: number) => {
|
||||
for (const r of rec.data) {
|
||||
for (let b = r.addr; b < r.addr + Math.max(1, r.size); b++) {
|
||||
const lineAddr = Math.floor(b / L) * L;
|
||||
let m = lines.get(lineAddr);
|
||||
if (!m) { m = new Map(); lines.set(lineAddr, m); }
|
||||
if (!m.has(b - lineAddr)) m.set(b - lineAddr, k);
|
||||
}
|
||||
}
|
||||
});
|
||||
firstUse.set(hw, lines);
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cache lines the step that just ran (step t-1) touched with its loads and stores: which line, which bytes of
|
||||
* it, where it was found, and how many of its bytes the program uses so far and in the whole run. A program that
|
||||
* reads one byte of each 64-byte line moves 64 bytes for every one it uses; this is where that shows.
|
||||
*/
|
||||
export function lineTouches(hw: any, t: number): LineTouch[] {
|
||||
const mem = hw.memory();
|
||||
const k = Math.floor(Number(t) || 0) - 1;
|
||||
if (k < 0 || k >= mem.steps.length) return [];
|
||||
const L: number = mem.hierarchy.line;
|
||||
const uses = usesOf(hw);
|
||||
const out: LineTouch[] = [];
|
||||
for (const r of mem.steps[k].data) {
|
||||
for (const line of r.lines) {
|
||||
const m = uses.get(line.lineAddr) ?? new Map<number, number>();
|
||||
const soFar = [...m].filter(([, at]) => at <= k).map(([off]) => off).sort((a, b) => a - b);
|
||||
out.push({
|
||||
kind: r.kind === 'write' ? 'write' : 'read', vaddr: r.vaddr ?? r.addr, addr: r.addr, size: r.size,
|
||||
lineAddr: line.lineAddr, lineSize: L,
|
||||
from: Math.max(r.addr, line.lineAddr) - line.lineAddr,
|
||||
to: Math.min(r.addr + Math.max(1, r.size), line.lineAddr + L) - line.lineAddr,
|
||||
level: line.level, hit: !!line.trail[0]?.hit,
|
||||
usedSoFar: soFar, usedInRun: [...m.keys()].sort((a, b) => a - b),
|
||||
stack: r.stack ?? null, kernel: !!r.kernel,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ---------- Mojo beside x86-64 ---------- */
|
||||
|
||||
/**
|
||||
* The line table of x86-64 sent from the Compiler view: `forSimulator` (mojo/att.ts) ends every instruction that
|
||||
* came from a line of the Mojo program with `; mojo line N`, from godbolt's own line table. Map: x86-64 line (1-based)
|
||||
* to Mojo line. Empty for x86-64 written by hand, which no Mojo line produced.
|
||||
*/
|
||||
export function asmMojoLines(asm: string): Map<number, number> {
|
||||
const out = new Map<number, number>();
|
||||
String(asm ?? '').split('\n').forEach((text, i) => {
|
||||
const m = /;\s*mojo line (\d+)\s*$/.exec(text);
|
||||
if (m) out.set(i + 1, Number(m[1]));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The lines of the other pane that match `line` of pane `from`, through that table (sorted; empty when nothing matches). */
|
||||
export function relateAsmMojo(asm: string, from: 'asm' | 'mojo', line: number): number[] {
|
||||
const table = asmMojoLines(asm);
|
||||
if (from === 'asm') { const m = table.get(line); return m == null ? [] : [m]; }
|
||||
return [...table].filter(([, m]) => m === line).map(([a]) => a).sort((a, b) => a - b);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Browser preferences that are not part of a piece of work: they live in localStorage, never in `PlayState`, so
|
||||
* a share link or a file can never turn one on for someone else (restructure plan, section 2.6).
|
||||
*
|
||||
* The best-practices helper has one switch per area, off until the student turns it on. A browser that refuses
|
||||
* storage still keeps the choice for the tab.
|
||||
*/
|
||||
import type { AreaId } from './areas.js';
|
||||
|
||||
/** The areas the helper runs in. */
|
||||
export const PRACTICE_AREAS: readonly AreaId[] = ['bridge', 'dev'];
|
||||
|
||||
const key = (area: AreaId): string => `pplus.practices.${area}`;
|
||||
const memory = new Map<AreaId, boolean>();
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
export function practicesOn(area: AreaId | null): boolean {
|
||||
if (!area || !PRACTICE_AREAS.includes(area)) return false;
|
||||
try { const v = localStorage.getItem(key(area)); if (v !== null) return v === '1'; } catch { /* blocked: fall back to this tab's choice */ }
|
||||
return memory.get(area) ?? false;
|
||||
}
|
||||
|
||||
export function setPracticesOn(area: AreaId, on: boolean): void {
|
||||
if (!PRACTICE_AREAS.includes(area)) return;
|
||||
memory.set(area, on);
|
||||
try { if (on) localStorage.setItem(key(area), '1'); else localStorage.removeItem(key(area)); } catch { /* the tab keeps it */ }
|
||||
for (const fn of [...listeners]) fn();
|
||||
}
|
||||
|
||||
/** Be told when a switch changes (so open workspaces can show or hide the helper). Returns the way to stop. */
|
||||
export function onPracticesChange(fn: () => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; }
|
||||
|
||||
/** Forget every choice (the tests use this). */
|
||||
export function forgetPractices(): void {
|
||||
memory.clear();
|
||||
for (const a of PRACTICE_AREAS) { try { localStorage.removeItem(key(a)); } catch { /* ignore */ } }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Where the Mojo on screen came from (restructure plan, section 2.4). One pure function answers for every view,
|
||||
* so no screen has to work it out for itself: the Bridge's Mojo is always generated; anywhere else it is whatever
|
||||
* `mojoOrigin` records (absent: written by hand, or an exercise's own program).
|
||||
*/
|
||||
import type { PlayState } from './state.js';
|
||||
import type { AreaId } from './areas.js';
|
||||
|
||||
export type MojoProvenance = 'generated' | 'generated-edited' | null;
|
||||
|
||||
export function mojoProvenance(s: { area: AreaId | null; state: Pick<PlayState, 'mojoOrigin'> }, area: AreaId | null = s.area): MojoProvenance {
|
||||
if (area === 'bridge') return 'generated';
|
||||
return s.state.mojoOrigin ?? null;
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
/**
|
||||
* The language reference, as data. One module feeds three things: the
|
||||
* reference section on the home page, the hover explanations in every
|
||||
* editor, and the tests that check every example here still parses.
|
||||
*
|
||||
* Wherever an engine already holds the fact (keywords, built-ins,
|
||||
* precedence, sentence forms, instruction glosses, condition codes), this
|
||||
* module reads it from the engine rather than restating it. The tables
|
||||
* written here by hand (statement forms, what stops a run, speco syntax)
|
||||
* carry examples, and `tests/reference.test.mjs` parses every one.
|
||||
*/
|
||||
import { KEYWORDS, BUILTINS, PRECEDENCE, CONTEXTUAL } from '../engines/pseudo/lang.js';
|
||||
import { SENTENCE_FORMS, COMPARISONS, IN_PHRASES } from '../engines/pseudo/english.js';
|
||||
import { OPS, CONDITION_TEXT, REG64, SYSCALLS } from '../engines/asm86/interp.js';
|
||||
import { PRESETS } from '../engines/asm86/machine.js';
|
||||
import type { LangId } from './types.js';
|
||||
|
||||
export interface RefEntry { term: string; meaning: string; example?: string; note?: string }
|
||||
export interface RefSection { id: string; title: string; intro?: string; entries: RefEntry[]; columns?: [string, string, string?] }
|
||||
export interface RefLanguage { id: LangId; title: string; blurb: string; sections: RefSection[] }
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Pseudocode */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const KEYWORD_GROUPS: Array<[string, string[]]> = [
|
||||
['Declarations', ['DECLARE', 'CONSTANT', 'DEFINE', 'TYPE', 'ENDTYPE', 'OF']],
|
||||
['Types', ['INTEGER', 'FLOAT', 'CHAR', 'STRING', 'BOOL', 'BOOLEAN', 'ARRAY', 'LIST', 'HASHMAP', 'SET']],
|
||||
['Selection', ['IF', 'THEN', 'ELSEIF', 'ELSE', 'ENDIF', 'CASE', 'OTHERWISE', 'ENDCASE']],
|
||||
['Iteration', ['FOR', 'TO', 'STEP', 'NEXT', 'PARALLEL', 'WHILE', 'ENDWHILE', 'REPEAT', 'UNTIL', 'BREAK', 'CONTINUE']],
|
||||
['Subroutines', ['FUNCTION', 'ENDFUNCTION', 'PROCEDURE', 'ENDPROCEDURE', 'RETURNS', 'RETURN', 'CALL', 'BYREF', 'BYVAL']],
|
||||
['Input and output', ['INPUT', 'OUTPUT']],
|
||||
['Operators', ['AND', 'OR', 'NOT', 'DIV', 'MOD', 'IN']],
|
||||
['Values', ['TRUE', 'FALSE']],
|
||||
['Reasoning', ['REQUIRE', 'ENSURE', 'INVARIANT', 'DECREASES', 'ASSERT', 'FORALL', 'EXISTS']],
|
||||
];
|
||||
|
||||
/** What each keyword means, for hover. */
|
||||
export const KEYWORD_MEANING: Record<string, string> = {
|
||||
DECLARE: 'Creates a name and fixes its type, with or without a starting value: DECLARE Counter : INTEGER, or DECLARE Counter : INTEGER <- 0', CONSTANT: 'Names a value that never changes: CONSTANT BasesPerCodon = 3', DEFINE: 'Makes one fixed set of a named set type: DEFINE Purines (\'A\', \'G\') : BaseSet', TYPE: 'Defines a record (TYPE … ENDTYPE with one DECLARE per field) or names a set type (TYPE BaseSet = SET OF CHAR)', ENDTYPE: 'Closes a TYPE block', OF: 'Joins a collection to its element type: LIST OF INTEGER',
|
||||
INTEGER: 'A whole number', FLOAT: 'A number with a fractional part; / always produces one', CHAR: 'Exactly one character, in single quotes', STRING: 'Any number of characters, in double quotes; positions count from 0', BOOL: 'TRUE or FALSE', ARRAY: 'A fixed number of values of one type, declared by length: ARRAY[4] OF INTEGER, or ARRAY[R, C] for two dimensions', LIST: 'Any number of values of one type, in order; starts empty and grows with APPEND', HASHMAP: 'Values reached by key: HASHMAP OF STRING : CHAR', SET: 'Distinct values in no order; ask IN',
|
||||
IF: 'Runs its body when the condition is TRUE', THEN: 'Ends the condition of an IF', ELSEIF: 'One word: another condition under the same IF, tested only if the ones above failed', ELSE: 'The body that runs when no condition above was TRUE', ENDIF: 'Closes an IF', CASE: 'CASE OF X: picks the first arm whose value, list of values, or half-open range matches X', OTHERWISE: 'The arm of a CASE that runs when nothing else matched; must come last', ENDCASE: 'Closes a CASE',
|
||||
FOR: 'A counted loop: FOR I <- 0 TO N runs with I = 0, 1, …, N-1. The bound is not reached. FOR EACH X IN C visits every value', PARALLEL: 'PARALLEL FOR I <- 0 TO N: a counted loop whose passes are independent, as on a GPU where each runs on its own thread. The lab runs them and stops with a data race if one pass writes a location another pass touches', TO: 'The stop value of a FOR, which the counter never reaches (half-open), or the upper end of a CASE range', STEP: 'The increment of a FOR counter; negative counts down', NEXT: 'Closes a FOR, naming its counter: NEXT I', WHILE: 'Tests before each pass; the body may run zero times', ENDWHILE: 'Closes a WHILE', REPEAT: 'Runs the body, then tests; the body runs at least once', UNTIL: 'Closes a REPEAT with the condition that stops it', BREAK: 'Leaves the innermost loop at once', CONTINUE: 'Skips the rest of this pass and starts the next',
|
||||
FUNCTION: 'A subroutine that hands back one value: FUNCTION F(X : INTEGER) RETURNS INTEGER', ENDFUNCTION: 'Closes a FUNCTION', PROCEDURE: 'A subroutine that does something and returns nothing; called with CALL', ENDPROCEDURE: 'Closes a PROCEDURE', RETURNS: 'States the type of a FUNCTION\'s answer', RETURN: 'Hands back the answer and ends the subroutine at once', CALL: 'Runs a PROCEDURE on a line of its own: CALL REPORT("ATT", Found)', BYREF: 'Marks a parameter the procedure may change in the caller; everything else is a copy', BYVAL: 'States the default explicitly: the parameter is a copy',
|
||||
INPUT: 'Fills one variable from outside the program', OUTPUT: 'Shows any number of values, listed with commas and printed one after another with nothing between; text prints without its quotes',
|
||||
AND: 'TRUE when both sides are; the right side is skipped once the left is FALSE, so put the guard first', OR: 'TRUE when either side is (or both)', NOT: 'TRUE when its operand is FALSE; binds looser than a comparison, so NOT A == B means NOT (A == B)', DIV: 'Integer division, discarding the remainder: 7 DIV 2 is 3', MOD: 'The remainder after integer division: 7 MOD 2 is 1', IN: 'Membership: X IN S for a SET, a LIST, a STRING, or the keys of a HASHMAP; also joins a FOR EACH variable to its collection',
|
||||
TRUE: 'The BOOL value for yes', FALSE: 'The BOOL value for no',
|
||||
REQUIRE: 'What every caller promises about the arguments; sits directly under the FUNCTION or PROCEDURE line', ENSURE: 'What the subroutine promises about its answer, RESULT; sits under the FUNCTION line after any REQUIRE', INVARIANT: 'What is true at the top of every pass of a loop; the first line of the loop body', DECREASES: 'A whole number that shrinks every pass (or every recursive call) and never goes below 0: why the loop ends', ASSERT: 'What is true at this line; checked on every run', FORALL: 'FORALL K IN [0, N) : P(K) is TRUE when P holds at every position', EXISTS: 'EXISTS K IN [0, N) : P(K) is TRUE when P holds at some position',
|
||||
SUM: 'SUM K IN [0, N) : Q[K] adds the values over the range', EACH: 'FOR EACH X IN C visits every value of a collection', RESULT: 'Inside an ENSURE, the value the function returned', OLD: 'Inside an ENSURE, OLD(X) is a BYREF parameter\'s value when the call began', BOOLEAN: 'Another spelling of BOOL',
|
||||
};
|
||||
|
||||
const OPERATOR_MEANING: Record<string, string> = {
|
||||
'<-': 'Assignment: the value on the right travels into the name on the left', '==': 'Equal to; produces a BOOL', '!=': 'Not equal to', '<': 'Less than', '<=': 'Less than or equal', '>': 'Greater than', '>=': 'Greater than or equal',
|
||||
'+': 'Addition', '-': 'Subtraction, or negation', '*': 'Multiplication', '/': 'Division; always produces a FLOAT, even 4 / 2', '^': 'Power; binds right: 2 ^ 3 ^ 2 is 2 ^ 9', '&': 'Joins two pieces of text into a STRING',
|
||||
'=': 'Used only in CONSTANT X = … and TYPE X = SET OF …; everywhere else it is a mistake for <- or ==', ':': 'Separates a name from its type, a key type from a value type, or a CASE label from its body',
|
||||
'[': 'Indexing: T[I] is the character at position I, counting from 0; A[R, C] for two dimensions; [0, N) is a half-open range of positions; [1, 2] is a LIST literal', '{': 'A SET literal {\'A\', \'G\'}, a HASHMAP literal {"ATG": \'M\'}, or a set written by rule { K IN [0, N) : T[K] == B }', '.': 'Reaches a field of a record: R.Name', '//': 'A comment to the end of the line',
|
||||
};
|
||||
|
||||
const PSEUDO_STATEMENTS: RefEntry[] = [
|
||||
{ term: 'DECLARE <name> : <type>', meaning: 'Creates a name of that type with no value yet. Several names may share a line.', example: 'DECLARE Counter : INTEGER\nDECLARE N, M : INTEGER' },
|
||||
{ term: 'DECLARE <name> : <type> <- <expr>', meaning: 'Creates a name and gives it its starting value on the same line, as Mojo\'s var total: Int = 0 does. One name per line in this form; the two-line form (DECLARE, then an assignment) means the same.', example: 'DECLARE T : STRING <- "GATTACA"\nDECLARE N : INTEGER <- LENGTH(T)\nDECLARE Total : INTEGER <- 0\nOUTPUT N, " ", Total' },
|
||||
{ term: 'CONSTANT <name> = <value>', meaning: 'A value fixed for the whole program; literals and other constants only.', example: 'CONSTANT BasesPerCodon = 3' },
|
||||
{ term: '<name> <- <expr>', meaning: 'Assignment. The right side is worked out first, then stored.', example: 'DECLARE Counter : INTEGER\nCounter <- 0\nCounter <- Counter + 1' },
|
||||
{ term: 'OUTPUT <expr>, <expr>, ...', meaning: 'Shows values in order. A collection prints the way you would type it.', example: 'OUTPUT "Found ", 3, " matches"' },
|
||||
{ term: 'INPUT <name>', meaning: 'Fills a declared variable from outside the program.', example: 'DECLARE Threshold : INTEGER\nINPUT Threshold' },
|
||||
{ term: 'IF <cond> THEN ... ELSEIF <cond> THEN ... ELSE ... ENDIF', meaning: 'The first TRUE condition wins; ELSEIF and ELSE are optional; one ENDIF closes the lot.', example: 'DECLARE Q : FLOAT\nQ <- 25.0\nIF Q < 20 THEN\n OUTPUT "discard"\nELSEIF Q < 30 THEN\n OUTPUT "marginal"\nELSE\n OUTPUT "keep"\nENDIF' },
|
||||
{ term: 'CASE OF <expr> ... <value> : ... <lo> TO <hi> : ... OTHERWISE : ... ENDCASE', meaning: 'Picks the first arm whose value, comma-separated values, or half-open range matches. Ranges are [lo, hi).', example: "DECLARE Base : CHAR\nDECLARE Partner : CHAR\nBase <- 'A'\nCASE OF Base\n 'A' : Partner <- 'T'\n 'T' : Partner <- 'A'\n 'G', 'C' : OUTPUT \"strong\"\n OTHERWISE : Partner <- 'N'\nENDCASE" },
|
||||
{ term: 'FOR <i> <- <start> TO <stop> [STEP <k>] ... NEXT <i>', meaning: 'Counts from start while the counter is strictly less than stop (strictly greater, with a negative STEP). The counter needs no DECLARE and has no value after the loop.', example: 'DECLARE T : STRING\nT <- "GATTACA"\nFOR I <- 0 TO LENGTH(T)\n OUTPUT T[I]\nNEXT I\nFOR J <- 10 TO 0 STEP -2\n OUTPUT J\nNEXT J' },
|
||||
{ term: 'PARALLEL FOR <i> <- <start> TO <stop> ... NEXT <i>', meaning: 'A counted loop whose passes may run at the same time. Each pass may write only its own slots (indexed by the counter) and names it declares; writing a shared name, or reading a slot another pass writes, is a data race and stops the run naming both passes. This is the map step of GPU programming.', example: 'DECLARE Xs, Squares : LIST OF FLOAT\nXs <- [1.0, 2.0, 3.0]\nSquares <- FILL(LENGTH(Xs), 0.0)\nPARALLEL FOR I <- 0 TO LENGTH(Xs)\n Squares[I] <- Xs[I] * Xs[I]\nNEXT I\nOUTPUT SUM_OF(Squares)' },
|
||||
{ term: 'FOR EACH <x> IN <collection> ... NEXT <x>', meaning: 'Visits every character of a STRING, value of a LIST or ARRAY, member of a SET, or key of a HASHMAP.', example: 'DECLARE GC : INTEGER\nGC <- 0\nFOR EACH B IN "GATTACA"\n IF B == \'G\' OR B == \'C\' THEN\n GC <- GC + 1\n ENDIF\nNEXT B' },
|
||||
{ term: 'WHILE <cond> ... ENDWHILE', meaning: 'Tests before each pass; may run zero times.', example: 'DECLARE I : INTEGER\nDECLARE T : STRING\nT <- "GATNACA"\nI <- 0\nWHILE I < LENGTH(T) AND T[I] != \'N\'\n I <- I + 1\nENDWHILE' },
|
||||
{ term: 'REPEAT ... UNTIL <cond>', meaning: 'Runs the body, then tests; runs at least once; stops when the condition becomes TRUE.', example: 'DECLARE N : INTEGER\nN <- 0\nREPEAT\n N <- N + 1\nUNTIL N >= 3' },
|
||||
{ term: 'BREAK / CONTINUE', meaning: 'Leave the innermost loop at once / skip to the next pass.', example: 'FOR I <- 0 TO 10\n IF I == 2 THEN\n CONTINUE\n ENDIF\n IF I == 5 THEN\n BREAK\n ENDIF\n OUTPUT I\nNEXT I' },
|
||||
{ term: 'FUNCTION <name>(<p> : <type>, ...) RETURNS <type> ... RETURN <expr> ... ENDFUNCTION', meaning: 'A subroutine with one answer. Parameters are copies. A call stands where a value stands.', example: 'FUNCTION MAX_OF(A : INTEGER, B : INTEGER) RETURNS INTEGER\n IF A > B THEN\n RETURN A\n ENDIF\n RETURN B\nENDFUNCTION\nOUTPUT MAX_OF(3, 7)' },
|
||||
{ term: 'PROCEDURE <name>(BYREF <p> : <type>, ...) ... ENDPROCEDURE, and CALL <name>(...)', meaning: 'A subroutine with no answer, run for its effect. BYREF lets it change the caller\'s variable.', example: 'PROCEDURE SWAP(BYREF X : INTEGER, BYREF Y : INTEGER)\n DECLARE Temp : INTEGER\n Temp <- X\n X <- Y\n Y <- Temp\nENDPROCEDURE\nDECLARE A, B : INTEGER\nA <- 1\nB <- 2\nCALL SWAP(A, B)' },
|
||||
{ term: 'TYPE <name> ... DECLARE <field> : <type> ... ENDTYPE', meaning: 'A record: several named fields that travel together. Reach a field with a dot.', example: 'TYPE Read\n DECLARE Name : STRING\n DECLARE Bases : STRING\nENDTYPE\nDECLARE R : Read\nR.Name <- "read_1"\nR.Bases <- "GATTACA"\nOUTPUT R.Name, LENGTH(R.Bases)' },
|
||||
{ term: 'TYPE <name> = SET OF <type>, and DEFINE <set> (<v>, ...) : <name>', meaning: 'Names a kind of set, then makes one fixed set of that kind. A growing set is DECLARE S : SET OF <type> plus ADD.', example: "TYPE BaseSet = SET OF CHAR\nDEFINE Purines ('A', 'G') : BaseSet\nIF 'A' IN Purines THEN\n OUTPUT \"purine\"\nENDIF" },
|
||||
{ term: 'REQUIRE / ENSURE / INVARIANT / DECREASES / ASSERT <cond>', meaning: 'Claims the lab checks on every run and the prover tries to prove for every input. See the speco reference.', example: 'FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER\n ENSURE RESULT == LENGTH({ K IN [0, LENGTH(T)) : T[K] == B })\n DECLARE Total : INTEGER\n Total <- 0\n FOR I <- 0 TO LENGTH(T)\n INVARIANT Total == LENGTH({ K IN [0, I) : T[K] == B })\n IF T[I] == B THEN\n Total <- Total + 1\n ENDIF\n NEXT I\n RETURN Total\nENDFUNCTION' },
|
||||
];
|
||||
|
||||
const PSEUDO_LITERALS: RefEntry[] = [
|
||||
{ term: '42, -3', meaning: 'an INTEGER' },
|
||||
{ term: '0.5, 2.0, 1.5e-3', meaning: 'a FLOAT; a digit on each side of the point is required' },
|
||||
{ term: "'A'", meaning: 'a CHAR: exactly one character in single quotes' },
|
||||
{ term: '"GATTACA", ""', meaning: 'a STRING in double quotes; \\n, \\t, \\" and \\\\ are escapes' },
|
||||
{ term: 'TRUE, FALSE', meaning: 'a BOOL' },
|
||||
{ term: '[4, 17]', meaning: 'a LIST' },
|
||||
{ term: "{'A', 'G'}", meaning: 'a SET' },
|
||||
{ term: '{"ATG": \'M\', "TAA": \'*\'}', meaning: 'a HASHMAP' },
|
||||
{ term: '[0, N)', meaning: 'a half-open range of positions, inside FORALL, EXISTS, SUM, and sets written by rule' },
|
||||
{ term: '{ K IN [0, N) : T[K] == B }', meaning: 'a set written by rule: every K in the range for which the condition holds' },
|
||||
{ term: '← ≤ ≥ ≠', meaning: 'accepted spellings of <-, <=, >=, !=' },
|
||||
];
|
||||
|
||||
const PSEUDO_STOPS: RefEntry[] = [
|
||||
{ term: 'Position does not exist', meaning: 'an index outside [0, LENGTH), a SLICE outside [0, LENGTH], or a row or column outside an ARRAY' },
|
||||
{ term: 'No value yet', meaning: 'reading a name, a position, or a field before anything is stored in it, or a FOR counter after its loop' },
|
||||
{ term: 'Missing key', meaning: 'reading H[K] when K is not a key of H; test with IN first' },
|
||||
{ term: 'Division by zero', meaning: 'dividing by 0 with /, DIV, or MOD' },
|
||||
{ term: 'No answer', meaning: 'a whole number to a negative power, SQRT of a negative, LOG of a non-positive, MIN of an empty list, text TO_INTEGER cannot read' },
|
||||
{ term: 'Too large', meaning: 'a whole number beyond ±9,007,199,254,740,991' },
|
||||
{ term: 'Input', meaning: 'INPUT with nothing left, or input that does not convert' },
|
||||
{ term: 'A broken promise', meaning: 'a REQUIRE, ENSURE, INVARIANT, DECREASES, or ASSERT that is FALSE' },
|
||||
{ term: 'No end in sight', meaning: 'more steps than the lab allows (20,000 here); the lab names the loop and says whether its condition has stopped changing' },
|
||||
{ term: 'Too deep', meaning: 'recursion more than 400 calls deep' },
|
||||
{ term: 'A data race', meaning: 'in a PARALLEL FOR, one pass writes a location (a shared name, or a slot of a list) that another pass reads or writes; the message names the location and both passes' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Idioms: the handful of shapes the stress test (docs/pseudo-stress-test.md)
|
||||
* found worth writing down once, so nobody has to rediscover them. Every
|
||||
* example runs, and `tests/reference.test.mjs` checks the OUTPUT in `note`.
|
||||
*/
|
||||
export const PSEUDO_IDIOMS: RefEntry[] = [
|
||||
{
|
||||
term: 'Find the first, three ways',
|
||||
meaning: 'A search can stop with RETURN inside a FUNCTION, with BREAK and a flag in a loop, or with a WHILE whose condition names what it is waiting for. All three agree on the answer: the position, or LENGTH when there is none. For a plain character or piece of text, INDEX_OF does the same search and answers -1 when absent; the three shapes are for searches with a condition of your own.',
|
||||
example: 'FUNCTION FIRST_N(T : STRING) RETURNS INTEGER\n FOR I <- 0 TO LENGTH(T)\n IF T[I] == \'N\' THEN\n RETURN I\n ENDIF\n NEXT I\n RETURN LENGTH(T)\nENDFUNCTION\nDECLARE T : STRING\nT <- "GATNACA"\nDECLARE Found, J : INTEGER\nFound <- LENGTH(T)\nFOR I <- 0 TO LENGTH(T)\n IF T[I] == \'N\' THEN\n Found <- I\n BREAK\n ENDIF\nNEXT I\nJ <- 0\nWHILE J < LENGTH(T) AND T[J] != \'N\'\n J <- J + 1\nENDWHILE\nOUTPUT FIRST_N(T), " ", Found, " ", J, " ", INDEX_OF(T, \'N\')',
|
||||
note: '3 3 3 3',
|
||||
},
|
||||
{
|
||||
term: 'Return two values: use a record',
|
||||
meaning: 'A FUNCTION hands back one value. When the answer has two parts, name a TYPE for the pair and return that; the reader sees what each part means instead of guessing which is which.',
|
||||
example: 'TYPE Extremes\n DECLARE Low : INTEGER\n DECLARE High : INTEGER\nENDTYPE\nFUNCTION RANGE_OF(Xs : LIST OF INTEGER) RETURNS Extremes\n REQUIRE LENGTH(Xs) > 0\n DECLARE E : Extremes\n E.Low <- MIN(Xs)\n E.High <- MAX(Xs)\n RETURN E\nENDFUNCTION\nDECLARE R : Extremes\nR <- RANGE_OF([7, 2, 9, 4])\nOUTPUT R.Low, " to ", R.High',
|
||||
note: '2 to 9',
|
||||
},
|
||||
{
|
||||
term: 'Memoise with a PROCEDURE and two BYREF parameters',
|
||||
meaning: 'A FUNCTION is pure, so it cannot take a table BYREF. Memoised recursion is therefore a PROCEDURE: the table travels BYREF, and the answer comes back BYREF too. It is the heaviest idiom in the notation; it is also the one that makes "the table is shared" visible.',
|
||||
example: 'PROCEDURE FIB(N : INTEGER, BYREF Memo : HASHMAP OF INTEGER : INTEGER, BYREF Answer : INTEGER)\n IF N < 2 THEN\n Answer <- N\n RETURN\n ENDIF\n IF N IN Memo THEN\n Answer <- Memo[N]\n RETURN\n ENDIF\n DECLARE A, B : INTEGER\n CALL FIB(N - 1, Memo, A)\n CALL FIB(N - 2, Memo, B)\n Memo[N] <- A + B\n Answer <- A + B\nENDPROCEDURE\nDECLARE Table : HASHMAP OF INTEGER : INTEGER\nDECLARE F : INTEGER\nCALL FIB(40, Table, F)\nOUTPUT F',
|
||||
note: '102334155',
|
||||
},
|
||||
{
|
||||
term: 'Split text: SPLIT, and what it does by hand',
|
||||
meaning: 'SPLIT(S, " ") cuts a text at every space and keeps empty pieces, so two spaces give an empty word; drop those yourself when you want words. Writing the walk by hand once is still worth it: grow a word until a separator, APPEND it, start a new one, and append the last word after the loop; forgetting that last step is the classic mistake, and the trace shows it.',
|
||||
example: 'FUNCTION WORDS_OF(S : STRING) RETURNS LIST OF STRING\n DECLARE Out : LIST OF STRING\n DECLARE W : STRING\n W <- ""\n FOR EACH C IN S\n IF C == \' \' THEN\n IF LENGTH(W) > 0 THEN\n APPEND(Out, W)\n ENDIF\n W <- ""\n ELSE\n W <- W & C\n ENDIF\n NEXT C\n IF LENGTH(W) > 0 THEN\n APPEND(Out, W)\n ENDIF\n RETURN Out\nENDFUNCTION\nOUTPUT WORDS_OF("the cat sat"), " ", SPLIT("the cat sat", " "), " ", JOIN(WORDS_OF("the cat sat"), "_")',
|
||||
note: '["the", "cat", "sat"] ["the", "", "cat", "sat"] the_cat_sat',
|
||||
},
|
||||
{
|
||||
term: 'A stack from a LIST',
|
||||
meaning: 'Push with APPEND; the top is the last position; pop with REMOVE of that position. A LIST already is a stack, so there is no stack type.',
|
||||
example: 'DECLARE Stack : LIST OF CHAR\nAPPEND(Stack, \'(\')\nAPPEND(Stack, \'[\')\nDECLARE Top : CHAR\nTop <- Stack[LENGTH(Stack) - 1]\nREMOVE(Stack, LENGTH(Stack) - 1)\nOUTPUT Top, " ", LENGTH(Stack)',
|
||||
note: '[ 1',
|
||||
},
|
||||
{
|
||||
term: 'A queue from a LIST',
|
||||
meaning: 'Join at the end with APPEND; leave from the front with REMOVE(Q, 0). REMOVE at the front shifts every later value, so this costs LENGTH steps per leave; a lesson on cost measures exactly that.',
|
||||
example: 'DECLARE Q : LIST OF STRING\nAPPEND(Q, "read_1")\nAPPEND(Q, "read_2")\nAPPEND(Q, "read_3")\nDECLARE Next_Up : STRING\nNext_Up <- Q[0]\nREMOVE(Q, 0)\nOUTPUT Next_Up, " ", Q',
|
||||
note: 'read_1 ["read_2", "read_3"]',
|
||||
},
|
||||
{
|
||||
term: 'Count with a HASHMAP',
|
||||
meaning: 'Test IN before reading a key: a missing key stops the run. "If seen, add one; else start at one" is the shape every tally takes, and the checker recognises it.',
|
||||
example: 'DECLARE Tally : HASHMAP OF CHAR : INTEGER\nFOR EACH B IN "GATTACA"\n IF B IN Tally THEN\n Tally[B] <- Tally[B] + 1\n ELSE\n Tally[B] <- 1\n ENDIF\nNEXT B\nOUTPUT Tally',
|
||||
note: '{\'A\': 3, \'C\': 1, \'G\': 1, \'T\': 2}',
|
||||
},
|
||||
{
|
||||
term: 'Swap through BYREF',
|
||||
meaning: 'The one place BYREF is the natural tool: a procedure that changes two of the caller\'s variables and has no answer of its own.',
|
||||
example: 'PROCEDURE SWAP(BYREF X : INTEGER, BYREF Y : INTEGER)\n DECLARE Temp : INTEGER\n Temp <- X\n X <- Y\n Y <- Temp\nENDPROCEDURE\nDECLARE A, B : INTEGER\nA <- 1\nB <- 2\nCALL SWAP(A, B)\nOUTPUT A, " ", B',
|
||||
note: '2 1',
|
||||
},
|
||||
{
|
||||
term: 'ARRAY for fixed shapes, LIST for everything a subroutine takes',
|
||||
meaning: 'An ARRAY type always states its lengths, so a parameter of ARRAY type works for one size only. Anything a FUNCTION or PROCEDURE takes is a LIST; an ARRAY is for a table whose shape is part of the problem, such as a 3×3 grid.',
|
||||
example: 'FUNCTION TOTAL(Xs : LIST OF INTEGER) RETURNS INTEGER\n DECLARE S : INTEGER\n S <- 0\n FOR EACH X IN Xs\n S <- S + X\n NEXT X\n RETURN S\nENDFUNCTION\nDECLARE Grid : ARRAY[2, 2] OF INTEGER\nGrid[0, 0] <- 1\nGrid[0, 1] <- 2\nGrid[1, 0] <- 3\nGrid[1, 1] <- 4\nOUTPUT TOTAL([1, 2, 3, 4]), " ", ROWS(Grid) * COLUMNS(Grid)',
|
||||
note: '10 4',
|
||||
},
|
||||
];
|
||||
|
||||
/** Names a program cannot use: keywords, contextual keywords, and built-ins, in any capitalization. */
|
||||
export function reservedNames(): RefEntry[] {
|
||||
const kw = [...(KEYWORDS as Set<string>)].sort().map((w) => ({ term: w, meaning: 'keyword', note: KEYWORD_MEANING[w] ? KEYWORD_MEANING[w].split(/[:;.]/)[0] : '' }));
|
||||
const ctx = Object.keys(CONTEXTUAL as Record<string, string>).sort().map((w) => ({ term: w, meaning: 'contextual keyword', note: KEYWORD_MEANING[w] ? KEYWORD_MEANING[w].split(/[:;.]/)[0] : '' }));
|
||||
const bi = Object.keys(BUILTINS as Record<string, any>).sort().map((w) => ({ term: w, meaning: 'built-in function', note: ((BUILTINS as any)[w].doc || '').split(/[:;.]/)[0] }));
|
||||
return [...kw, ...ctx, ...bi];
|
||||
}
|
||||
|
||||
function builtinEntries(): RefEntry[] {
|
||||
return Object.entries(BUILTINS as Record<string, any>).map(([name, b]) => ({ term: b.sig || name, meaning: b.doc || '', note: b.group || '' }));
|
||||
}
|
||||
|
||||
export const PSEUDO_REF: RefLanguage = {
|
||||
id: 'pseudo', title: 'pseudo', blurb: 'The course notation: uppercase keywords, <- for assignment, half-open bounds everywhere, typed names, and claims the prover can check.',
|
||||
sections: [
|
||||
{ id: 'pseudo-keywords', title: 'Keywords', intro: 'Uppercase, always. Names are case-insensitive and may not reuse a keyword or a built-in.', entries: KEYWORD_GROUPS.flatMap(([group, words]) => words.filter((w) => (KEYWORDS as Set<string>).has(w)).map((w) => ({ term: w, meaning: KEYWORD_MEANING[w] || '', note: group }))).concat(Object.entries(CONTEXTUAL as Record<string, string>).map(([w, where]) => ({ term: w, meaning: `${KEYWORD_MEANING[w] || ''} (a keyword only ${where})`, note: 'Contextual' }))), columns: ['Keyword', 'Meaning', 'Group'] },
|
||||
{ id: 'pseudo-literals', title: 'Literals', entries: PSEUDO_LITERALS, columns: ['Written', 'Is'] },
|
||||
{ id: 'pseudo-operators', title: 'Operators, loosest first', intro: 'Parenthesize wherever a reader might have to look this table up.', entries: (PRECEDENCE as any[]).map((p) => ({ term: p.ops.join(' '), meaning: `${p.assoc === 'chain' ? 'chains' : p.assoc}${p.note ? ': ' + p.note : ''}`, note: `level ${p.level}` })), columns: ['Operators', 'Associativity and notes', 'Level'] },
|
||||
{ id: 'pseudo-statements', title: 'Statements', intro: 'Every form, with a runnable example.', entries: PSEUDO_STATEMENTS, columns: ['Form', 'Meaning', 'Example'] },
|
||||
{ id: 'pseudo-builtins', title: 'Built-in functions', entries: builtinEntries(), columns: ['Signature', 'Returns', 'Group'] },
|
||||
{ id: 'pseudo-idioms', title: 'Idioms', intro: 'Shapes worth learning once. Each example runs; the last column is what it prints.', entries: PSEUDO_IDIOMS, columns: ['Idiom', 'Why it is written this way', 'Example and output'] },
|
||||
{ id: 'pseudo-stops', title: 'What stops a run', entries: PSEUDO_STOPS, columns: ['Stop', 'When'] },
|
||||
{ id: 'pseudo-reserved', title: 'Names you cannot use', intro: 'Names ignore case, so Next, step, and Keys are refused just as NEXT, STEP, and KEYS would be. Pick a longer word: Neighbour, Generation, KeyList.', entries: reservedNames(), columns: ['Word', 'Reserved as', 'Means'] },
|
||||
],
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* lingo */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const LINGO_QUESTIONS: RefEntry[] = [
|
||||
{ term: 'range-ends', meaning: '"from 0 to the length of T" does not say whether the end is included. Offers "up to but not including" and "up to and including".', example: 'To count in T:\n Start with Count at 0.\n For each i from 0 to the length of T:\n Add 1 to Count.\n The answer is Count.' },
|
||||
{ term: 'between', meaning: '"between 20 and 30" leaves both ends undecided. Offers the three readings.', example: 'To test Q:\n If Q is between 20 and 30, the answer is 1.\n The answer is 0.' },
|
||||
{ term: 'answer-in-loop', meaning: '"the answer is i" inside a loop could stop now or keep looking. Offers "Stop and answer i" and "Set Best to i".', example: 'To find it in T:\n For each position i of T:\n If the letter of T at i is \'N\', the answer is i.\n The answer is the length of T.' },
|
||||
{ term: 'is-step', meaning: '"Count is 0" could set Count or claim it. As a step, say "Set Count to 0" or "Check that Count is 0".', example: 'To do it with T:\n Count is 0.\n The answer is Count.' },
|
||||
{ term: 'and-or', meaning: '"A or B and C" does not say which binds. Parentheses do.', example: "To test b and i:\n If b is 'A' or b is 'T' and i is 0, the answer is 1.\n The answer is 0." },
|
||||
{ term: 'not-or', meaning: '"is not \'G\' or \'C\'" has two readings; say "is neither \'G\' nor \'C\'" or "is not one of".', example: "To test b:\n If b is not 'G' or 'C', the answer is 1.\n The answer is 0." },
|
||||
{ term: 'stop', meaning: '"Stop" inside a loop could end the loop or the routine.', example: 'To scan T:\n Start with Count at 0.\n For each letter b of T:\n If b is \'N\', stop.\n Add 1 to Count.\n The answer is Count.' },
|
||||
{ term: 'pronoun', meaning: '"it", "they", "them" could stand for several names. Name the thing you mean.', example: "To scan T:\n Start with Count at 0.\n For each letter b of T:\n If it is 'G', add 1 to Count.\n The answer is Count." },
|
||||
{ term: 'used-before-set', meaning: 'A name used before any step gives it a value: the set-up step is missing.', example: 'To scan T:\n For each letter b of T:\n Add 1 to Count.\n The answer is Count.' },
|
||||
{ term: 'text-place', meaning: '"Add b to R" with R a text does not say where b goes; say "to the end of" or "to the front of".', example: 'To reverse T:\n Start with an empty text called R.\n For each letter b of T:\n Add b to R.\n The answer is R.' },
|
||||
];
|
||||
|
||||
export const LINGO_REF: RefLanguage = {
|
||||
id: 'lingo', title: 'lingo', blurb: 'Plain-English steps with exactly one meaning each. The reader knows a fixed set of sentence shapes; anything else is a phrase you define, or a question it asks you.',
|
||||
sections: [
|
||||
...(SENTENCE_FORMS as any[]).map((g, i) => ({ id: `lingo-forms-${i}`, title: g.group as string, entries: (g.forms as string[][]).map(([form, example]) => ({ term: form, meaning: '', example: example || undefined })), columns: ['Sentence', '', 'Example'] as [string, string, string] })),
|
||||
{ id: 'lingo-comparisons', title: 'Comparison phrasings', intro: 'Every phrase in a column means the same operator.', entries: Object.entries((COMPARISONS as Array<[string, string]>).reduce((acc, [phrase, op]) => { (acc[op] ||= []).push(phrase); return acc; }, {} as Record<string, string[]>)).map(([op, phrases]) => ({ term: op, meaning: phrases.join(' · ') })).concat((IN_PHRASES as Array<[string, string]>).map(([p, k]) => ({ term: k === 'in' ? 'IN' : 'NOT IN', meaning: p.replace(/\|/g, ' / ') }))), columns: ['Means', 'Phrasings'] },
|
||||
{ id: 'lingo-questions', title: 'Questions the reader asks', intro: 'Each is deterministic: the same sentence always raises the same question, with the readings as one-click rewrites.', entries: LINGO_QUESTIONS, columns: ['Id', 'When, and what it offers', 'A sentence that raises it'] },
|
||||
],
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* speco */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** The symbol table that lowers math to the notation and renders it back. speco.ts imports this. */
|
||||
export const SPECO_SYMBOLS: Array<{ math: string; ascii: string; meaning: string }> = [
|
||||
{ math: '∀', ascii: 'FORALL', meaning: 'for every position in a range: ∀ k ∈ [0, n) : P(k)' },
|
||||
{ math: '∃', ascii: 'EXISTS', meaning: 'for some position in a range' },
|
||||
{ math: 'Σ', ascii: 'SUM', meaning: 'the sum over a range: Σ k ∈ [0, n) : Q[k]' },
|
||||
{ math: '∈', ascii: 'IN', meaning: 'membership, or the range a bound variable runs over' },
|
||||
{ math: '∧', ascii: 'AND', meaning: 'both' },
|
||||
{ math: '∨', ascii: 'OR', meaning: 'either' },
|
||||
{ math: '¬', ascii: 'NOT', meaning: 'not' },
|
||||
{ math: '≤', ascii: '<=', meaning: 'at most' },
|
||||
{ math: '≥', ascii: '>=', meaning: 'at least' },
|
||||
{ math: '≠', ascii: '!=', meaning: 'different' },
|
||||
{ math: '=', ascii: '==', meaning: 'equal (a claim, never an assignment)' },
|
||||
{ math: '|X|', ascii: 'LENGTH(X)', meaning: 'the size of a text, list, set, or set written by rule' },
|
||||
{ math: 'result', ascii: 'RESULT', meaning: 'the value the function returns' },
|
||||
{ math: 'X₀', ascii: 'OLD(X)', meaning: 'a BYREF parameter\'s value when the call began' },
|
||||
];
|
||||
|
||||
const SPECO_FORMS: RefEntry[] = [
|
||||
{ term: 'SPEC <name>(<params>)', meaning: 'Opens the claims about one FUNCTION or PROCEDURE in the pseudocode pane. The parameter names are documentation; the pseudocode header is authoritative.', example: 'SPEC COUNT_BASE(B, T)\n ENSURE result = |{ K ∈ [0, |T|) : T[K] = B }|' },
|
||||
{ term: 'REQUIRE <claim>', meaning: 'What every caller promises about the arguments.', example: 'SPEC GC_FRACTION(T)\n REQUIRE |T| ≥ 1' },
|
||||
{ term: 'ENSURE <claim>', meaning: 'What the routine promises about result (and about BYREF parameters, with X₀ for the starting value).', example: 'SPEC MAX_OF(A, B)\n ENSURE result ≥ A ∧ result ≥ B' },
|
||||
{ term: 'LOOP FOR <i> / LOOP FOR EACH <x> / LOOP WHILE / LOOP REPEAT / LOOP <n>', meaning: 'Names the loop the lines under it describe: by its counter, by its kind, or by its position among the routine\'s loops.', example: 'SPEC COUNT_BASE(B, T)\n LOOP FOR I\n INVARIANT Total = |{ K ∈ [0, I) : T[K] = B }|' },
|
||||
{ term: 'INVARIANT <claim>', meaning: 'True at the top of every pass. Checked before the first pass, after every pass, and once more when the loop ends normally.', example: 'SPEC CONTAINS_SORTED(L, X)\n LOOP WHILE\n INVARIANT 0 ≤ Lo ∧ Lo ≤ Hi ∧ Hi ≤ |L|' },
|
||||
{ term: 'DECREASES <whole number>', meaning: 'A measure that is at least 0 whenever the loop continues and shrinks every pass: why it ends. Under SPEC directly, it measures a recursive routine.', example: 'SPEC CONTAINS_SORTED(L, X)\n LOOP WHILE\n DECREASES Hi - Lo' },
|
||||
{ term: '{ k ∈ [lo, hi) : <condition> }', meaning: 'A set written by rule; |…| around it counts its members.', example: 'SPEC COUNT_GC(T)\n ENSURE result = |{ k ∈ [0, |T|) : T[k] = \'G\' ∨ T[k] = \'C\' }|' },
|
||||
];
|
||||
|
||||
export const SPECO_REF: RefLanguage = {
|
||||
id: 'speco', title: 'speco', blurb: 'Specifications as a document of their own, in mathematical notation. Programming+ weaves them into the pseudocode and the prover checks every claim for every input it can reason about.',
|
||||
sections: [
|
||||
{ id: 'speco-symbols', title: 'Symbols', intro: 'Type either column; the pane accepts the math and the notation\'s ASCII spelling alike.', entries: SPECO_SYMBOLS.map((s) => ({ term: s.math, meaning: s.meaning, note: s.ascii })), columns: ['Math', 'Meaning', 'Notation'] },
|
||||
{ id: 'speco-forms', title: 'Lines', entries: SPECO_FORMS, columns: ['Form', 'Meaning', 'Example'] },
|
||||
{
|
||||
id: 'speco-verdicts', title: 'What the prover reports', entries: [
|
||||
{ term: 'proved', meaning: 'on every path the checker examined, the claim follows from what is known; no input can break it' },
|
||||
{ term: 'broken by a run', meaning: 'the checker could not prove it, and a generated input violates it; Programming+ shows the smallest it found' },
|
||||
{ term: 'open', meaning: 'not proved and not broken by any input tried: usually a loop needs an invariant, or the claim needs reasoning the checker lacks (products of unknowns, facts about whole sets, exact FLOAT values)' },
|
||||
], columns: ['Verdict', 'Meaning']
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* x86-64 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const REG_MEANING: Record<string, string> = {
|
||||
rax: 'accumulator; the answer of a procedure and the system-call number', rbx: 'callee-saved general register', rcx: '4th argument; loop counter by convention', rdx: '3rd argument; high half of a 128-bit product or dividend', rsi: '2nd argument; source pointer by convention', rdi: '1st argument; destination pointer by convention', rbp: 'frame pointer (callee-saved)', rsp: 'stack pointer: the address of the top of the stack',
|
||||
r8: '5th argument', r9: '6th argument', r10: 'scratch', r11: 'scratch', r12: 'callee-saved', r13: 'callee-saved', r14: 'callee-saved', r15: 'callee-saved',
|
||||
};
|
||||
|
||||
const SETUP_FORMS: RefEntry[] = [
|
||||
{ term: 'rdi = 0x1000', meaning: 'any register, at any width: rdi, edi, di, dil' },
|
||||
{ term: "dl = 'A'", meaning: 'a character is its ASCII code' },
|
||||
{ term: 'memory 0x1000 "GATTACA"', meaning: 'text, one byte per letter; \\n and \\t work' },
|
||||
{ term: 'memory 0x2000 bytes 1 2 3 255', meaning: 'individual bytes' },
|
||||
{ term: 'memory 0x3000 qwords 3 11 14', meaning: '8-byte values, little-endian' },
|
||||
{ term: 'memory 0x4000 zero 64', meaning: 'a run of zeros, for output' },
|
||||
{ term: 'stdin "what read returns"', meaning: 'input for the read system call' },
|
||||
{ term: 'flags CF ZF', meaning: 'flags that start set' },
|
||||
];
|
||||
|
||||
function regEntries(): RefEntry[] {
|
||||
const widths = (r: string) => {
|
||||
if (/^r\d+$/.test(r)) return `${r}, ${r}d, ${r}w, ${r}b`;
|
||||
const m: Record<string, string> = { rax: 'rax, eax, ax, al / ah', rbx: 'rbx, ebx, bx, bl / bh', rcx: 'rcx, ecx, cx, cl / ch', rdx: 'rdx, edx, dx, dl / dh', rsi: 'rsi, esi, si, sil', rdi: 'rdi, edi, di, dil', rbp: 'rbp, ebp, bp, bpl', rsp: 'rsp, esp, sp, spl' };
|
||||
return m[r] || r;
|
||||
};
|
||||
return (REG64 as string[]).map((r) => ({ term: r, meaning: REG_MEANING[r] || '', note: widths(r) }));
|
||||
}
|
||||
|
||||
export const ASM_REF: RefLanguage = {
|
||||
id: 'asm', title: 'x86-64', blurb: 'Intel syntax, destination first, the course\'s instruction subset. Every program also gets a 512-byte stack; an address outside every region is a page fault.',
|
||||
sections: [
|
||||
{ id: 'asm-registers', title: 'Registers', intro: 'A 32-bit write zeroes the upper half; 8- and 16-bit writes leave the rest alone.', entries: regEntries(), columns: ['64-bit name', 'Role (System V convention)', 'Narrower names'] },
|
||||
{ id: 'asm-instructions', title: 'Instructions', entries: Object.entries(OPS as Record<string, any>).map(([op, d]) => ({ term: op, meaning: d.gloss || '', note: d.arity != null ? `${d.arity} operand${d.arity === 1 ? '' : 's'}` : '' })), columns: ['Mnemonic', 'What it does', 'Operands'] },
|
||||
{ id: 'asm-conditions', title: 'Condition codes', intro: 'Append to j, set, or cmov: je, setg, cmovae.', entries: Object.entries(CONDITION_TEXT as Record<string, string>).map(([cc, text]) => ({ term: cc, meaning: text })), columns: ['Code', 'Meaning'] },
|
||||
{
|
||||
id: 'asm-flags', title: 'Flags', entries: [
|
||||
{ term: 'ZF', meaning: 'the result was zero' }, { term: 'SF', meaning: 'the result\'s top bit is set (negative when read as signed)' }, { term: 'CF', meaning: 'an unsigned carry out, or borrow in' }, { term: 'OF', meaning: 'signed overflow: the sign of the result is wrong' }, { term: 'PF', meaning: 'the low byte of the result has an even number of one bits; after ucomisd, set when either side was NaN' },
|
||||
], columns: ['Flag', 'Set when']
|
||||
},
|
||||
{ id: 'asm-syscalls', title: 'System calls', intro: 'Number in rax, arguments in rdi, rsi, rdx; the answer returns in rax; rcx and r11 are clobbered.', entries: Object.entries(SYSCALLS as Record<string, any>).map(([n, s]) => ({ term: `${n}`, meaning: s.name ? `${s.name}${s.gloss ? ': ' + s.gloss : ''}` : String(s) })), columns: ['rax', 'Call'] },
|
||||
{ id: 'asm-setup', title: 'The setup box', entries: SETUP_FORMS, columns: ['Line', 'Meaning'] },
|
||||
{ id: 'asm-machines', title: 'Machine presets', entries: Object.values(PRESETS as Record<string, any>).map((m) => ({ term: m.name, meaning: m.description || '', note: m.caches?.l1d ? `L1d ${m.caches.l1d.size} B, ${m.caches.l1d.line}-byte lines, ${m.caches.l1d.ways}-way, ${m.caches.l1d.latency} cycles` : '' })), columns: ['Preset', 'Description', 'L1d'] },
|
||||
],
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* matho (equations, written in LaTeX) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** What the matho pane reads, with an example of each; every example is run through the translator by the tests. */
|
||||
export const MATHO_FORMS: RefEntry[] = [
|
||||
{ term: 'f(x) = …', meaning: 'An equation with a function on the left defines FUNCTION F(X : FLOAT) RETURNS FLOAT. Names used on the right but not named on the left become extra parameters, with a note.', example: 'f(x) = a x^2 + b' },
|
||||
{ term: 'name = …', meaning: 'A plain name on the left names the function; its parameters are the free names on the right, in order of appearance. \\bar{x} → X_BAR, E_k → E_K, \\sigma^2 → SIGMA_SQUARED.', example: '\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i' },
|
||||
{ term: 'x_i', meaning: 'A subscript that is an index (bound by a sum, or free on the left side) makes the name a LIST OF FLOAT and the subscript a position. Any other subscript is part of the name: v_0 is V0, x_{max} is XMax.', example: 'h(t) = v_0 t - \\frac{1}{2} g t^2' },
|
||||
{ term: '\\sum_{i=a}^{b} …', meaning: 'A FOR loop with an accumulator, Total. The upper bound is inclusive in mathematics and exclusive in pseudo, so n-1 becomes TO N. From i = 1, a subscript i becomes the position I - 1, with a note.', example: 's = \\sum_{i=1}^{n} x_i^2' },
|
||||
{ term: '\\sum_i … \\sum_{x \\in S} …', meaning: 'With no bounds, the loop runs over every position of the list the index walks. Over a set, it is FOR EACH.', example: 'm = \\sum_{x \\in S} x' },
|
||||
{ term: '\\prod, n!', meaning: 'A product loop with an accumulator starting at 1.0; n! is the same loop from 2 to n.', example: 'c = \\frac{n!}{k! (n-k)!}' },
|
||||
{ term: '\\frac{a}{b}, \\sqrt{x}, x^k, e^x', meaning: 'Division, SQRT, ^ (x^{1/2} is SQRT too), and EXP. A plain e is a name; e^{…} is the exponential.', example: 'f(x) = \\frac{1}{\\sqrt{2\\pi\\sigma^2}} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}' },
|
||||
{ term: '|x|, \\lfloor x \\rfloor, \\lceil x \\rceil, \\bmod', meaning: 'ABS, FLOOR, CEIL and MOD. FLOOR, CEIL and MOD make their operands INTEGER.', example: 'r = \\lfloor n / 2 \\rfloor + a \\bmod b' },
|
||||
{ term: '\\sin \\cos \\tan \\exp \\ln \\log \\max \\min', meaning: 'The built-ins of the same name. \\log is LOG10; \\log_2 is LOG2; \\log_b x is LOG(x) / LOG(b). \\sin^2 x is SIN(X) ^ 2.', example: 'y = \\sin^2 \\theta + \\log_{10} n' },
|
||||
{ term: '\\binom{n}{k}', meaning: 'CHOOSE(N, K); both become INTEGER.', example: 'P(k) = \\binom{n}{k} p^k (1-p)^{n-k}' },
|
||||
{ term: '\\vec{a} \\cdot \\vec{b}, \\|\\vec{a}\\|', meaning: 'A \\vec or \\mathbf name is a LIST OF FLOAT; \\cdot between two of them is DOT and the double bar is NORM_OF.', example: '\\cos\\theta = \\frac{\\vec{a} \\cdot \\vec{b}}{\\|\\vec{a}\\| \\|\\vec{b}\\|}' },
|
||||
{ term: 'A_{ij}', meaning: 'Two index letters in one subscript: a LIST OF LIST OF FLOAT, indexed A[I][J].', example: 'y_i = \\sum_{j=0}^{n-1} A_{ij} x_j' },
|
||||
{ term: '\\begin{cases} … \\end{cases}', meaning: 'IF / ELSEIF / ELSE. Conditions use < \\le > \\ge = \\ne, chains such as 0 \\le x < 1, and \\text{and} / \\text{or}. The last case must be the one with no condition.', example: 'f(x) = \\begin{cases} 0 & \\text{if } x < 0 \\\\ x & \\text{otherwise} \\end{cases}' },
|
||||
{ term: 'an earlier equation\'s name', meaning: 'A name defined by an equation higher up is a call to that function, with its parameters joining this one\'s. Inside a loop, a call whose arguments do not change is computed once, before the loop, as a local.', example: 'g(x) = x^2 + 1\nh(x) = 2 g(x) + c' },
|
||||
{ term: 'Greek letters, \\text{…}, \\bar \\hat \\tilde', meaning: 'Names: \\sigma is Sigma, \\text{pH} is PH, \\bar{x} is XBar. Two symbols that would be one pseudo name (p and P) are told apart with a suffix, and a note says so.', example: '\\text{pH} = -\\log_{10} [H]' },
|
||||
];
|
||||
|
||||
export const MATHO_REFUSALS: RefEntry[] = [
|
||||
{ term: '\\int', meaning: 'An integral has no finite procedure behind it. Write the sum it approximates: \\sum_{i=0}^{n-1} f(a + i h) h with a step h, which becomes a loop.' },
|
||||
{ term: '\\infty', meaning: 'A program cannot run to infinity. Give the sum or product an upper bound, such as n, and make n a parameter.' },
|
||||
{ term: '\\lim, \\partial, \\nabla, f\'', meaning: 'Limits and derivatives are not procedures. Write the difference quotient (f(x + h) - f(x)) / h for a step h, or pick the value of n you mean.' },
|
||||
{ term: '\\forall, \\exists', meaning: 'A statement about all or some values is a specification, not a procedure: it belongs in the speco pane as an ENSURE, or becomes the loop that searches.' },
|
||||
{ term: 'a = b = c, x < 0 on its own, \\pm, \\approx, \\propto, \\sim', meaning: 'Statements and relations rather than definitions: keep the two sides you want computed, split ± into two equations, name the constant a proportionality leaves out, write RANDN() or RAND(x) for a draw.' },
|
||||
];
|
||||
|
||||
export const MATHO_REF: RefLanguage = {
|
||||
id: 'matho', title: 'matho', blurb: 'Equations as a source language, written in LaTeX. Each equation becomes a FUNCTION in pseudo; sums become loops, subscripts become positions, cases become IF. Every decision the translation makes (which letters are whole numbers, which are lists, where a 1-based sum meets a 0-based list) is a note on the equation\'s line.',
|
||||
sections: [
|
||||
{ id: 'matho-forms', title: 'What it reads', entries: MATHO_FORMS, columns: ['Written', 'Becomes', 'Example'] },
|
||||
{ id: 'matho-what-a-program-can-be', title: 'What it refuses, and what to write instead', intro: 'Some mathematics has no finite procedure behind it. The reader says so, and says what the procedure would be.', entries: MATHO_REFUSALS, columns: ['Written', 'Why, and what to write'] },
|
||||
],
|
||||
};
|
||||
|
||||
export const REFERENCE: RefLanguage[] = [LINGO_REF, MATHO_REF, PSEUDO_REF, SPECO_REF, ASM_REF];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Hover explanations */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface Explanation { title: string; body: string; where?: string }
|
||||
|
||||
const LINGO_WORDS: Record<string, string> = {
|
||||
'up to but not including': 'The range stops just before this value: the last position of T is one less than its length.', 'up to and including': 'The range reaches this value; the end is the last one visited.', 'down to but not including': 'Counts down and stops just before this value.', 'down to and including': 'Counts down through this value.', 'for each position': 'Visits every position 0, 1, …, length-1 of a text or list.', 'for each letter': 'Visits every letter of a text, without its position.', 'the letter of': '"the letter of T at i": the character at position i, counting from 0.', 'the length of': 'How many letters or items.', 'start with': 'Gives a name its first value.', 'the answer is': 'Ends the routine with that value.', 'stop and answer': 'Ends the routine at once with that value, even inside a loop.', 'stop the loop': 'Leaves the loop (BREAK).', 'skip to the next': 'Starts the next pass (CONTINUE).', 'an empty list called': 'Makes a new empty list with that name.', 'an empty tally called': 'Makes a new empty tally (a HASHMAP from keys to counts).', 'the number of positions': 'Counts the positions where a condition holds: a set written by rule, measured.', 'is one of': 'Membership in a short list of values.', 'is neither': 'Not either of two values.', 'for every': 'A FORALL over a range.', 'to the end of': 'Appends to a text or list.', 'to the front of': 'Prepends to a text.', 'repeat while': 'Tests before each pass (WHILE).',
|
||||
to: 'Opens a routine: "To <do something> with <inputs>:". The names used in the steps are its inputs.', start: '"Start with Count at 0." gives a name its first value; "Start with an empty list called Starts."', set: '"Set Best to i." changes a value.', add: '"Add 1 to Count." increases a number; "Add i to Starts." appends to a list; "Add b to the end of R." extends a text.', subtract: '"Subtract 1 from Left."', count: '"Count the word in Counts." tallies a key.', for: '"For each position i of T:", "For each letter b of T:", "For each i from A up to but not including B:"', each: 'Part of "For each …".', repeat: '"Repeat while <condition>:" tests before each pass.', while: 'Part of "Repeat while …".', if: '"If <condition>, <step>." or "If <condition>:" with steps under it.', otherwise: 'The steps that run when the If above did not.', stop: '"Stop the loop." leaves the loop; "Stop and answer i." ends the routine.', skip: '"Skip to the next position."', the: '"The answer is <value>." reports; "The <phrase> is <value>." defines a phrase.', answer: '"The answer is <value>." ends the routine with that value.', when: '"<phrase> when <condition>." defines a yes-or-no phrase.', letter: '"the letter of T at i": the character at a position, counting from 0.', length: '"the length of T": how many letters.', position: '"For each position i of T" visits 0, 1, …, length-1.', up: '"up to but not including B" stops just before B; "up to and including B" reaches it.', including: 'Decides whether the end of a range counts.', including_: '', empty: '"T is empty" tests for length 0.', neither: '"is neither \'G\' nor \'C\'": not one of them.', one: '"is one of \'G\', \'C\'" is membership.', every: '"for every j from A up to but not including B, <condition>" is a FORALL.', larger: '"the larger of A and B".', smaller: '"the smaller of A and B".', number: '"the number of positions k of T where <condition>" counts.', show: '"Show <value>." prints it.', check: '"Check that <condition>." is an ASSERT.',
|
||||
};
|
||||
|
||||
export function explain(lang: LangId, token: string, lineText = ''): Explanation | null {
|
||||
const t = token.trim();
|
||||
if (!t) return null;
|
||||
switch (lang) {
|
||||
case 'pseudo': {
|
||||
const up = t.toUpperCase();
|
||||
if (KEYWORD_MEANING[up] && ((KEYWORDS as Set<string>).has(up) || up in CONTEXTUAL || up === 'SUM' || up === 'RESULT' || up === 'OLD' || up === 'BOOLEAN')) return { title: up, body: KEYWORD_MEANING[up], where: 'keyword' };
|
||||
const b = (BUILTINS as Record<string, any>)[up];
|
||||
if (b) return { title: b.sig || up, body: b.doc || '', where: `built-in · ${b.group || ''}` };
|
||||
if (OPERATOR_MEANING[t]) return { title: t, body: OPERATOR_MEANING[t], where: 'operator' };
|
||||
if (/^'.'$/.test(t)) return { title: t, body: 'A CHAR: one character. Compare it against T[I], never against a "string".', where: 'literal' };
|
||||
if (/^".*"$/.test(t)) return { title: 'STRING', body: 'Any number of characters. LENGTH counts characters; positions start at 0.', where: 'literal' };
|
||||
if (/^\d+\.\d+/.test(t)) return { title: t, body: 'A FLOAT literal.', where: 'literal' };
|
||||
if (/^\d+$/.test(t)) return { title: t, body: 'An INTEGER literal.', where: 'literal' };
|
||||
if (/^\/\//.test(t)) return { title: 'comment', body: 'Runs to the end of the line. Say why, not what.' };
|
||||
return null;
|
||||
}
|
||||
case 'lingo': {
|
||||
const lc = t.toLowerCase();
|
||||
const cmp = (COMPARISONS as Array<[string, string]>).find(([p]) => p === lc);
|
||||
if (cmp) return { title: `"${lc}"`, body: `Means ${cmp[1]}.`, where: 'comparison' };
|
||||
if (LINGO_WORDS[lc]) return { title: lc, body: LINGO_WORDS[lc] };
|
||||
if (/^'.'$/.test(t)) return { title: t, body: 'A letter.' };
|
||||
if (/^".*"$/.test(t)) return { title: 'a text', body: 'A text in double quotes.' };
|
||||
if (/^\d+$/.test(t)) return { title: t, body: 'A whole number.' };
|
||||
if (/^[A-Z][A-Za-z0-9]*$/.test(t) || /^[a-z]$/.test(t)) return { title: t, body: 'A name: an input of the routine, or something a step gave a value to.', where: 'name' };
|
||||
return null;
|
||||
}
|
||||
case 'matho': {
|
||||
if (!t.startsWith('\\')) {
|
||||
if (/^\d/.test(t)) return { title: t, body: 'A number. Whole numbers stay whole; a decimal point makes a FLOAT.', where: 'literal' };
|
||||
if (/^[A-Za-z]$/.test(t)) return { title: t, body: `A name. On its own it becomes the parameter ${t.toUpperCase()}; with an index subscript (${t}_i) it becomes a LIST OF FLOAT; bound by a sum it becomes the loop counter.`, where: 'name' };
|
||||
return null;
|
||||
}
|
||||
const cmd = t.slice(1);
|
||||
const refused = MATHO_REFUSALS.find((e) => e.term.split(/,\s*/).some((x) => x.replace(/^\\/, '') === cmd));
|
||||
if (refused) return { title: t, body: refused.meaning, where: 'refused' };
|
||||
const form = MATHO_FORMS.find((e) => new RegExp(`\\\\${cmd}(?![A-Za-z])`).test(e.term));
|
||||
if (form) return { title: form.term, body: form.meaning, where: 'LaTeX' };
|
||||
const greek: Record<string, string> = { alpha: 'Alpha', beta: 'Beta', gamma: 'Gamma', delta: 'Delta', theta: 'Theta', lambda: 'Lambda', mu: 'Mu', sigma: 'Sigma', tau: 'Tau', phi: 'Phi', omega: 'Omega', pi: 'PI()' };
|
||||
if (greek[cmd]) return { title: t, body: cmd === 'pi' ? 'The constant: PI().' : `A Greek letter is a name: ${greek[cmd]}.`, where: 'name' };
|
||||
return null;
|
||||
}
|
||||
case 'speco': {
|
||||
const sym = SPECO_SYMBOLS.find((s) => s.math === t || s.ascii === t.toUpperCase() || (s.math === '|X|' && t === '|') || (s.math === 'result' && t.toLowerCase() === 'result') || (s.ascii === 'OLD(X)' && t.toUpperCase() === 'OLD'));
|
||||
if (sym) return { title: `${sym.math} ${sym.ascii}`, body: sym.meaning, where: 'speco' };
|
||||
const kw: Record<string, string> = { SPEC: SPECO_FORMS[0].meaning, REQUIRE: SPECO_FORMS[1].meaning, ENSURE: SPECO_FORMS[2].meaning, LOOP: SPECO_FORMS[3].meaning, INVARIANT: SPECO_FORMS[4].meaning, DECREASES: SPECO_FORMS[5].meaning };
|
||||
if (kw[t.toUpperCase()]) return { title: t.toUpperCase(), body: kw[t.toUpperCase()], where: 'speco line' };
|
||||
return explain('pseudo', t, lineText);
|
||||
}
|
||||
case 'asm': {
|
||||
const lc = t.toLowerCase();
|
||||
const op = (OPS as Record<string, any>)[lc];
|
||||
if (op) return { title: lc, body: op.gloss || '', where: 'instruction' };
|
||||
const ccm = /^(j|set|cmov)([a-z]{1,3})$/.exec(lc);
|
||||
if (ccm && (CONDITION_TEXT as Record<string, string>)[ccm[2]]) return { title: lc, body: `${ccm[1] === 'j' ? 'jump' : ccm[1] === 'set' ? 'set the byte to 1' : 'copy'} if ${(CONDITION_TEXT as Record<string, string>)[ccm[2]]}`, where: 'conditional' };
|
||||
const base = regBase(lc);
|
||||
if (base) return { title: lc, body: `${REG_MEANING[base] || 'general register'}${base !== lc ? ` (the ${widthOf(lc)} part of ${base})` : ''}`, where: 'register' };
|
||||
if (/^(byte|word|dword|qword|xmmword)$/.test(lc)) return { title: `${lc} ptr`, body: `Says how many bytes to fetch: ${({ byte: 1, word: 2, dword: 4, qword: 8, xmmword: 16 } as any)[lc]}.` };
|
||||
if (/^(ZF|SF|CF|OF)$/i.test(t)) return { title: t.toUpperCase(), body: (ASM_REF.sections.find((s) => s.id === 'asm-flags')!.entries.find((e) => e.term === t.toUpperCase())?.meaning) || '' };
|
||||
if (/^\.?[A-Za-z_$][\w$.]*:?$/.test(t) && /:$/.test(t)) return { title: t.replace(/:$/, ''), body: 'A label: a name for the address of the next instruction.' };
|
||||
if (/^0x[0-9a-f]+$/i.test(t)) return { title: t, body: `${parseInt(t, 16)} in decimal.` };
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function regBase(name: string): string | null {
|
||||
const m: Record<string, string> = { eax: 'rax', ax: 'rax', al: 'rax', ah: 'rax', ebx: 'rbx', bx: 'rbx', bl: 'rbx', bh: 'rbx', ecx: 'rcx', cx: 'rcx', cl: 'rcx', ch: 'rcx', edx: 'rdx', dx: 'rdx', dl: 'rdx', dh: 'rdx', esi: 'rsi', si: 'rsi', sil: 'rsi', edi: 'rdi', di: 'rdi', dil: 'rdi', ebp: 'rbp', bp: 'rbp', bpl: 'rbp', esp: 'rsp', sp: 'rsp', spl: 'rsp' };
|
||||
if ((REG64 as string[]).includes(name)) return name;
|
||||
if (m[name]) return m[name];
|
||||
const r = /^(r(?:8|9|1[0-5]))[dwb]$/.exec(name);
|
||||
return r ? r[1] : null;
|
||||
}
|
||||
function widthOf(name: string): string {
|
||||
if (/^e|d$/.test(name) && !/^(d[lhix]|dil)$/.test(name)) return 'low 32-bit';
|
||||
if (/^[abcd]h$/.test(name)) return 'second byte';
|
||||
if (/[lb]$/.test(name)) return 'low byte';
|
||||
return 'low 16-bit';
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* The run, read top to bottom (the Developer and Bridge areas' Run view): one row per step, and a column for each
|
||||
* variable the student chose to follow, holding its value after that step, with the lifecycle of the value it
|
||||
* names (made, copied, moved in, moved out, destroyed) marked in the same cell. It replaces four views that each
|
||||
* showed part of this (the variables now, the trace table, the table of values, the lifetimes).
|
||||
*
|
||||
* DOM-free: src/ui/views/run.ts draws it; tests/runview.test.mjs checks it against the interpreters' traces.
|
||||
*/
|
||||
import type { Trace } from './types.js';
|
||||
import { formatValue, UNSET } from '../engines/pseudo/lang.js';
|
||||
|
||||
/** A variable as the run view knows it: its name in a routine. Recursion's frames of one routine share a column. */
|
||||
export interface RunColumn {
|
||||
/** `routine.name`, the column's identity. */
|
||||
key: string;
|
||||
fn: string;
|
||||
name: string;
|
||||
/** The type as the interpreter recorded it, in words. */
|
||||
type: string;
|
||||
/** How many steps write it, and the first. */
|
||||
writes: number;
|
||||
firstStep: number;
|
||||
}
|
||||
|
||||
export type LifeKind = 'made' | 'copied' | 'moved-in' | 'moved-out' | 'destroyed';
|
||||
export interface LifeMark { kind: LifeKind; text: string }
|
||||
|
||||
export interface RunCell {
|
||||
/** The value after the step, as the language prints it; null when the variable is not in scope (or has no value yet). */
|
||||
text: string | null;
|
||||
/** This step wrote it, or reads it. */
|
||||
wrote: boolean;
|
||||
read: boolean;
|
||||
/** What happened to the value it names during this step (Mojo values whose lifecycle can be seen). */
|
||||
life: LifeMark[];
|
||||
/** The positions this step wrote inside it (`2` for L[2], `5, 6` for D[5, 6]), when it wrote an element. */
|
||||
at: string[];
|
||||
}
|
||||
|
||||
export interface RunRow {
|
||||
/** 0-based step index; the stepper's position after it is `step + 1`. */
|
||||
step: number;
|
||||
line: number | null;
|
||||
text: string;
|
||||
kind: string;
|
||||
depth: number;
|
||||
/** Names written (with a position, `L[2]`, when one element was). */
|
||||
writes: string[];
|
||||
cells: Record<string, RunCell>;
|
||||
/** Lifecycle events of values no column names: temporaries, fields. */
|
||||
otherLife: string[];
|
||||
/** Lines printed by this step. */
|
||||
printed: string[];
|
||||
}
|
||||
|
||||
const frameName = (f: any): string => (f?.name ? String(f.name) : 'main');
|
||||
|
||||
export function typeText(t: any): string {
|
||||
if (!t) return '';
|
||||
if (typeof t === 'string') return t;
|
||||
if (t.k === 'LIST') return `LIST OF ${typeText(t.of)}`;
|
||||
if (t.k === 'SET') return `SET OF ${typeText(t.of)}`;
|
||||
return t.k || t.name || '';
|
||||
}
|
||||
|
||||
/** A value as its language prints it, or null for "no value yet". Mojo values carry their own display. */
|
||||
export function valueText(v: any): string | null {
|
||||
if (!v) return null;
|
||||
if (typeof v.text === 'string') return v.text;
|
||||
if (v.value === undefined || v.value === UNSET || typeof v.value === 'symbol') return null;
|
||||
return formatValue(v.value, v.type);
|
||||
}
|
||||
|
||||
/** The newest frame of routine `fn` in a state, the one a column reads (recursion shows its innermost call). */
|
||||
function frameOf(state: any, fn: string): any {
|
||||
const frames = (state?.frames ?? []).filter((f: any) => frameName(f) === fn);
|
||||
return frames[frames.length - 1] ?? null;
|
||||
}
|
||||
|
||||
/** Every variable that appears anywhere in the run, in order of first appearance. */
|
||||
export function runColumns(trace: Trace): RunColumn[] {
|
||||
if (trace.lang === 'asm') return [];
|
||||
const cols = new Map<string, RunColumn>();
|
||||
const states = trace.states as any[];
|
||||
for (let i = 0; i < states.length; i++) {
|
||||
for (const f of states[i]?.frames ?? []) {
|
||||
for (const v of Object.values(f.vars ?? {}) as any[]) {
|
||||
const key = `${frameName(f)}.${v.name}`;
|
||||
if (!cols.has(key)) cols.set(key, { key, fn: frameName(f), name: v.name, type: typeText(v.type), writes: 0, firstStep: Math.max(0, i - 1) });
|
||||
}
|
||||
}
|
||||
}
|
||||
(trace.steps as any[]).forEach((s, i) => {
|
||||
const st = trace.states[i + 1] as any;
|
||||
for (const w of s.writes ?? []) {
|
||||
const f = (st?.frames ?? []).find((x: any) => w.frame == null || x.id === w.frame);
|
||||
const c = cols.get(`${frameName(f)}.${w.name}`) ?? [...cols.values()].find((x) => x.name === w.name);
|
||||
if (c) c.writes++;
|
||||
}
|
||||
});
|
||||
return [...cols.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* The columns to follow when the student has not chosen: the variables of the routine that does the most work
|
||||
* (the most writes to its variables; `self` and `_` do not count), most changed first, up to `max`, shown in the
|
||||
* order they appear. A routine with nothing to change (a `main` that only calls) gives way to one that does.
|
||||
*/
|
||||
export function defaultFollow(cols: RunColumn[], max = 5): string[] {
|
||||
const plain = cols.filter((c) => c.name !== 'self' && c.name !== '_');
|
||||
const work = new Map<string, number>();
|
||||
for (const c of plain) work.set(c.fn, (work.get(c.fn) ?? 0) + c.writes);
|
||||
const fn = [...work].sort((a, b) => b[1] - a[1])[0]?.[0];
|
||||
if (fn == null) return [];
|
||||
const mine = plain.filter((c) => c.fn === fn);
|
||||
const pick = [...mine.filter((c) => c.writes > 0).sort((a, b) => b.writes - a.writes || a.firstStep - b.firstStep), ...mine.filter((c) => c.writes === 0)].slice(0, max);
|
||||
return pick.sort((a, b) => a.firstStep - b.firstStep).map((c) => c.key);
|
||||
}
|
||||
|
||||
/** Which value (by its id in the run) each variable names, and when: from the interpreter's `named` events. */
|
||||
function namesOfValues(trace: Trace): Map<number, string[]> {
|
||||
const out = new Map<number, string[]>();
|
||||
(trace.steps as any[]).forEach((s) => {
|
||||
for (const e of s.life ?? []) {
|
||||
if (e.kind !== 'named') continue;
|
||||
const key = `${s.sub ?? 'main'}.${e.name}`;
|
||||
const list = out.get(e.id) ?? [];
|
||||
if (!list.includes(key)) list.push(key);
|
||||
out.set(e.id, list);
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows for steps [from, to) with cells for the followed columns. Values are those after each step; a
|
||||
* variable not in scope after the step is blank. `onlyWrites` keeps the steps that change something, print, or
|
||||
* end a routine, as the old trace table's filter did.
|
||||
*/
|
||||
export function runRows(trace: Trace, follow: string[], from = 0, to = trace.count, opts: { onlyWrites?: boolean } = {}): RunRow[] {
|
||||
if (trace.lang === 'asm') return [];
|
||||
const steps = trace.steps as any[];
|
||||
const states = trace.states as any[];
|
||||
const named = namesOfValues(trace);
|
||||
const cols = follow.map((key) => { const dot = key.indexOf('.'); return { key, fn: key.slice(0, dot), name: key.slice(dot + 1) }; });
|
||||
const rows: RunRow[] = [];
|
||||
for (let i = Math.max(0, from); i < Math.min(to, trace.count); i++) {
|
||||
const s = steps[i];
|
||||
const before = states[i];
|
||||
// a step that stops the run is recorded after the frames unwound: its values are the ones it stopped on
|
||||
const after = s.kind === 'error' && !(states[i + 1]?.frames ?? []).length ? before : states[i + 1];
|
||||
const printed = (trace.output ?? []).slice(before?.outputLength ?? 0, after?.outputLength ?? 0);
|
||||
if (opts.onlyWrites && !(s.writes?.length || printed.length || s.kind === 'return' || s.kind === 'error' || s.life?.length)) continue;
|
||||
const cells: Record<string, RunCell> = {};
|
||||
for (const c of cols) {
|
||||
const f = frameOf(after, c.fn);
|
||||
const v = varIn(f?.vars, c.name);
|
||||
const own = (a: any) => a.name === c.name && (a.frame == null || a.frame === f?.id);
|
||||
cells[c.key] = { text: f && v ? valueText(v) : null, wrote: !!f && (s.writes ?? []).some(own), read: !!f && (s.reads ?? []).some(own), life: [], at: f ? [...new Set<string>((s.writes ?? []).filter((w: any) => own(w) && w.path).map((w: any) => w.path.join(', ')))] : [] };
|
||||
}
|
||||
const otherLife: string[] = [];
|
||||
for (const e of s.life ?? []) {
|
||||
if (e.kind === 'named') continue;
|
||||
const mark = (id: number, kind: LifeKind, text: string) => {
|
||||
const keys = (named.get(id) ?? []).filter((k) => cells[k]);
|
||||
if (keys.length) for (const k of keys) cells[k].life.push({ kind, text });
|
||||
else otherLife.push(`#${id} ${text}`);
|
||||
};
|
||||
if (e.kind === 'made') mark(e.id, 'made', `made: ${e.label}`);
|
||||
else if (e.kind === 'copied') mark(e.id, 'copied', `copied from #${e.from}`);
|
||||
else if (e.kind === 'moved') { mark(e.id, 'moved-in', `moved in from #${e.from}`); if (e.from != null) mark(e.from, 'moved-out', `moved out into #${e.id}`); }
|
||||
else if (e.kind === 'destroyed') mark(e.id, 'destroyed', 'destroyed');
|
||||
}
|
||||
rows.push({
|
||||
step: i, line: s.line ?? null, text: s.text || s.kind, kind: s.kind, depth: s.depth ?? (after?.frames?.length ?? 1) - 1,
|
||||
writes: [...new Set((s.writes ?? []).map((w: any) => (w.path ? `${w.name}[${w.path.join(', ')}]` : w.name)))] as string[],
|
||||
cells, otherLife, printed,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* A string or a list of plain values as a row of cells with their positions (the ruler a tutor draws), or null
|
||||
* for anything else, a single character, or more than 80 cells.
|
||||
*/
|
||||
export function rulerCells(v: any): string[] | null {
|
||||
if (!v) return null;
|
||||
let cells: string[] | null = null;
|
||||
const val = v.value;
|
||||
if (typeof v.text === 'string') {
|
||||
// Mojo: the interpreter's own values
|
||||
if (val?.k === 'str') cells = [...val.v];
|
||||
else if (val?.k === 'list' && val.items.every((x: any) => ['int', 'bool', 'str', 'float'].includes(x?.k)))
|
||||
cells = val.items.map((x: any) => (x.k === 'bool' ? (x.v ? 'True' : 'False') : String(x.v)));
|
||||
} else if (typeof val === 'string') cells = [...val];
|
||||
else if (val && Array.isArray(val.dims) && Array.isArray(val.data) && val.dims.length === 1 && val.data.every((x: any) => typeof x !== 'object'))
|
||||
cells = val.data.map((x: any) => (x === undefined || x === UNSET || typeof x === 'symbol' ? '' : formatValue(x, v.type?.of, { bareChar: true })));
|
||||
else if (Array.isArray(val) && val.every((x) => typeof x !== 'object')) cells = val.map((x) => formatValue(x, v.type?.of, { bareChar: true }));
|
||||
return cells && cells.length > 1 && cells.length <= 80 ? cells : null;
|
||||
}
|
||||
|
||||
/** A list of lists of plain values (a table, a grid) as rows of cell texts, at most 16 by 16; null otherwise. */
|
||||
export function gridCells(v: any): string[][] | null {
|
||||
if (!v || typeof v.text === 'string') {
|
||||
const val = v?.value;
|
||||
if (val?.k !== 'list' || !val.items.length || val.items.length > 16) return null;
|
||||
if (!val.items.every((r: any) => r?.k === 'list' && r.items.length <= 16 && r.items.every((x: any) => ['int', 'bool', 'str', 'float'].includes(x?.k)))) return null;
|
||||
return val.items.map((r: any) => r.items.map((x: any) => (x.k === 'bool' ? (x.v ? 'True' : 'False') : String(x.v))));
|
||||
}
|
||||
const val = v.value;
|
||||
// a pseudo ARRAY: its dimensions and its cells in row order
|
||||
if (val && Array.isArray(val.dims) && Array.isArray(val.data)) {
|
||||
if (val.dims.length !== 2 || val.dims[0] > 16 || val.dims[1] > 16) return null;
|
||||
const [r, c] = val.dims;
|
||||
return Array.from({ length: r }, (_, i) => val.data.slice(i * c, i * c + c).map((x: any) => (x === undefined || x === UNSET || typeof x === 'symbol' ? '' : formatValue(x, v.type?.of))));
|
||||
}
|
||||
if (!Array.isArray(val) || !val.length || val.length > 16 || !val.every((r) => Array.isArray(r) && r.length <= 16)) return null;
|
||||
return val.map((r: any[]) => r.map((x) => (x === undefined || x === UNSET || typeof x === 'symbol' ? '' : typeof x === 'object' ? '…' : formatValue(x, v.type?.of?.of))));
|
||||
}
|
||||
|
||||
/** Each followed variable at stepper position `t` (after `t` steps): its text, and its ruler or grid when it has one. */
|
||||
export function valuesAt(trace: Trace, follow: string[], t: number): Array<{ key: string; text: string | null; ruler: string[] | null; grid: string[][] | null; inScope: boolean; type: string }> {
|
||||
const at = Math.max(0, Math.min(t, trace.count));
|
||||
let st = (trace.states as any[])[at];
|
||||
if (at > 0 && (trace.steps as any[])[at - 1]?.kind === 'error' && !(st?.frames ?? []).length) st = (trace.states as any[])[at - 1];
|
||||
return follow.map((key) => {
|
||||
const dot = key.indexOf('.');
|
||||
const f = frameOf(st, key.slice(0, dot));
|
||||
const v = varIn(f?.vars, key.slice(dot + 1));
|
||||
return { key, text: v ? valueText(v) : null, ruler: v ? rulerCells(v) : null, grid: v ? gridCells(v) : null, inScope: !!f && !!v, type: typeText(v?.type) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame's variable by the name the program writes. Pseudo keys a frame's variables by that name, and lingo (whose
|
||||
* names are not case-sensitive) by the name in upper case, with the written name in `.name`: `Count` is under COUNT.
|
||||
*/
|
||||
export function varIn(vars: Record<string, any> | undefined, name: string): any {
|
||||
if (!vars) return undefined;
|
||||
return vars[name] ?? vars[name.toUpperCase()] ?? Object.values(vars).find((v: any) => v?.name === name);
|
||||
}
|
||||
@@ -0,0 +1,567 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import type { Diagnostic, LangId, Lowered, Parsed, ProofReport, PropertyReport, Trace, 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 { compileMojo, compilerDiagnostics, listingFunctions, type BuildLevel, type CompileOutcome, type ListingFunction } from '../services/godbolt.js';
|
||||
import { keepCompile, keptCompiles, compiledStatus, type CompiledStatus, type KeptCompile } from './compiles.js';
|
||||
import { mojoProvenance, type MojoProvenance } from './provenance.js';
|
||||
import { practicesOn } from './prefs.js';
|
||||
import { versionKey, listVersions, saveVersion, renameVersion, deleteVersion, restoreVersion, hasUnsavedEdits, currentVersion, newWorkspaceId, autoName, type SaveResult, type Version } from './versions.js';
|
||||
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';
|
||||
|
||||
/** One answer from godbolt, kept with exactly what it answered. */
|
||||
export interface CompileRecord {
|
||||
source: string;
|
||||
stdin: string;
|
||||
level: BuildLevel;
|
||||
at: number;
|
||||
outcome: CompileOutcome;
|
||||
/** The compiler's messages, on the Mojo pane's lines. */
|
||||
diagnostics: Diagnostic[];
|
||||
/** The listing, one entry per function. */
|
||||
functions: ListingFunction[];
|
||||
}
|
||||
|
||||
type Listener = (what: 'state' | 'source' | 'run') => void;
|
||||
|
||||
export class Session {
|
||||
state: PlayState;
|
||||
private memo = new Map<string, { key: string; value: any }>();
|
||||
private listeners = new Set<Listener>();
|
||||
/** 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
|
||||
* (the app), a given id for an embed's own save, or null for nowhere.
|
||||
* `keep` decides whether a state is worth saving at all; when it says no,
|
||||
* the save is removed (an embed keeps one only while it holds edits, so an
|
||||
* unedited example always shows the author's current version).
|
||||
*/
|
||||
// `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 } = {}) {
|
||||
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;
|
||||
}
|
||||
/**
|
||||
* The area the work is open in (from the route); the layout is kept per area. Null for a session that is not
|
||||
* a workspace (a single-view embed, a test): every pane counts, and the Mojo pane is the state's own.
|
||||
*/
|
||||
readonly area: AreaId | null;
|
||||
private readonly finder: typeof findPractices;
|
||||
private readonly storageId: string | null | undefined;
|
||||
/** A catalog problem's own version, so a save records which version it was made against and whether it differs. */
|
||||
private original: PlayState | null;
|
||||
/** The student's edits were made to an older version of the problem than the one the app now has. */
|
||||
stale: boolean;
|
||||
/** The problem's own version is shown again (Reset): later saves are made against it. */
|
||||
resetTo(state: PlayState): void { this.original = structuredClone(state); this.stale = false; this.replace(state); }
|
||||
private readonly keep: ((state: PlayState) => boolean) | undefined;
|
||||
|
||||
onChange(fn: Listener): () => void { this.listeners.add(fn); return () => this.listeners.delete(fn); }
|
||||
|
||||
/** The stepper moved to step `t`: cheap, frequent, not persisted. Views that follow the run listen here. */
|
||||
private stepListeners = new Set<(t: number) => void>();
|
||||
onStep(fn: (t: number) => void): () => void { this.stepListeners.add(fn); return () => this.stepListeners.delete(fn); }
|
||||
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<T>(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;
|
||||
}
|
||||
|
||||
/* ---------- mutation ---------- */
|
||||
|
||||
/**
|
||||
* The student typed in pane `lang`. For the four linked languages the hub makes the other panes follow in the
|
||||
* same change (sync/hub.ts); 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 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;
|
||||
this.persist(); this.emit('source');
|
||||
}
|
||||
|
||||
/**
|
||||
* "Edit in Developer": the Bridge's generated Mojo becomes the Mojo pane's own text, recorded as generated so
|
||||
* the Developer area can say so. The caller asks first when the pane already holds something else.
|
||||
*/
|
||||
adoptGeneratedMojo(): boolean {
|
||||
const d = this.derivedMojo();
|
||||
if (!d.source.trim()) return false;
|
||||
this.state.sources.mojo = d.source;
|
||||
this.state.mojoOrigin = 'generated';
|
||||
this.state.lang = 'mojo';
|
||||
this.memo.delete('mojo'); this.memo.delete('trace.mojo');
|
||||
this.persist(); this.emit('source');
|
||||
return true;
|
||||
}
|
||||
/** Where the Mojo in the pane came from, for the labels (core/provenance.ts). */
|
||||
provenance(): MojoProvenance { return mojoProvenance(this); }
|
||||
/**
|
||||
* "I've reviewed this": the only way generated Mojo stops being labeled. Takes the header comment off and forgets
|
||||
* the origin; nothing else (not a successful compile, not an edit) does.
|
||||
*/
|
||||
clearMojoOrigin(): boolean {
|
||||
if (!this.state.mojoOrigin || this.area === 'bridge') return false;
|
||||
const lines = (this.state.sources.mojo ?? '').split('\n');
|
||||
if (lines[0] === GENERATED_HEADER) lines.shift();
|
||||
if (lines.length && lines[0].trim() === '' && (this.state.sources.mojo ?? '').startsWith(GENERATED_HEADER)) lines.shift();
|
||||
this.state.sources.mojo = lines.join('\n');
|
||||
delete this.state.mojoOrigin;
|
||||
this.memo.delete('mojo'); this.memo.delete('trace.mojo');
|
||||
this.persist(); this.emit('source');
|
||||
return true;
|
||||
}
|
||||
/** Whether adopting the generated Mojo would replace Mojo the pane holds that is not already this program. */
|
||||
wouldReplaceMojo(): boolean {
|
||||
const have = (this.state.sources.mojo ?? '').trim();
|
||||
return !!have && have !== this.derivedMojo().source.trim();
|
||||
}
|
||||
/** 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<Record<Linked, string>>; 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. */
|
||||
layout(): Layout { return this.area ? this.state.layout?.[this.area] ?? {} : {}; }
|
||||
setLayout(l: Layout): void { if (!this.area) return; this.state.layout = { ...(this.state.layout || {}), [this.area]: { ...(this.state.layout?.[this.area] || {}), ...l } }; this.persist(); }
|
||||
/* ---------- saved versions (core/versions.ts) ---------- */
|
||||
|
||||
/** The list this work keeps its versions in; null until work from a link or a file is first saved. */
|
||||
versionKey(): string | null { return versionKey(this.state); }
|
||||
versions(): Version[] { return listVersions(this.versionKey()); }
|
||||
/** Whether the work has edits that no saved version holds (and, for a catalog problem, that differ from the problem as written). */
|
||||
hasUnsavedEdits(): boolean { return hasUnsavedEdits(this.versionKey(), this.state, this.original); }
|
||||
/** The saved version the work is exactly, if it is one. */
|
||||
currentVersion(): Version | null { return currentVersion(this.versionKey(), this.state); }
|
||||
|
||||
/** Save the work under a name. Work that came from a link or a file gets its workspace id the first time. */
|
||||
saveVersion(name: string, auto = false): SaveResult {
|
||||
if (!this.state.problem && !this.state.workspace) { this.state.workspace = newWorkspaceId(); this.persist(); this.emit('state'); }
|
||||
return saveVersion(this.versionKey(), name, this.state, this.area ?? 'bridge', { auto });
|
||||
}
|
||||
renameVersion(id: string, name: string): boolean { return renameVersion(this.versionKey(), id, name); }
|
||||
deleteVersion(id: string): boolean { return deleteVersion(this.versionKey(), id); }
|
||||
|
||||
/** Save the work as "Before switching (time)" when it holds edits nothing else holds. False when it could not be saved (the caller asks before going on). */
|
||||
private keepBefore(why: 'switching' | 'reset'): boolean {
|
||||
if (!this.hasUnsavedEdits()) return true;
|
||||
return this.saveVersion(autoName(why), true).ok;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a saved version the work. What the work held that no version does is saved first, so switching never loses
|
||||
* it; the layout, the step and the open tab stay as they are. Returns false when that save was refused (and nothing changed).
|
||||
*/
|
||||
restoreVersion(id: string): boolean {
|
||||
const key = this.versionKey();
|
||||
if (!key || !this.versions().some((v) => v.id === id)) return false;
|
||||
if (!this.keepBefore('switching')) return false;
|
||||
const next = restoreVersion(key, id, this.state);
|
||||
if (!next) return false;
|
||||
this.replace(next);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Back to the exercise as written: the work is saved first as "Before reset (time)" when it holds edits. False when that save was refused. */
|
||||
reset(fresh: PlayState): boolean {
|
||||
if (!this.keepBefore('reset')) return false;
|
||||
this.resetTo(fresh);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The problem changed under the student's edits (`stale`): keep the edits as a version and open the problem as it
|
||||
* is now. False when there is nothing to open (no catalog problem) or the save was refused.
|
||||
*/
|
||||
seeNewVersion(): boolean {
|
||||
if (!this.original || !this.state.problem) return false;
|
||||
if (!this.saveVersion(autoName('new')).ok) return false;
|
||||
this.resetTo(structuredClone(this.original));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Work that is not the problem this session opened with (a loaded file): the problem's own version no longer applies. */
|
||||
adopt(state: PlayState): void { this.original = null; this.stale = false; this.replace(state); }
|
||||
replace(state: PlayState): void { this.state = state; this.memo.clear(); this.maps = { up: {}, down: {} }; this.persist(); this.emit('source'); }
|
||||
|
||||
private persist(): void {
|
||||
const id = this.storageId === undefined ? this.state.problem : this.storageId;
|
||||
if (!id) return;
|
||||
if (this.original && id === this.state.problem) { this.state.base = editsFingerprint(this.original); this.state.edited = editedFrom(this.state, this.original); }
|
||||
if (this.keep && !this.keep(this.state)) clearLocal(id);
|
||||
else saveLocal(id, this.state);
|
||||
}
|
||||
|
||||
/* ---------- 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<any> | null {
|
||||
const src = this.source('lingo');
|
||||
if (!src.trim()) return null;
|
||||
return this.cached('lingo', src, () => SERVICES.lingo.parse(src));
|
||||
}
|
||||
|
||||
parsedMatho(): Parsed<MathoProgram> | null {
|
||||
const src = this.source('matho');
|
||||
if (!src.trim()) return null;
|
||||
return this.cached('matho', src, () => SERVICES.matho.parse(src) as Parsed<MathoProgram>);
|
||||
}
|
||||
|
||||
parsedPseudo(): Parsed<any> | null {
|
||||
const source = this.source('pseudo');
|
||||
if (!source.trim()) return null;
|
||||
return this.cached('pseudo', source, () => studyOf(source));
|
||||
}
|
||||
|
||||
parsedSpeco(): Parsed<SpecoProgram> | null {
|
||||
const src = this.source('speco');
|
||||
if (!src.trim()) return null;
|
||||
return this.cached('speco', src, () => SERVICES.speco.parse(src) as Parsed<SpecoProgram>);
|
||||
}
|
||||
|
||||
parsedMojo(): Parsed<MojoProgram> | null {
|
||||
const src = this.source('mojo');
|
||||
if (!src.trim()) return null;
|
||||
return this.cached('mojo', src, () => SERVICES.mojo.parse(src) as Parsed<MojoProgram>);
|
||||
}
|
||||
|
||||
/* ---------- the real compiler ---------- */
|
||||
|
||||
private compiles: CompileRecord[] = [];
|
||||
/** A request in flight, so the button can say so and a second click waits. */
|
||||
compiling: Promise<CompileRecord | null> | null = null;
|
||||
|
||||
buildLevel(): BuildLevel { return this.state.build ?? 'O0'; }
|
||||
setBuildLevel(level: BuildLevel): void { this.state.build = level; this.persist(); this.emit('state'); }
|
||||
|
||||
/** Compile and run the Mojo pane on godbolt; the answer is kept for the views that read it. */
|
||||
compile(fetchImpl?: typeof compileMojo, levelOverride?: BuildLevel): Promise<CompileRecord | null> {
|
||||
if (this.compiling) return this.compiling;
|
||||
const source = this.source('mojo');
|
||||
if (!source.trim()) return Promise.resolve(null);
|
||||
const stdin = this.inputLines().join('\n') + (this.inputLines().length ? '\n' : '');
|
||||
const level = levelOverride ?? this.buildLevel();
|
||||
this.compiling = (fetchImpl ?? compileMojo)(source, { stdin, level }).then((outcome) => {
|
||||
const rec: CompileRecord = {
|
||||
source, stdin, level, at: Date.now(), outcome,
|
||||
diagnostics: outcome.answer ? compilerDiagnostics(outcome.answer.buildStderr) : [],
|
||||
functions: outcome.answer ? listingFunctions(outcome.answer.asm) : [],
|
||||
};
|
||||
this.compiles = [rec, ...this.compiles.filter((r) => !(r.source === source && r.stdin === stdin && r.level === level))].slice(0, 8);
|
||||
keepCompile(rec);
|
||||
return rec;
|
||||
}).finally(() => { this.compiling = null; this.emit('run'); });
|
||||
this.emit('run');
|
||||
return this.compiling;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers godbolt gave earlier for exactly the source now in the Mojo pane, in this tab or another, before a
|
||||
* reload or a change of problem (core/compiles.ts): they join this session's own, so nothing is asked twice.
|
||||
*/
|
||||
private recall(): void {
|
||||
const src = this.source('mojo');
|
||||
if (!src.trim() || this.recalledFor === src) return;
|
||||
this.recalledFor = src;
|
||||
const have = (k: KeptCompile) => this.compiles.some((r) => r.source === k.source && r.stdin === k.stdin && r.level === k.level);
|
||||
const kept = keptCompiles(src).filter((k) => !have(k)).map((k): CompileRecord => ({
|
||||
...k, diagnostics: k.outcome.answer ? compilerDiagnostics(k.outcome.answer.buildStderr) : [], functions: k.outcome.answer ? listingFunctions(k.outcome.answer.asm) : [],
|
||||
}));
|
||||
if (kept.length) this.compiles = [...this.compiles, ...kept].sort((a, b) => b.at - a.at).slice(0, 8);
|
||||
}
|
||||
private recalledFor: string | null = null;
|
||||
|
||||
/** The newest answer, and whether the pane still holds the source it answered. */
|
||||
lastCompile(): { record: CompileRecord; fresh: boolean } | null {
|
||||
this.recall();
|
||||
// the build level the student chose; another level's answer (asked for to compare) does not replace it
|
||||
const rec = this.compiles.find((r) => r.level === this.buildLevel()) ?? this.compiles[0];
|
||||
return rec ? { record: rec, fresh: rec.source === this.source('mojo') } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The godbolt badge for the Mojo in the pane: 'compiled' when this browser asked godbolt about exactly this
|
||||
* source, input and build level; 'edited' when this session compiled an earlier version; otherwise nothing.
|
||||
*/
|
||||
compileBadge(): { kind: 'compiled'; status: CompiledStatus } | { kind: 'edited' } | null {
|
||||
const src = this.source('mojo');
|
||||
if (!src.trim()) return null;
|
||||
const stdin = this.inputLines().join('\n') + (this.inputLines().length ? '\n' : '');
|
||||
const status = compiledStatus(src, stdin, this.buildLevel());
|
||||
if (status) return { kind: 'compiled', status };
|
||||
this.recall();
|
||||
return this.compiles.length && !this.compiles.some((r) => r.source === src) ? { kind: 'edited' } : null;
|
||||
}
|
||||
|
||||
/** The answer for this source at a given build level, if one has been asked for (the comparison of builds). */
|
||||
compileAt(source: string, level: BuildLevel): CompileRecord | null {
|
||||
this.recall();
|
||||
return this.compiles.find((r) => r.source === source && r.level === level) ?? null;
|
||||
}
|
||||
|
||||
/** The newest answer for exactly the source in the pane (any input or build), for its diagnostics. */
|
||||
private compileForSource(): CompileRecord | null {
|
||||
this.recall();
|
||||
const src = this.source('mojo');
|
||||
return this.compiles.find((r) => r.source === src) ?? null;
|
||||
}
|
||||
|
||||
/* ---------- best practices (off until the student turns it on, per area) ---------- */
|
||||
|
||||
/** Whether the helper is on for the area that is open. */
|
||||
practicesOn(): boolean { return practicesOn(this.area); }
|
||||
/**
|
||||
* What the best-practices rules find in the Mojo on screen: nothing at all, and nothing is run, unless the helper is
|
||||
* on for this area. In the Bridge that is the generated Mojo; in the Developer area, the student's own.
|
||||
*/
|
||||
practices(): PracticeFinding[] {
|
||||
if (!this.practicesOn()) return [];
|
||||
const src = this.source('mojo');
|
||||
if (!src.trim()) return [];
|
||||
return this.cached('practices', src, () => this.finder(src, this.parsedMojo()?.program?.module));
|
||||
}
|
||||
|
||||
/** The pseudo lines a line of the Bridge's Mojo came from (empty when it came from none, or there is no pseudo). */
|
||||
pseudoLinesOfMojo(line: number): number[] { return SyncHub.relate(this.lineMaps(), 'mojo', line, 'pseudo'); }
|
||||
|
||||
/**
|
||||
* The Bridge's "Show idiomatic version": a copy of the generated Mojo with the safe best-practice rewrites applied,
|
||||
* offered only when the result passes the checker as well as the literal one did and the interpreter prints exactly
|
||||
* what it prints for the literal one (which the tests tie to the pseudo's own run). Otherwise the reason it was
|
||||
* not offered. Asked for on demand; nothing runs until it is.
|
||||
*/
|
||||
idiomaticMojo(): { ok: true; source: string; applied: PracticeFinding[] } | { ok: false; reason: string } {
|
||||
if (!this.practicesOn() || this.area !== 'bridge') return { ok: false, reason: 'Best practices are off.' };
|
||||
const literal = this.source('mojo');
|
||||
if (!literal.trim()) return { ok: false, reason: 'There is no Mojo yet.' };
|
||||
return this.cached('idiomatic', literal, () => {
|
||||
const { source, applied } = applyPractices(literal);
|
||||
if (!applied.length) return { ok: false as const, reason: 'There is nothing to rewrite safely.' };
|
||||
const errs = (t: string) => checkMojo(t).diagnostics.filter((d) => d.severity === 'error').length;
|
||||
if (errs(source) > errs(literal)) return { ok: false as const, reason: 'The rewritten version did not pass the checker, so it is not shown.' };
|
||||
const run = (t: string) => { const m = checkMojo(t); return runMojo(m.module, t, { input: this.inputLines() }); };
|
||||
const a = run(literal), b = run(source);
|
||||
if (a.refused !== null || b.refused !== null) return { ok: false as const, reason: `Programming+ could not run both versions to compare them (${a.refused ?? b.refused}), so it does not show the rewrite.` };
|
||||
if (a.stdout !== b.stdout || a.exitCode !== b.exitCode) return { ok: false as const, reason: 'The rewritten version printed something different, so it is not shown.' };
|
||||
return { ok: true as const, source, applied };
|
||||
});
|
||||
}
|
||||
|
||||
parsedAsm(): Parsed<any> | 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 ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
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<any> | 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 } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* The whole playground is one state object. It lives in the URL hash (so a
|
||||
* link opens exactly this state, in the app or as an embedded view) and in
|
||||
* localStorage per problem (so a reload keeps a student's work).
|
||||
*
|
||||
* Routes (<area> is bridge, dev or hw: src/core/areas.ts; nothing else is a route):
|
||||
* #/ home: the problem list
|
||||
* #/<area>/p/<problemId> a catalog problem in an area, with the student's saved edits
|
||||
* #/<area>/s/<blob> a shared state in an area, compressed into the URL
|
||||
* #/embed/<view>/<blob> one view, no chrome, for an <iframe>
|
||||
* #/embed/<view>/p/<id> one view of a catalog problem
|
||||
* #/embed/playground/... the whole workspace, as the state lays it out (area=<area> picks the area)
|
||||
* #/quarto "With Quarto": the Quarto extension's shortcodes, as a gallery (#/quarto#<section> scrolls)
|
||||
*
|
||||
* The blob is deflate-raw + base64url of the JSON below; `~` prefix marks
|
||||
* plain base64url when compression is unavailable.
|
||||
*/
|
||||
import type { LangId, ViewId } from './types.js';
|
||||
import type { SyncInfo } from '../sync/hub.js';
|
||||
import { isAreaId, type AreaId } from './areas.js';
|
||||
import { normalizeBoard, type BoardItem } from './hardware.js';
|
||||
|
||||
export interface PlayState {
|
||||
v: 3;
|
||||
problem?: string;
|
||||
title?: string;
|
||||
sources: Partial<Record<LangId, string>>;
|
||||
/** Which language pane is active. */
|
||||
lang: LangId;
|
||||
/** Which bottom view is open. */
|
||||
view: ViewId;
|
||||
/** The call used to run, e.g. `COUNT_BASE('A', "GATTACA")`. */
|
||||
call?: string | null;
|
||||
/** Lines INPUT reads, one per line, for pseudo, lingo and matho runs. */
|
||||
input?: string;
|
||||
/** Assembly setup block and machine preset. */
|
||||
setup?: string;
|
||||
machine?: string;
|
||||
/** Step index the stepper is parked at. */
|
||||
t?: number;
|
||||
/** The bottom views pane, folded away. */
|
||||
viewsCollapsed?: boolean;
|
||||
/** How the Mojo pane is compiled: as written (-O0, every function kept) or as `mojo build` does by default. */
|
||||
build?: 'O0' | 'default';
|
||||
/** The workspace as the student arranged it, one arrangement per area: pane widths as fractions, which dock tab is open, what is folded. */
|
||||
layout?: Partial<Record<AreaId, Layout>>;
|
||||
/**
|
||||
* Which linked pane (lingo, matho, pseudo, speco) was edited last, so the others follow it; which panes are
|
||||
* not in step and why; and the student's own spelling of equation names. Absent until the first edit.
|
||||
*/
|
||||
sync?: SyncInfo;
|
||||
/**
|
||||
* Where `sources.mojo` came from when the student did not write it: `generated` for Mojo copied out of the
|
||||
* Bridge (the literal translation of pseudo), `generated-edited` once the student has changed it. Absent for Mojo
|
||||
* written by hand or an exercise's own program.
|
||||
*/
|
||||
mojoOrigin?: 'generated' | 'generated-edited';
|
||||
/** Work that began from a share link or a file has no problem id: this names it, so its saved versions have a home. Added when such work is first saved. */
|
||||
workspace?: string;
|
||||
/** For a save of a catalog problem: the fingerprint of the problem as it was when the save was made. */
|
||||
base?: string;
|
||||
/** For a save of a catalog problem: whether it holds edits the problem did not. */
|
||||
edited?: boolean;
|
||||
}
|
||||
|
||||
export type DockTab = 'setup' | 'output' | 'problems' | 'compiler' | 'asm' | 'practices';
|
||||
|
||||
export interface Layout {
|
||||
/** Editor column width. */
|
||||
split?: number;
|
||||
/** The active pane's share of the editor column beside its companion. */
|
||||
companion?: number;
|
||||
/** The variables panel's share of the right column. */
|
||||
right?: number;
|
||||
/** The dock's share of the height. */
|
||||
dock?: number;
|
||||
dockTab?: DockTab;
|
||||
dockCollapsed?: boolean;
|
||||
setupCollapsed?: boolean;
|
||||
/** The Hardware area's board: the cards it shows, in order (core/hardware.ts); absent means the first preset. */
|
||||
board?: BoardItem[];
|
||||
/** The variables the Run view follows, as `routine.name` (core/runview.ts); absent until the student chooses. */
|
||||
follow?: string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'];
|
||||
|
||||
/**
|
||||
* What `#/embed/<view>/...` can show: the whole playground, one view with the code it reads, or one
|
||||
* pane (a LangId). The Share dialog offers these, and the Quarto shortcode's `view=` takes them.
|
||||
*/
|
||||
export const EMBED_VIEWS = ['playground', 'trace', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'problems', 'compiler', 'asm', ...DEFAULT_PANES.filter((p) => p !== 'asm')] as const;
|
||||
|
||||
export function emptyState(): PlayState {
|
||||
return { v: 3, sources: {}, lang: 'pseudo', view: 'problems' };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Encoding */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const B64 = { enc: (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''), dec: (s: string) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0)) };
|
||||
|
||||
async function pipe(bytes: Uint8Array, stream: any): Promise<Uint8Array> {
|
||||
const ws = new Blob([bytes as BlobPart]).stream().pipeThrough(stream);
|
||||
return new Uint8Array(await new Response(ws).arrayBuffer());
|
||||
}
|
||||
|
||||
export async function encodeState(state: PlayState): Promise<string> {
|
||||
const json = new TextEncoder().encode(JSON.stringify(state));
|
||||
try {
|
||||
if (typeof CompressionStream !== 'undefined') return B64.enc(await pipe(json, new CompressionStream('deflate-raw')));
|
||||
} catch { /* fall through */ }
|
||||
return '~' + B64.enc(json);
|
||||
}
|
||||
|
||||
export async function decodeState(blob: string): Promise<PlayState> {
|
||||
let bytes: Uint8Array;
|
||||
if (blob.startsWith('~')) bytes = B64.dec(blob.slice(1));
|
||||
else bytes = await pipe(B64.dec(blob), new DecompressionStream('deflate-raw'));
|
||||
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
||||
return normalize(parsed);
|
||||
}
|
||||
|
||||
function normalizeLayout(l: any): Layout {
|
||||
const num = (v: any) => (typeof v === 'number' && v > 0 && v < 1 ? v : undefined);
|
||||
return { split: num(l.split), companion: num(l.companion), right: num(l.right), dock: num(l.dock),
|
||||
dockTab: ['setup', 'output', 'problems', 'compiler', 'asm', 'practices'].includes(l.dockTab) ? l.dockTab : undefined,
|
||||
dockCollapsed: typeof l.dockCollapsed === 'boolean' ? l.dockCollapsed : undefined, setupCollapsed: typeof l.setupCollapsed === 'boolean' ? l.setupCollapsed : undefined,
|
||||
board: normalizeBoard(l.board),
|
||||
follow: Array.isArray(l.follow) ? l.follow.filter((k: unknown) => typeof k === 'string' && k.includes('.')).slice(0, 40) : undefined };
|
||||
}
|
||||
|
||||
export function normalize(x: any): PlayState {
|
||||
const s = emptyState();
|
||||
// Programming+ is a new product: a state from any other version (an old link, an old save, no
|
||||
// version at all) normalizes to empty rather than being migrated. No aliases, no legacy fields.
|
||||
if (!x || typeof x !== 'object' || x.v !== 3) return s;
|
||||
if (x.sources && typeof x.sources === 'object') for (const k of DEFAULT_PANES) if (typeof x.sources[k] === 'string') s.sources[k] = x.sources[k];
|
||||
if (DEFAULT_PANES.includes(x.lang)) s.lang = x.lang;
|
||||
if (['problems', 'trace', 'proof', 'tests', 'asm', 'flow', 'data', 'table', 'compiler', 'life'].includes(x.view)) s.view = x.view;
|
||||
if (x.build === 'O0' || x.build === 'default') s.build = x.build;
|
||||
if (typeof x.viewsCollapsed === 'boolean') s.viewsCollapsed = x.viewsCollapsed;
|
||||
if (x.layout && typeof x.layout === 'object') {
|
||||
const layouts: Partial<Record<AreaId, Layout>> = {};
|
||||
for (const [k, v] of Object.entries(x.layout)) if (isAreaId(k) && v && typeof v === 'object') layouts[k] = normalizeLayout(v);
|
||||
if (Object.keys(layouts).length) s.layout = layouts;
|
||||
}
|
||||
if (typeof x.call === 'string' || x.call === null) s.call = x.call;
|
||||
if (typeof x.setup === 'string') s.setup = x.setup;
|
||||
if (typeof x.input === 'string') s.input = x.input;
|
||||
if (typeof x.machine === 'string') s.machine = x.machine;
|
||||
if (typeof x.t === 'number' && x.t >= 0) s.t = Math.floor(x.t);
|
||||
if (typeof x.problem === 'string') s.problem = x.problem;
|
||||
if (typeof x.title === 'string') s.title = x.title;
|
||||
if (x.sync && typeof x.sync === 'object' && ['lingo', 'matho', 'pseudo', 'speco'].includes(x.sync.authority)) {
|
||||
const stale: SyncInfo['stale'] = {};
|
||||
if (x.sync.stale && typeof x.sync.stale === 'object') for (const k of ['lingo', 'matho', 'pseudo', 'speco'] as const) if (typeof x.sync.stale[k] === 'string') stale[k] = x.sync.stale[k];
|
||||
const names: Record<string, string> = {};
|
||||
if (x.sync.names && typeof x.sync.names === 'object') for (const [k, v] of Object.entries(x.sync.names)) if (typeof v === 'string') names[k] = v;
|
||||
s.sync = { authority: x.sync.authority, stale, names };
|
||||
}
|
||||
if (x.mojoOrigin === 'generated' || x.mojoOrigin === 'generated-edited') s.mojoOrigin = x.mojoOrigin;
|
||||
if (typeof x.workspace === 'string' && /^[a-z0-9-]{4,48}$/.test(x.workspace)) s.workspace = x.workspace;
|
||||
if (typeof x.base === 'string') s.base = x.base;
|
||||
if (typeof x.edited === 'boolean') s.edited = x.edited;
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* An embed's query can set up the example the way the playground's own controls do, so a catalog
|
||||
* problem (`#/embed/playground/p/demo`) can be shown arranged for a page without a blob:
|
||||
* lang=mojo the pane that is active
|
||||
* panel=flow the inspect tab (trace table values flow data life proof tests) or dock tab
|
||||
* (output problems compiler asm setup) the playground opens on
|
||||
* build=O0|default how the Mojo pane is compiled
|
||||
* machine=<preset> the x86-64 machine model
|
||||
* dock=open|closed the dock under the editors; docktab=<tab> picks its tab
|
||||
* area=dev the area the whole-workspace embed shows (bridge, dev, hw); the layout below is that area's
|
||||
* editor=0.6 side=0.5 dockheight=0.7 the playground's split fractions (editor column, variables
|
||||
* panel, and the dock's share of the height)
|
||||
* t=12 the step the stepper is parked at
|
||||
* Anything not given keeps what the state says; anything malformed is ignored.
|
||||
*/
|
||||
export function applyEmbedParams(state: PlayState, params: URLSearchParams, area: AreaId = 'bridge'): PlayState {
|
||||
const s: PlayState = { ...state, layout: { ...(state.layout ?? {}), [area]: { ...(state.layout?.[area] ?? {}) } } };
|
||||
const layout = s.layout![area]!;
|
||||
const lang = params.get('lang');
|
||||
if (lang && (DEFAULT_PANES as string[]).includes(lang)) s.lang = lang as LangId;
|
||||
const panel = params.get('panel');
|
||||
if (panel && ['trace', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'problems', 'compiler', 'asm'].includes(panel)) s.view = panel as ViewId;
|
||||
if (panel === 'output' || panel === 'setup') layout.dockTab = panel;
|
||||
const build = params.get('build');
|
||||
if (build === 'O0' || build === 'default') s.build = build;
|
||||
const machine = params.get('machine');
|
||||
if (machine) s.machine = machine;
|
||||
const dock = params.get('dock');
|
||||
if (dock === 'open' || dock === 'closed') layout.dockCollapsed = dock === 'closed';
|
||||
const tab = params.get('docktab');
|
||||
if (tab && ['setup', 'output', 'problems', 'compiler', 'asm', 'practices'].includes(tab)) layout.dockTab = tab as DockTab;
|
||||
const frac = (k: string) => { const v = Number(params.get(k)); return params.has(k) && v > 0 && v < 1 ? v : undefined; };
|
||||
if (frac('editor') !== undefined) layout.split = frac('editor');
|
||||
if (frac('side') !== undefined) layout.right = frac('side');
|
||||
if (frac('dockheight') !== undefined) layout.dock = frac('dockheight');
|
||||
const t = Number(params.get('t'));
|
||||
if (params.has('t') && Number.isInteger(t) && t >= 0) s.t = t;
|
||||
if (!Object.keys(layout).length) delete s.layout![area];
|
||||
return s;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Routes */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export type Route =
|
||||
| { kind: 'home' }
|
||||
| { kind: 'quarto'; anchor?: string }
|
||||
| { kind: 'problem'; area: AreaId; id: string }
|
||||
| { kind: 'shared'; area: AreaId; blob: string }
|
||||
| { kind: 'embed'; view: ViewId | LangId; blob?: string; problem?: string; params: URLSearchParams };
|
||||
|
||||
/** Anything that is not one of the routes in the header is home; there are no aliases for old links. */
|
||||
export function parseRoute(hash: string): Route {
|
||||
const h = (hash || '').replace(/^#/, '');
|
||||
const [pathPart, query = ''] = h.split('?');
|
||||
const parts = pathPart.split('/').filter(Boolean);
|
||||
const params = new URLSearchParams(query);
|
||||
if (!parts.length) return { kind: 'home' };
|
||||
if (parts.length === 1 && /^quarto(#[\w-]*)?$/.test(parts[0])) { const a = parts[0].split('#')[1]; return a ? { kind: 'quarto', anchor: a } : { kind: 'quarto' }; }
|
||||
if (isAreaId(parts[0]) && parts[1] === 'p' && parts[2]) return { kind: 'problem', area: parts[0], id: decodeURIComponent(parts[2]) };
|
||||
if (isAreaId(parts[0]) && parts[1] === 's' && parts[2]) return { kind: 'shared', area: parts[0], blob: parts[2] };
|
||||
if (parts[0] === 'embed' && parts[1]) {
|
||||
const view = parts[1] as ViewId | LangId;
|
||||
if (parts[2] === 'p' && parts[3]) return { kind: 'embed', view, problem: decodeURIComponent(parts[3]), params };
|
||||
return { kind: 'embed', view, blob: parts[2], params };
|
||||
}
|
||||
return { kind: 'home' };
|
||||
}
|
||||
|
||||
export function routeFor(r: Route): string {
|
||||
switch (r.kind) {
|
||||
case 'home': return '#/';
|
||||
case 'quarto': return r.anchor ? `#/quarto#${r.anchor}` : '#/quarto';
|
||||
case 'problem': return `#/${r.area}/p/${encodeURIComponent(r.id)}`;
|
||||
case 'shared': return `#/${r.area}/s/${r.blob}`;
|
||||
case 'embed': {
|
||||
const q = r.params.toString();
|
||||
const base = r.problem ? `#/embed/${r.view}/p/${encodeURIComponent(r.problem)}` : `#/embed/${r.view}/${r.blob}`;
|
||||
return q ? `${base}?${q}` : base;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Local persistence */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const KEY = (id: string) => `pplus.${id}`;
|
||||
|
||||
/** Saved work from before the rename lives under the old prefix; read it once, then it is re-saved under the new one. */
|
||||
export function migrateLocal(): void {
|
||||
try {
|
||||
for (const k of Object.keys(localStorage)) {
|
||||
if (k.startsWith('progo.') && localStorage.getItem('pplus.' + k.slice(6)) === null) localStorage.setItem('pplus.' + k.slice(6), localStorage.getItem(k)!);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
export function loadLocal(id: string): PlayState | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY(id));
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw);
|
||||
// a save from another state format is dropped, not migrated: the problem opens as written
|
||||
if (!parsed || parsed.v !== 3) { clearLocal(id); return null; }
|
||||
return normalize(parsed);
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
export function saveLocal(id: string, state: PlayState): void {
|
||||
try { localStorage.setItem(KEY(id), JSON.stringify(state)); } catch { /* private mode or quota */ }
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an embed keeps the reader's edits: its own save, one per embedded
|
||||
* example (the view, and the problem or the program's blob), never the
|
||||
* app's save for the problem. Two pages that embed the same example share it.
|
||||
*/
|
||||
export function embedStorageId(view: string, problem?: string, blob?: string): string {
|
||||
if (problem) return `embed.${view}.p.${problem}`;
|
||||
let h = 0x811c9dc5; // FNV-1a: a short, stable name for a long blob
|
||||
for (let i = 0; i < (blob ?? '').length; i++) { h ^= blob!.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
||||
return `embed.${view}.b.${h.toString(16).padStart(8, '0')}`;
|
||||
}
|
||||
|
||||
/** The parts of a state a reader edits; the rest (pane, view, step) is where they are looking. */
|
||||
/* `sync` is bookkeeping (which pane the others follow, which are stale), not something the reader wrote: a state whose texts are the problem's own is unedited whatever it says. A saved version does keep it (core/versions.ts), because restoring one must bring the links back as they were. */
|
||||
const EDITS = ['sources', 'input', 'call', 'setup', 'machine', 'build', 'mojoOrigin'] as const;
|
||||
|
||||
/** Whether `state` holds edits that `original` does not. */
|
||||
export function editedFrom(state: PlayState, original: PlayState): boolean {
|
||||
return EDITS.some((k) => JSON.stringify(state[k] ?? null) !== JSON.stringify(original[k] ?? null));
|
||||
}
|
||||
|
||||
/** Which fields count as the reader's edits, for code outside this file (saved versions add `sync`). */
|
||||
export const EDIT_FIELDS: readonly (typeof EDITS[number])[] = EDITS;
|
||||
|
||||
/** A short, stable name for the edits of a state (FNV-1a over EDITS), to tell when a catalog problem has changed under a save. */
|
||||
export function editsFingerprint(state: PlayState): string {
|
||||
const text = JSON.stringify(EDITS.map((k) => state[k] ?? null));
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
||||
return h.toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* What to open for a catalog problem, given its save. A save made against an older version of the
|
||||
* problem that holds no edits is dropped, so the reader sees the author's current version; a save
|
||||
* that holds edits is kept, and marked stale so the app can say the problem changed underneath it.
|
||||
*/
|
||||
export function resolveSaved(original: PlayState, saved: PlayState | null): { state: PlayState; stale: boolean } {
|
||||
if (!saved) return { state: original, stale: false };
|
||||
const changed = saved.base !== undefined && saved.base !== editsFingerprint(original);
|
||||
if (!changed) return { state: saved, stale: false };
|
||||
return saved.edited ? { state: saved, stale: true } : { state: original, stale: false };
|
||||
}
|
||||
|
||||
export function clearLocal(id: string): void {
|
||||
try { localStorage.removeItem(KEY(id)); } catch { /* ignore */ }
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* The two shared contracts every language service emits, and the service
|
||||
* interface the shell programs against. Nothing in `ui/` imports an engine
|
||||
* directly; it goes through these.
|
||||
*/
|
||||
|
||||
export type LangId = 'lingo' | 'matho' | 'pseudo' | 'speco' | 'mojo' | 'asm';
|
||||
|
||||
export type Severity = 'error' | 'warning' | 'note';
|
||||
|
||||
/** One finding, in the student's own line numbers for that language. */
|
||||
export interface Diagnostic {
|
||||
lang: LangId;
|
||||
severity: Severity;
|
||||
/** A stable id such as `range-ends`, `unset-read`, `invariant-keep`. */
|
||||
id: string;
|
||||
line: number;
|
||||
col?: number;
|
||||
message: string;
|
||||
/** Two or more readings of an ambiguous sentence; each is a one-click rewrite. */
|
||||
question?: { text: string; options: QuickFix[] };
|
||||
/** A single fix with no question attached (a casing fix, a missing closer). */
|
||||
fix?: QuickFix;
|
||||
/** Anchor into the pseudocode guide, e.g. `#for-stops-one-short`. */
|
||||
guide?: string;
|
||||
/** Who says so, when it is not Programming+'s own checker: "the Mojo 1.1.0 compiler". */
|
||||
origin?: string;
|
||||
/** A page that explains it (the Mojo manual, say), when `guide` does not apply. */
|
||||
docUrl?: string;
|
||||
}
|
||||
|
||||
export interface QuickFix {
|
||||
label: string;
|
||||
/** Replace this range of the source (1-based line, 1-based inclusive cols) with `text`. */
|
||||
line: number;
|
||||
/** A fix that spans lines replaces from `line`/`col` to `endLine`/`endCol`; absent, it stays on `line`. */
|
||||
endLine?: number;
|
||||
col: number;
|
||||
endCol: number | null;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** A recorded run: `states[t]` is the state before `steps[t]` runs. */
|
||||
export interface Trace<State = unknown, Step = unknown> {
|
||||
lang: LangId;
|
||||
steps: Step[];
|
||||
states: State[];
|
||||
count: number;
|
||||
output: string[];
|
||||
error: { kind: string; message: string; line?: number | null } | null;
|
||||
truncated: boolean;
|
||||
/** How often each source line ran. */
|
||||
hits: Map<number, number>;
|
||||
/** The language's own trace object, for views that know the language. */
|
||||
raw: unknown;
|
||||
}
|
||||
|
||||
export interface Frame<State = unknown, Step = unknown> {
|
||||
t: number;
|
||||
state: State;
|
||||
last: Step | null;
|
||||
next: Step | null;
|
||||
}
|
||||
|
||||
export function frameAt<S, P>(trace: Trace<S, P>, t: number): Frame<S, P> {
|
||||
const c = Math.max(0, Math.min(t, trace.count));
|
||||
return { t: c, state: trace.states[c], last: c > 0 ? trace.steps[c - 1] : null, next: c < trace.count ? trace.steps[c] : null };
|
||||
}
|
||||
|
||||
/** A line map from one language's source to another's. */
|
||||
export type LineMap = Array<{ from: number; to: number }>;
|
||||
|
||||
export interface Lowered {
|
||||
target: LangId;
|
||||
source: string;
|
||||
map: LineMap;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
export interface Obligation {
|
||||
kind: string;
|
||||
label: string;
|
||||
line: number;
|
||||
col?: number;
|
||||
status: 'proved' | 'broken' | 'open';
|
||||
paths: number;
|
||||
facts: string[];
|
||||
goal: string;
|
||||
reason?: string;
|
||||
counterexample?: string;
|
||||
}
|
||||
|
||||
export interface ProofReport {
|
||||
units: Array<{ name: string; kind: string; line: number; obligations: Obligation[]; inferred: string[]; notes: string[]; partial: boolean }>;
|
||||
counts: { proved: number; broken: number; open: number; total: number };
|
||||
}
|
||||
|
||||
export interface PropertyReport {
|
||||
name: string;
|
||||
checked: number;
|
||||
failures: Array<{ call: string; message: string; line?: number; kind: string }>;
|
||||
problem?: string;
|
||||
}
|
||||
|
||||
/** What a parse hands back: an opaque program plus diagnostics. */
|
||||
export interface Parsed<Program = unknown> {
|
||||
program: Program | null;
|
||||
diagnostics: Diagnostic[];
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
/** A call such as `COUNT_BASE('A', "GATTACA")`, for programs with no main body. */
|
||||
call?: string | null;
|
||||
input?: string[];
|
||||
maxSteps?: number;
|
||||
/** Assembly: register and memory setup lines, in the sandbox's syntax. */
|
||||
setup?: string;
|
||||
machine?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The language-service interface. Methods a language does not support are
|
||||
* simply absent, and the shell hides the matching view.
|
||||
*/
|
||||
export interface LanguageService<Program = unknown, State = unknown, Step = unknown> {
|
||||
id: LangId;
|
||||
name: string;
|
||||
parse(source: string): Parsed<Program>;
|
||||
run?(parsed: Parsed<Program>, options: RunOptions): Trace<State, Step>;
|
||||
lower?(parsed: Parsed<Program>, target: LangId): Lowered | null;
|
||||
prove?(parsed: Parsed<Program>): ProofReport;
|
||||
checkProperties?(parsed: Parsed<Program>, name?: string): PropertyReport[];
|
||||
/** A default call for `run`, when the program has subroutines and no main body. */
|
||||
defaultCall?(parsed: Parsed<Program>): string | null;
|
||||
/** Highlight classes per token, for the editor. */
|
||||
tokenize?(line: string): Array<{ text: string; cls: string }>;
|
||||
/** The whole document at once, one token list per line, for languages whose strings span lines. */
|
||||
tokenizeLines?(source: string): Array<Array<{ text: string; cls: string }>>;
|
||||
}
|
||||
|
||||
export type ViewId = 'problems' | 'trace' | 'proof' | 'tests' | 'asm' | 'flow' | 'data' | 'table' | 'compiler' | 'life';
|
||||
|
||||
export const LANG_NAMES: Record<LangId, string> = {
|
||||
lingo: 'lingo', matho: 'matho', pseudo: 'pseudo', speco: 'speco', mojo: 'Mojo', asm: 'x86-64',
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Saved versions (restructure plan, section 2.7): a student can save the state of their work under a name and
|
||||
* come back to any saved version. DOM-free; the storage is a parameter (localStorage when there is one), so the
|
||||
* tests run it against a fake.
|
||||
*
|
||||
* A version holds what the student edits: every source, the link bookkeeping (`sync`), where the Mojo came from,
|
||||
* the call, the input, the assembly setup and machine, the build level. It also records the area it was saved in,
|
||||
* a name, and a time. It does not hold the layout, the step, or the open tab: those are where the student is
|
||||
* looking, not what they made, so restoring a version never moves them.
|
||||
*
|
||||
* One list per piece of work: `pplus.versions.<problemId>` for a catalog problem, and
|
||||
* `pplus.versions.ws.<workspaceId>` for work that began from a share link or a file.
|
||||
*/
|
||||
import { editedFrom, EDIT_FIELDS, normalize, type PlayState } from './state.js';
|
||||
import { isAreaId, type AreaId } from './areas.js';
|
||||
|
||||
/** The most versions one piece of work keeps. */
|
||||
export const MAX_VERSIONS = 50;
|
||||
/** Characters of localStorage in use above which the drop-down says the browser is nearly full (most browsers hold about 5 million). */
|
||||
export const PRESSURE_CHARS = 4_000_000;
|
||||
|
||||
const FIELDS = [...EDIT_FIELDS, 'sync'] as const;
|
||||
export type VersionEdits = Partial<Pick<PlayState, typeof FIELDS[number]>>;
|
||||
|
||||
export interface Version {
|
||||
id: string;
|
||||
name: string;
|
||||
at: number;
|
||||
area: AreaId;
|
||||
/** Saved by Programming+ before a switch or a reset, not by the student. */
|
||||
auto?: boolean;
|
||||
edits: VersionEdits;
|
||||
}
|
||||
|
||||
export interface Store { getItem(k: string): string | null; setItem(k: string, v: string): void; removeItem(k: string): void; key?(i: number): string | null; readonly length?: number }
|
||||
|
||||
const defaultStore = (): Store | null => { try { return typeof localStorage === 'undefined' ? null : localStorage; } catch { return null; } };
|
||||
|
||||
/** The list a piece of work keeps its versions in, or null while it has neither a problem nor a workspace. */
|
||||
export function versionKey(state: Pick<PlayState, 'problem' | 'workspace'>): string | null {
|
||||
if (state.problem) return `pplus.versions.${state.problem}`;
|
||||
if (state.workspace) return `pplus.versions.ws.${state.workspace}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A name for work that has none yet. Random, short, and safe in a key. */
|
||||
export function newWorkspaceId(): string {
|
||||
const bytes = new Uint8Array(8);
|
||||
if (typeof crypto !== 'undefined' && crypto.getRandomValues) crypto.getRandomValues(bytes); else for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256);
|
||||
return 'w' + [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
/** The edited fields of a state, and only those. */
|
||||
export function editsOf(state: PlayState): VersionEdits {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const k of FIELDS) if (state[k] !== undefined) out[k] = structuredClone(state[k]);
|
||||
return out as VersionEdits;
|
||||
}
|
||||
|
||||
/** A short, stable name for a state's edits (FNV-1a), `sync` included: two states with the same fingerprint restore to the same work. */
|
||||
export function versionFingerprint(edits: VersionEdits | PlayState): string {
|
||||
const text = canon(FIELDS.map((k) => (edits as Record<string, unknown>)[k] ?? null));
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
|
||||
return h.toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
/** JSON with the keys in order, so the same edits read back from storage or a file name the same version. */
|
||||
function canon(x: unknown): string {
|
||||
if (Array.isArray(x)) return `[${x.map(canon).join(',')}]`;
|
||||
if (x && typeof x === 'object') return `{${Object.keys(x).sort().filter((k) => (x as Record<string, unknown>)[k] !== undefined).map((k) => `${JSON.stringify(k)}:${canon((x as Record<string, unknown>)[k])}`).join(',')}}`;
|
||||
return JSON.stringify(x) ?? 'null';
|
||||
}
|
||||
|
||||
function readList(key: string, store: Store | null): Version[] {
|
||||
if (!store) return memoryLists.get(key) ?? [];
|
||||
try {
|
||||
const raw = store.getItem(key);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed) ? parsed.map(cleanVersion).filter((v): v is Version => !!v) : [];
|
||||
} catch { return []; }
|
||||
}
|
||||
/** A browser with no storage still keeps versions for the tab. */
|
||||
const memoryLists = new Map<string, Version[]>();
|
||||
|
||||
/** A version read back from storage or a file: only what is well formed; the edits go through `normalize`, so a damaged one cannot smuggle anything in. */
|
||||
export function cleanVersion(v: any): Version | null {
|
||||
if (!v || typeof v !== 'object' || typeof v.id !== 'string' || !/^[A-Za-z0-9_-]{1,40}$/.test(v.id) || typeof v.name !== 'string' || typeof v.at !== 'number' || !isAreaId(v.area)) return null;
|
||||
const n = normalize({ v: 3, ...(v.edits && typeof v.edits === 'object' ? v.edits : {}) });
|
||||
return { id: v.id, name: v.name.slice(0, 120), at: v.at, area: v.area, ...(v.auto ? { auto: true } : {}), edits: editsOf(n) };
|
||||
}
|
||||
|
||||
function writeList(key: string, list: Version[], store: Store | null): boolean {
|
||||
if (!store) { memoryLists.set(key, list); return true; }
|
||||
try { store.setItem(key, JSON.stringify(list)); return true; } catch { return false; }
|
||||
}
|
||||
|
||||
/** Saved versions, newest first. */
|
||||
export function listVersions(key: string | null, store: Store | null = defaultStore()): Version[] {
|
||||
if (!key) return [];
|
||||
return readList(key, store).slice().sort((a, b) => b.at - a.at);
|
||||
}
|
||||
|
||||
export type SaveResult = { ok: true; version: Version; dropped: Version[] } | { ok: false; reason: 'cap' | 'storage' | 'no-key' };
|
||||
|
||||
let counter = 0;
|
||||
const newId = (at: number): string => `v${at.toString(36)}${(counter++ % 1296).toString(36)}${Math.floor(Math.random() * 1296).toString(36)}`;
|
||||
|
||||
/**
|
||||
* Save the state's edits as a version. When the list is full, the oldest automatic versions go first; if only
|
||||
* named ones are left it refuses rather than delete something the student named.
|
||||
*/
|
||||
export function saveVersion(key: string | null, name: string, state: PlayState, area: AreaId, opts: { auto?: boolean; now?: number; store?: Store | null } = {}): SaveResult {
|
||||
if (!key) return { ok: false, reason: 'no-key' };
|
||||
const store = opts.store === undefined ? defaultStore() : opts.store;
|
||||
const at = opts.now ?? Date.now();
|
||||
let list = readList(key, store).slice().sort((a, b) => b.at - a.at);
|
||||
const dropped: Version[] = [];
|
||||
while (list.length >= MAX_VERSIONS) {
|
||||
const oldestAuto = [...list].reverse().find((v) => v.auto);
|
||||
if (!oldestAuto) return { ok: false, reason: 'cap' };
|
||||
list = list.filter((v) => v !== oldestAuto); dropped.push(oldestAuto);
|
||||
}
|
||||
const version: Version = { id: newId(at), name: name.trim() || 'Untitled version', at, area, ...(opts.auto ? { auto: true } : {}), edits: editsOf(state) };
|
||||
list.unshift(version);
|
||||
return writeList(key, list, store) ? { ok: true, version, dropped } : { ok: false, reason: 'storage' };
|
||||
}
|
||||
|
||||
export function renameVersion(key: string | null, id: string, name: string, store: Store | null = defaultStore()): boolean {
|
||||
if (!key || !name.trim()) return false;
|
||||
const list = readList(key, store);
|
||||
const v = list.find((x) => x.id === id);
|
||||
if (!v) return false;
|
||||
v.name = name.trim().slice(0, 120);
|
||||
delete v.auto; // a version the student named is theirs: it is no longer the first to go
|
||||
return writeList(key, list, store);
|
||||
}
|
||||
|
||||
export function deleteVersion(key: string | null, id: string, store: Store | null = defaultStore()): boolean {
|
||||
if (!key) return false;
|
||||
const list = readList(key, store);
|
||||
const rest = list.filter((x) => x.id !== id);
|
||||
if (rest.length === list.length) return false;
|
||||
if (!rest.length) { if (store) { try { store.removeItem(key); } catch { /* ignore */ } } else memoryLists.delete(key); return true; }
|
||||
return writeList(key, rest, store);
|
||||
}
|
||||
|
||||
/**
|
||||
* The state with a version's edits put in place of the current ones. Everything else (the layout, the step, the
|
||||
* open tab and view, the title, the problem) is the current state's own, so restoring changes the work and not where
|
||||
* the student is looking. A field the version does not have is removed, not left over from the work being replaced.
|
||||
*/
|
||||
export function restoreVersion(key: string | null, id: string, current: PlayState, store: Store | null = defaultStore()): PlayState | null {
|
||||
const v = listVersions(key, store).find((x) => x.id === id);
|
||||
if (!v) return null;
|
||||
const next: PlayState = structuredClone(current);
|
||||
for (const k of FIELDS) delete (next as unknown as Record<string, unknown>)[k];
|
||||
Object.assign(next, structuredClone(v.edits));
|
||||
if (!next.sources) next.sources = {};
|
||||
delete next.edited; delete next.base;
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the work has edits that no saved version holds. For a catalog problem, work that is the problem as
|
||||
* written has none to lose (pass the problem's own state as `original`).
|
||||
*/
|
||||
export function hasUnsavedEdits(key: string | null, state: PlayState, original?: PlayState | null, store: Store | null = defaultStore()): boolean {
|
||||
if (original && !editedFrom(state, original)) return false;
|
||||
if (!original && !Object.values(state.sources).some((t) => (t ?? '').trim())) return false;
|
||||
const fp = versionFingerprint(state);
|
||||
return !listVersions(key, store).some((v) => versionFingerprint(v.edits) === fp);
|
||||
}
|
||||
|
||||
/** Which saved version, if any, the current work is exactly. */
|
||||
export function currentVersion(key: string | null, state: PlayState, store: Store | null = defaultStore()): Version | null {
|
||||
const fp = versionFingerprint(state);
|
||||
return listVersions(key, store).find((v) => versionFingerprint(v.edits) === fp) ?? null;
|
||||
}
|
||||
|
||||
/** How full the browser's storage is, as a guess: characters held across every key against what browsers usually allow. */
|
||||
export function storagePressure(store: Store | null = defaultStore()): { used: number; nearlyFull: boolean } {
|
||||
let used = 0;
|
||||
try {
|
||||
const n = store?.length ?? 0;
|
||||
for (let i = 0; i < n; i++) { const k = store!.key?.(i); if (k != null) used += k.length + (store!.getItem(k)?.length ?? 0); }
|
||||
} catch { /* unreadable: say nothing */ }
|
||||
return { used, nearlyFull: used >= PRESSURE_CHARS };
|
||||
}
|
||||
|
||||
/** The versions for a file: every well-formed one in the list. */
|
||||
export function exportVersions(key: string | null, store: Store | null = defaultStore()): Version[] { return listVersions(key, store); }
|
||||
|
||||
/**
|
||||
* Put versions from a file into a list: one with an id the list already has is left as it is (an import never
|
||||
* overwrites), and the cap holds (the oldest automatic ones make room; otherwise the rest are not added).
|
||||
*/
|
||||
export function importVersions(key: string | null, incoming: unknown, store: Store | null = defaultStore()): { added: number; skipped: number } {
|
||||
if (!key || !Array.isArray(incoming)) return { added: 0, skipped: Array.isArray(incoming) ? incoming.length : 0 };
|
||||
let list = readList(key, store);
|
||||
let added = 0, skipped = 0;
|
||||
for (const raw of incoming) {
|
||||
const v = cleanVersion(raw);
|
||||
if (!v || list.some((x) => x.id === v.id)) { skipped++; continue; }
|
||||
if (list.length >= MAX_VERSIONS) {
|
||||
const oldestAuto = [...list].sort((a, b) => a.at - b.at).find((x) => x.auto);
|
||||
if (!oldestAuto) { skipped++; continue; }
|
||||
list = list.filter((x) => x !== oldestAuto);
|
||||
}
|
||||
list.push(v); added++;
|
||||
}
|
||||
if (added) writeList(key, list, store);
|
||||
return { added, skipped };
|
||||
}
|
||||
|
||||
/** The name of an automatic version: "Before switching (3:42 PM)". */
|
||||
export function autoName(why: 'switching' | 'reset' | 'new', at = Date.now()): string {
|
||||
const t = new Date(at).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
|
||||
return why === 'new' ? 'My edits, before the problem changed' : `Before ${why === 'reset' ? 'reset' : 'switching'} (${t})`;
|
||||
}
|
||||
Reference in new issue
Block a user