// Test benches: a part with a table of tests. Its drive columns are output // pins it sets, its check columns input pins it reads; wire them to whatever // is tested. Each row sets the drive columns, gives the circuit clock ticks // if asked, and checks what comes back. A run takes the whole circuit the // bench is in on its own, from all zeros (switches as they are), so it never // disturbs the circuit running; what the circuit holds carries from row to // row, so a row can test memory, a counter, or a computer running a program. // // A drive cell is a number (12, 0x0C, 0b1100), P for a clock pulse, or empty // to leave it as it was. A check cell is the number it should read, empty // for any. Ticks: N pulses (the P columns and the circuit's own clocks) // before the check; ≤N gives up to N, checking after each, until it matches. import { compile, rowSource } from './compile' import { colKeys, colPinNames } from './benchLayout' import { chipPins, type DefLookup } from './geometry' import { uid } from './ops' import { Simulator } from './sim' import type { Bench, BenchCol, BenchRow, CircuitNode, ComponentDef } from './types' export interface RowResult { /** True all checks hold, false one does not, null nothing to check. */ ok: boolean | null /** What the check columns read after the row, by column id. */ got: Record /** Ticks the row ran. */ ticks: number error?: string } export interface BenchResult { rows: RowResult[] pass: number fail: number error?: string } const SETTLE = 2_000_000 /** Ticks a run gives in all, at most (a run after an edit stays short; by hand it may go longer). */ export const AUTO_TICKS = 20_000 export const HAND_TICKS = 500_000 /** "Every combination" makes rows for this many drive bits at most. */ export const MAX_COMBO_BITS = 10 export { colKeys, colPinNames } export const driveCols = (b: Bench | undefined) => (b?.cols ?? []).filter(c => c.dir === 'drive') export const checkCols = (b: Bench | undefined) => (b?.cols ?? []).filter(c => c.dir === 'check') /** A cell as a number, P (drive columns only), or null when empty or a don't-care. */ export function parseCell(s: string | undefined, bits: number, drive: boolean): number | 'P' | null | { error: string } { const t = (s ?? '').trim() if (!t || t === '-' || t.toLowerCase() === 'x') return null if (drive && /^(p|↑)$/i.test(t)) return 'P' let v: number if (/^\d+$/.test(t)) v = parseInt(t, 10) else if (/^0x[0-9a-f]+$/i.test(t)) v = parseInt(t.slice(2), 16) else if (/^0b[01]+$/i.test(t)) v = parseInt(t.slice(2), 2) else if (/^-\d+$/.test(t)) v = 2 ** bits + parseInt(t, 10) else return { error: `"${t}" is not a number${drive ? ' or P' : ''}` } if (v < 0 || v >= 2 ** bits) return { error: `${t} does not fit in ${bits} bit${bits === 1 ? '' : 's'}` } return v } /** Ticks of a row: N, or ≤N (also <=N) to wait for the checks. Empty: one pulse when the row has a P, else none. */ export function parseTicks(s: string | undefined): { n: number; wait: boolean } | null | { error: string } { const t = (s ?? '').trim() if (!t) return null const m = /^(≤|<=|<|max\s*|up\s*to\s*)?\s*(\d+)$/i.exec(t) if (!m) return { error: `Ticks "${t}": a number, or ≤ and a number` } const n = parseInt(m[2]!, 10) if (n > HAND_TICKS) return { error: `Ticks: at most ${HAND_TICKS}` } return { n, wait: !!m[1] } } /** Sets the circuit's own switches the way they stand (buttons up, keyboards empty). */ export function setSwitches(sim: Simulator, def: ComponentDef) { for (const n of def.nodes) { if (n.kind === 'input') sim.setSource(n.id, !!n.on) else if (n.kind === 'panel') for (const r of n.rows ?? []) if (r.type === 'switch') sim.setSource(rowSource(n.id, r.id), !!r.on) } } /** Runs a bench's rows on the circuit it is in. */ export function runBench(getDef: DefLookup, circuitId: string, benchId: string, maxTicks = AUTO_TICKS): BenchResult { const def = getDef(circuitId) const bench = def?.nodes.find(n => n.id === benchId)?.bench const res: BenchResult = { rows: [], pass: 0, fail: 0 } if (!def || !bench) return { ...res, error: 'The bench is gone' } const drives = driveCols(bench) const checks = checkCols(bench) if (!drives.length && !checks.length) return { ...res, error: 'No columns yet' } const sim = new Simulator(compile(getDef, circuitId)) setSwitches(sim, def) sim.run(SETTLE) const clocks = sim.nl.clocks.length > 0 let left = maxTicks const put = (c: BenchCol, v: number) => colKeys(c).forEach((k, i) => sim.setSource(`${benchId}:${k}`, Math.floor(v / 2 ** i) % 2 === 1)) const read = (c: BenchCol) => colKeys(c).reduce((v, k, i) => v + (sim.pin(benchId, k) ? 2 ** i : 0), 0) for (const row of bench.rows) { const out: RowResult = { ok: null, got: {}, ticks: 0 } res.rows.push(out) const fail = (error: string) => { out.ok = false out.error = error res.fail++ } // Drive columns; pulses held low for now. const pulses: BenchCol[] = [] let bad = '' for (const c of drives) { const v = parseCell(row.set?.[c.id], c.bits, true) if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}` else if (v === 'P') { pulses.push(c) put(c, 0) } else if (v !== null) put(c, v) } const want: { c: BenchCol; v: number }[] = [] for (const c of checks) { const v = parseCell(row.expect?.[c.id], c.bits, false) if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}` else if (typeof v === 'number') want.push({ c, v }) } const ticks = parseTicks(row.ticks) if (ticks && 'error' in ticks) bad ||= ticks.error if (bad) { fail(bad) continue } const spec = (ticks as { n: number; wait: boolean } | null) ?? { n: pulses.length ? 1 : 0, wait: false } if (spec.n && !pulses.length && !clocks) { fail('Ticks, but nothing to tick: a column with P, or a clock in the circuit') continue } if (!sim.run(SETTLE)) { fail('It oscillates and never settles') continue } const matches = () => want.every(({ c, v }) => read(c) === v) const tick = (): boolean => { for (const c of pulses) put(c, 2 ** c.bits - 1) if (clocks) sim.setClock(1) if (!sim.run(SETTLE)) return false for (const c of pulses) put(c, 0) if (clocks) sim.setClock(0) return sim.run(SETTLE) } let stopped = '' for (let t = 0; t < spec.n; t++) { if (spec.wait && want.length && matches()) break if (left-- <= 0) { stopped = `Stopped after ${maxTicks.toLocaleString('en')} ticks in all` break } if (!tick()) { stopped = 'It oscillates and never settles' break } out.ticks++ } for (const c of checks) out.got[c.id] = read(c) if (stopped) { fail(stopped) if (left <= 0) { res.error = stopped break } continue } if (!want.length) continue out.ok = matches() if (out.ok) res.pass++ else { res.fail++ if (spec.wait) out.error = `Not within ${spec.n} ticks` } } return res } /** Every combination of the drive columns, counting up (the first column the highest). */ export function combinationRows(bench: Bench): BenchRow[] | { error: string } { const drives = driveCols(bench) const bits = drives.reduce((n, c) => n + c.bits, 0) if (!drives.length) return { error: 'Add a drive column first' } if (bits > MAX_COMBO_BITS) return { error: `${bits} drive bits are ${2 ** bits} combinations: at most ${MAX_COMBO_BITS} bits` } const rows: BenchRow[] = [] for (let i = 0; i < 2 ** bits; i++) { let rest = i const set: Record = {} for (let k = drives.length - 1; k >= 0; k--) { const c = drives[k]! set[c.id] = String(rest % 2 ** c.bits) rest = Math.floor(rest / 2 ** c.bits) } rows.push({ set }) } return rows } /** * The rows with what the circuit reads now in their empty check cells (to * keep it working the same). Cells already filled in stay, so a row that * waits for them waits the same. */ export function recordExpected(r: BenchResult, rows: BenchRow[]): BenchRow[] { return rows.map((row, i) => { const res = r.rows[i] if (!res || (res.error && res.ok !== false)) return row const expect = { ...row.expect } for (const [k, v] of Object.entries(res.got)) if (!expect[k]?.trim()) expect[k] = String(v) return { ...row, expect } }) } // ── Columns for a component ────────────────────────────────────────── const SERIES = /^(.*?)(\d+)$/ /** Pins as groups: A0…An (numbered from 0, none missing) make one group A; any other pin is its own. Keys bit 0 first. */ export function groupPins(pins: { key: string; label: string }[]): { name: string; keys: string[] }[] { const series = new Map>() for (const p of pins) { const m = SERIES.exec(p.label.trim()) if (!m || !m[1]) continue const s = series.get(m[1]) ?? new Map() s.set(Number(m[2]), p.key) series.set(m[1], s) } const whole = new Set([...series.entries()].filter(([, s]) => s.size >= 2 && [...s.keys()].every(i => i < s.size)).map(([name]) => name)) const out: { name: string; keys: string[] }[] = [] const done = new Set() for (const p of pins) { const name = SERIES.exec(p.label.trim())?.[1] if (name && whole.has(name)) { if (done.has(name)) continue done.add(name) const s = series.get(name)! out.push({ name, keys: [...s.keys()].sort((a, b) => a - b).map(i => s.get(i)!) }) } else out.push({ name: p.label.trim() || p.key, keys: [p.key] }) } return out } /** * Sets a bench up for a placed component: a drive column per input group, a * check column per output group, wired to them (inputs already wired from * elsewhere stay as they are). Rows keyed by group name are moved to the * new columns. Returns the wires to add. */ export function benchFor(def: ComponentDef, bench: CircuitNode, chip: CircuitNode, chipDef: ComponentDef): { from: { node: string; pin: string }; to: { node: string; pin: string } }[] { const pins = chipPins(chipDef) const ins = groupPins(pins.inputs) const outs = groupPins(pins.outputs) const cols: BenchCol[] = [ ...ins.map(g => ({ id: uid('c'), name: g.name, bits: g.keys.length, dir: 'drive' as const })), ...outs.map(g => ({ id: uid('c'), name: g.name, bits: g.keys.length, dir: 'check' as const })), ] const byName = new Map(cols.map(c => [`${c.dir}:${c.name}`, c.id])) const remap = (cells: Record | undefined, dir: BenchCol['dir']) => { if (!cells) return undefined const out = Object.fromEntries(Object.entries(cells).map(([k, v]) => [byName.get(`${dir}:${k}`) ?? k, v])) return Object.keys(out).length ? out : undefined } const rows = (bench.bench?.rows ?? []).map(r => { const set = remap(r.set, 'drive') const expect = remap(r.expect, 'check') return { ...(set ? { set } : {}), ...(expect ? { expect } : {}), ...(r.ticks ? { ticks: r.ticks } : {}) } }) bench.bench = { cols, rows } const fed = new Set(def.wires.filter(w => w.to.node === chip.id).map(w => w.to.pin)) const wires: { from: { node: string; pin: string }; to: { node: string; pin: string } }[] = [] ins.forEach((g, gi) => { const keys = colKeys(cols[gi]!) g.keys.forEach((k, i) => !fed.has(k) && wires.push({ from: { node: bench.id, pin: keys[i]! }, to: { node: chip.id, pin: k } })) }) outs.forEach((g, gi) => { const keys = colKeys(cols[ins.length + gi]!) g.keys.forEach((k, i) => wires.push({ from: { node: chip.id, pin: k }, to: { node: bench.id, pin: keys[i]! } })) }) return wires } /** Benches saved by the first version (docked to a component, no pins): columns and wires to that component instead. */ export function upgradeBenches(def: ComponentDef, getDef: DefLookup) { for (const n of def.nodes) { const on = n.kind === 'bench' ? n.bench?.on : undefined if (!n.bench || n.bench.cols || !on) { if (n.bench?.on) delete n.bench.on continue } const chip = def.nodes.find(x => x.id === on) const chipDef = chip?.kind === 'chip' && chip.chip ? getDef(chip.chip) : undefined if (!chip || !chipDef) { n.bench = { cols: [], rows: [] } continue } for (const w of benchFor(def, n, chip, chipDef)) def.wires.push({ id: uid('w'), ...w }) } }