diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index 3893c71..ff3fd4e 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -6085,31 +6085,28 @@ button.tile:hover {
/* Test bench */
.node .bench-body {
- fill: #141c24;
+ fill: #121921;
stroke: #3b4554;
- stroke-dasharray: 4 3;
}
.node .bench-body.pass {
stroke: var(--on);
- stroke-dasharray: none;
}
.node .bench-body.fail {
stroke: var(--danger);
- stroke-dasharray: none;
}
.node .bench-title {
fill: var(--text);
font-size: 10px;
- font-weight: 600;
+ font-weight: 700;
pointer-events: none;
}
.node .bench-line {
fill: var(--muted);
- font-size: 10px;
+ font-size: 9.5px;
pointer-events: none;
}
@@ -6121,6 +6118,117 @@ button.tile:hover {
fill: var(--danger);
}
+.node .bench-run circle {
+ fill: #1d3a2a;
+ stroke: var(--on);
+ cursor: pointer;
+}
+
+.node .bench-run path {
+ fill: var(--on);
+ pointer-events: none;
+}
+
+.node .bench-run:hover circle {
+ fill: #25553a;
+}
+
+.node .bench-head {
+ fill: var(--muted);
+ font-family: var(--font-mono);
+ font-size: 9.5px;
+ font-weight: 600;
+ pointer-events: none;
+}
+
+.node .bench-head.drive {
+ fill: #9fb3c8;
+}
+
+.node .bench-row {
+ cursor: pointer;
+}
+
+.node .bench-row-bg {
+ fill: transparent;
+}
+
+.node .bench-row:hover .bench-row-bg {
+ fill: rgb(255 255 255 / 0.05);
+}
+
+.node .bench-row.fail .bench-row-bg {
+ fill: rgb(255 90 80 / 0.22);
+}
+
+.node .bench-row.pass .bench-row-bg {
+ fill: rgb(61 220 132 / 0.07);
+}
+
+.node .bench-row.live .bench-row-bg {
+ stroke: var(--accent);
+ stroke-width: 1;
+}
+
+.node .bench-cell-text {
+ fill: var(--text);
+ font-family: var(--font-mono);
+ font-size: 10px;
+ white-space: pre;
+ pointer-events: none;
+}
+
+.node .bench-cell-text.num,
+.node .bench-cell-text.got {
+ fill: #5d6a7c;
+}
+
+.node .bench-cell-text.wrong,
+.node .bench-cell-text.fail {
+ fill: #ff8a80;
+ font-weight: 700;
+}
+
+.node .bench-cell-text.pass {
+ fill: var(--on);
+}
+
+.bench-cols {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.bench-col {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--muted);
+}
+
+.bench-col .field-input {
+ width: 140px;
+ padding: 3px 6px;
+}
+
+.bench-col .bench-bits {
+ width: 56px;
+}
+
+.bench-col-dir {
+ width: 44px;
+ font-weight: 600;
+}
+
+.bench-col.drive .bench-col-dir {
+ color: #9fb3c8;
+}
+
+.bench-col.check .bench-col-dir {
+ color: var(--on);
+}
+
.modal.bench {
width: min(1100px, 100%);
}
@@ -6139,14 +6247,6 @@ button.tile:hover {
margin: 10px 0 8px;
}
-.bench-target {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 13px;
- font-weight: 600;
-}
-
.bench-summary {
margin-bottom: 6px;
font-size: 13px;
diff --git a/app/components/editor/BenchDialog.vue b/app/components/editor/BenchDialog.vue
index 402942a..1f9185d 100644
--- a/app/components/editor/BenchDialog.vue
+++ b/app/components/editor/BenchDialog.vue
@@ -1,24 +1,20 @@
@@ -88,77 +105,87 @@ function gotNote(i: number, name: string): string {
-
Tests
+ {{ node?.label?.trim() || 'Test bench' }}
- Each row sets the inputs, gives it ticks, then checks the outputs. It runs on its own from all zeros; what it holds carries to the next row.
- Inputs: a number (12, 0x0C, 0b1100), P for a clock pulse, empty to leave it. Outputs: what it should show, empty for any.
- Ticks: 5 pulses (the P inputs and its own clocks), or ≤1000 to wait until the outputs are right.
+ Wire its pins to what you test: drive columns are its outputs (on the right of its box), check columns its inputs (on the left).
+ Each row sets the drive columns, gives ticks, then checks. A run takes this circuit on its own from all zeros; what it holds carries to the next row.
+ Drive: a number (12, 0x0C, 0b1100), P for a clock pulse, empty to leave it. Check: what it should read, empty for any.
+ Ticks: 5 pulses (P columns and the circuit's clocks), or ≤1000 to wait until the checks hold. Click a row on the box to put it on the running circuit.
-
-
- Tests
-
- nothing yet
- {{ c.name }}
-
-
-
-
Every combination
-
Take what it does
-
Run
+
Columns
+
-
Pick the component it tests above, or drop the bench on one.
-
+ Rows
+
{{ result.error }}.
{{ result.fail }} failing, {{ result.pass }} pass
All {{ result.pass }} pass
- Nothing checked yet
-
-
Row
-
+
+
Every combination
+
Take what it does
+
Run
+
+
+ Add columns first, or drop the bench on a component to get one for each of its pins.
+ Row
diff --git a/app/components/editor/Canvas.vue b/app/components/editor/Canvas.vue
index b0273c8..0891c4c 100644
--- a/app/components/editor/Canvas.vue
+++ b/app/components/editor/Canvas.vue
@@ -660,6 +660,8 @@ type Drag =
node: CircuitNode
toggle: boolean
row?: PanelRow
+ /** On a test bench: its run button, or one of its rows (a click puts it on the circuit). */
+ benchHit?: 'run' | number
/** How many parts were picked up (followers not counted): one part may snap to a pin a square away. */
grabbed: number
/** Pins of the parts staying put, and of the moving parts where they started; filled once the drag moves. */
@@ -840,6 +842,7 @@ function onPointerDown(e: PointerEvent) {
node,
toggle: (node.kind === 'input' || node.kind === 'keyboard' || !!row) && !multi,
row,
+ benchHit: benchHitAt(target, node, multi),
grabbed: selected.value.has(id) ? ed.selection.value.length : 1,
}
return
@@ -1172,7 +1175,9 @@ function onPointerUp(e: PointerEvent) {
} else if (d.moved) {
ed.unplugMoved(new Set(d.orig.nodes.keys()))
if (d.node.kind !== 'bench' || !ed.dropBench(d.node)) ed.commit(false)
- } else if (d.toggle && d.row) ed.toggleRow(d.node, d.row)
+ } else if (d.benchHit === 'run') ed.runBenchNow(d.node.id, true)
+ else if (typeof d.benchHit === 'number') ed.applyBenchRow(d.node.id, d.benchHit)
+ else if (d.toggle && d.row) ed.toggleRow(d.node, d.row)
else if (d.toggle && d.node.kind === 'keyboard') ed.typeInto(d.node.id)
else if (d.toggle) ed.toggleInput(d.node)
break
@@ -1245,6 +1250,14 @@ function onPointerUp(e: PointerEvent) {
}
}
+/** What a press on a test bench's box hits: its run button or a row. */
+function benchHitAt(target: Element, node: CircuitNode, multi: boolean): 'run' | number | undefined {
+ if (node.kind !== 'bench' || multi) return undefined
+ if (target.closest('[data-bench-run]')) return 'run'
+ const row = target.closest('[data-bench-row]')?.getAttribute('data-bench-row')
+ return row ? Number(row) : undefined
+}
+
function onDoubleClick(node: CircuitNode) {
if (node.kind === 'chip' && node.chip) ed.open(node.chip)
else if (node.kind === 'bench') ed.benchOpen.value = node.id
diff --git a/app/components/editor/NodeView.vue b/app/components/editor/NodeView.vue
index eb0d3e7..d50f757 100644
--- a/app/components/editor/NodeView.vue
+++ b/app/components/editor/NodeView.vue
@@ -3,6 +3,7 @@ import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, rgbHex, shapeTransform, type Shape } from '~/lib/logic/geometry'
+import { benchLayout } from '~/lib/logic/benchLayout'
import { keyLabel, TERMINAL_COLS, TERMINAL_LINES } from '~/lib/logic/devices'
import type { CircuitNode } from '~/lib/logic/types'
@@ -172,19 +173,44 @@ const faceHex = (inner: string) => sevenSegment([0, 1, 2, 3].reduce((n, i) => n
/** The colour of an RGB pixel inside this chip ('' while off). */
const facePx = (inner: string) => rgbHex(fv(inner, 'r'), fv(inner, 'g'), fv(inner, 'b'))
const rgbNow = computed(() => (props.node.rgb ? rgbHex(v('r'), v('g'), v('b')) : ''))
-// Test bench: its target and the last run.
-const benchSum = computed(() => {
- if (props.node.kind !== 'bench') return { title: '', line: '', state: '' }
- const target = ed.benchTarget(props.node)
- const title = target ? `Tests: ${target.def.name}` : 'Test bench'
- const rows = props.node.bench?.rows.length ?? 0
- const r = props.ghost ? undefined : ed.benchResults.value.get(props.node.id)
- if (!target) return { title, line: 'drop on a component', state: 'idle' }
- if (!rows) return { title, line: 'no tests yet: double-click', state: 'idle' }
- if (!r) return { title, line: `${rows} tests`, state: 'idle' }
- if (r.error && !r.fail) return { title, line: r.error, state: 'fail' }
- if (r.fail) return { title, line: `✗ ${r.fail} failing, ${r.pass} pass`, state: 'fail' }
- return { title, line: r.pass ? `✓ all ${r.pass} pass` : `${rows} rows, nothing checked`, state: r.pass ? 'pass' : 'idle' }
+// Test bench: the layout of its box, its rows and how they went.
+interface BenchRowView {
+ i: number
+ state: string
+ live: boolean
+ cells: { key: string; x: number; text: string; cls: string }[]
+ title: string
+}
+const bl = computed(() => benchLayout(props.node))
+const benchTitleW = computed(() => ((props.node.label?.trim() || 'Test bench').length * 6.4 + 10))
+const bench = computed(() => {
+ const n = props.node
+ const empty = { state: 'idle', line: '', cols: false, rows: [] as BenchRowView[], right: 0 }
+ if (n.kind !== 'bench') return empty
+ const l = bl.value
+ const right = l.x + Math.max(l.tableW, 9)
+ const cols = !!n.bench?.cols?.length
+ if (!cols) return { ...empty, right }
+ const r = props.ghost ? undefined : ed.benchResults.value.get(n.id)
+ const live = props.ghost ? undefined : ed.benchLive.value.get(n.id)
+ const rows: BenchRowView[] = (n.bench?.rows ?? []).slice(0, l.shown).map((row, i) => {
+ const res = r?.rows[i]
+ const state = res?.ok === false ? 'fail' : res?.ok ? 'pass' : ''
+ const cells = l.cols.map(c => {
+ if (c.col === '#') return { key: c.key, x: c.x, text: String(i + 1), cls: 'num' }
+ if (c.col === 'ticks') return { key: c.key, x: c.x, text: row.ticks ?? '', cls: 'num' }
+ if (c.col === 'state') return { key: c.key, x: c.x, text: res?.ok === false ? '✗' : res?.ok ? '✓' : '', cls: state }
+ if (c.drive) return { key: c.key, x: c.x, text: row.set?.[c.col] ?? '', cls: 'drive' }
+ const want = row.expect?.[c.col] ?? ''
+ const got = res?.got[c.col]
+ const wrong = res?.ok === false && want !== '' && got !== undefined && Number(want) !== got
+ return { key: c.key, x: c.x, text: want || (got !== undefined ? String(got) : ''), cls: wrong ? 'wrong' : want ? '' : 'got' }
+ })
+ const gotText = res ? Object.entries(res.got).map(([id, v]) => `${n.bench?.cols?.find(c => c.id === id)?.name ?? id} = ${v}`).join(', ') : ''
+ return { i, state, live: live === i, cells, title: [res?.error, gotText && `Reads ${gotText}`, 'Click: put this row on the circuit'].filter(Boolean).join('\n') }
+ })
+ const line = !n.bench?.rows.length ? 'no rows yet: double-click' : !r ? '' : r.error && !r.fail ? r.error : r.fail ? `✗ ${r.fail} failing` : r.pass ? `✓ ${r.pass} pass` : ''
+ return { state: r?.fail || (r?.error && !r.pass) ? 'fail' : r?.pass ? 'pass' : 'idle', line, cols, rows, right }
})
// Terminal and keyboard: what the store keeps for this part.
@@ -436,11 +462,28 @@ const title = computed(() => {
{{ node.conn && !connType ? 'type missing' : 'no lines' }}
-
+
-
- {{ benchSum.title }}
- {{ benchSum.line }}
+
+ {{ node.label?.trim() || 'Test bench' }}
+ {{ bench.line }}
+
+ Run the tests
+
+
+
+
+ {{ c.head }}
+
+ {{ r.title }}
+
+ {{ c.text }}
+
+ + {{ bl.more }} more rows (double-click)
+
+ Drop on a component, or double-click to set up
+ {{ p.label }}
+ {{ p.label }}
diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts
index 62e621a..0119d12 100644
--- a/app/composables/useEditor.ts
+++ b/app/composables/useEditor.ts
@@ -27,7 +27,7 @@ import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { probeValue } from '~/lib/logic/probes'
import { bitsCode, codeBits, DATA_KEYS, KEY_QUEUE, putChar } from '~/lib/logic/devices'
-import { AUTO_TICKS, HAND_TICKS, runBench, type BenchResult } from '~/lib/logic/bench'
+import { AUTO_TICKS, benchFor, colKeys, HAND_TICKS, parseCell, runBench, upgradeBenches, type BenchResult } from '~/lib/logic/bench'
import { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library'
@@ -438,6 +438,12 @@ function create() {
function rebuild() {
const d = def.value
+ // Benches from the first version (docked, no pins) get their columns and wires.
+ if (d.nodes.some(n => n.kind === 'bench' && n.bench?.on)) {
+ upgradeBenches(d, getDef.value)
+ commit()
+ return
+ }
const nl = compile(getDef.value, d.id)
const key = `${meta.value.id}/${d.id}`
// The circuit running goes on as it is; one opened starts from what it held when it was last open.
@@ -456,6 +462,7 @@ function create() {
}
}
scheduleBenches()
+ for (const n of d.nodes) if (n.kind === 'bench' && benchLive.value.has(n.id)) feedBench(n.id, s)
devTerms = d.nodes.filter(n => n.kind === 'terminal').map(n => n.id)
devKbs = d.nodes.filter(n => n.kind === 'keyboard').map(n => n.id)
if (!devKbs.includes(typingInto.value ?? '')) typingInto.value = null
@@ -910,15 +917,13 @@ function create() {
if (p.kind === 'ref') node.label = def.value.nodes.filter(n => n.kind === 'tag' && n.label?.trim()).at(-1)?.label?.trim() ?? ''
if (p.kind === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows()
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
- if (p.kind === 'bench') {
- node.bench = { rows: [] }
- // Dropped on (or next to) a component: docks below it.
- const chip = benchSpot(node)
- if (chip) dockAt(node, chip)
- }
+ if (p.kind === 'bench') node.bench = { cols: [], rows: [] }
// A new pixel is like the one placed last: building a colour screen, every pixel comes in colour.
if (p.kind === 'pixel' && def.value.nodes.findLast(n => n.kind === 'pixel')?.rgb) node.rgb = true
def.value.nodes.push(node)
+ // A bench put down on a component: set up for it.
+ const benchChip = p.kind === 'bench' ? benchSpot(node) : undefined
+ if (benchChip) benchOnto(node, benchChip)
rememberPart(p.kind, p.chip)
const swap = (r: PinRef) => (r.node === 'ghost' ? { node: node.id, pin: r.pin } : r)
const made = links.filter(l => addWire(swap(l.from), swap(l.to))).length
@@ -1096,7 +1101,6 @@ function create() {
for (let size = -1; size !== set.size; ) {
size = set.size
for (const p of [...dockedPanels(def.value, set), ...pluggedInto(def.value, set), ...latchedTo(def.value, set)]) set.add(p.id)
- for (const n of def.value.nodes) if (n.bench?.on && set.has(n.bench.on)) set.add(n.id)
}
return set
}
@@ -1448,9 +1452,11 @@ function create() {
const benchResults = shallowRef(new Map
())
/** The bench whose tests are open in the dialog. */
const benchOpen = ref(null)
+ /** The row each bench applies to the running circuit (none: its outputs are 0). */
+ const benchLive = shallowRef(new Map())
let benchTimer: ReturnType | undefined
- /** The component a bench docks to: one whose box is under the bench's middle, or within two squares of it. */
+ /** The component under a bench's middle, or within two squares of it. */
function benchSpot(bench: CircuitNode): CircuitNode | undefined {
const own = shapeOf(bench, getDef.value).body
const x = bench.x + own.x + own.w / 2
@@ -1458,7 +1464,7 @@ function create() {
let best: CircuitNode | undefined
let bestD = 2.01
for (const n of def.value.nodes) {
- if (n.kind !== 'chip') continue
+ if (n.kind !== 'chip' || n.id === bench.id) continue
const b = shapeOf(n, getDef.value).body
const dx = Math.max(n.x + b.x - x, 0, x - (n.x + b.x + b.w))
const dy = Math.max(n.y + b.y - y, 0, y - (n.y + b.y + b.h))
@@ -1471,51 +1477,36 @@ function create() {
return best
}
- /** Docks a bench to a component, just below it. */
- function dockAt(bench: CircuitNode, chip: CircuitNode) {
+ /**
+ * Sets an empty bench up for a component: its columns from the component's
+ * pins, wired to them, and the bench moved to the left of it.
+ */
+ function benchOnto(bench: CircuitNode, chip: CircuitNode): boolean {
+ const chipDef = chip.chip ? getDef.value(chip.chip) : undefined
+ if (!chipDef || bench.bench?.cols?.length) return false
+ const wires = benchFor(def.value, bench, chip, chipDef)
+ const own = shapeOf(bench, getDef.value).body
const b = shapeOf(chip, getDef.value).body
- bench.bench = { rows: bench.bench?.rows ?? [], on: chip.id }
- bench.x = chip.x + b.x
- bench.y = Math.ceil(chip.y + b.y + b.h + 1.5)
- }
-
- /** A bench let go after a drag: onto a component, it docks there (elsewhere it stays as it was). */
- function dropBench(bench: CircuitNode) {
- const chip = benchSpot(bench)
- if (!chip || !bench.bench) return false
- dockAt(bench, chip)
- commit(false)
- scheduleBenches()
- notify(`Docked: it tests ${getDef.value(chip.chip ?? '')?.name ?? 'the component'}`)
+ bench.x = chip.x + b.x - own.w - 6
+ bench.y = chip.y
+ for (const w of wires) addWire(w.from, w.to)
return true
}
- /** Docks a bench to a component of this circuit (or undocks it) and runs its tests. */
- function dockBench(id: string, chipId: string | null) {
- const n = def.value.nodes.find(x => x.id === id)
- const chip = chipId ? def.value.nodes.find(x => x.id === chipId && x.kind === 'chip') : undefined
- if (!n?.bench) return
- if (chip) dockAt(n, chip)
- else delete n.bench.on
- commit(false)
+ /** A bench let go after a drag: an empty one onto a component is set up for it. */
+ function dropBench(bench: CircuitNode) {
+ const chip = benchSpot(bench)
+ if (!chip || !benchOnto(bench, chip)) return false
+ commit()
scheduleBenches()
- }
-
- /** The component a bench tests, if it is docked to one that is still here. */
- function benchTarget(bench: CircuitNode): { node: CircuitNode; def: ComponentDef } | undefined {
- const node = bench.bench?.on ? def.value.nodes.find(n => n.id === bench.bench!.on) : undefined
- const d = node?.kind === 'chip' && node.chip ? getDef.value(node.chip) : undefined
- return node && d ? { node, def: d } : undefined
+ notify(`Wired to ${getDef.value(chip.chip ?? '')?.name ?? 'the component'}: a column for each of its pins`)
+ return true
}
/** Runs a bench's tests now; by hand they may run longer. */
function runBenchNow(id: string, byHand = false) {
- const n = def.value.nodes.find(x => x.id === id)
- if (!n?.bench) return
- const t = benchTarget(n)
- const res: BenchResult = t
- ? runBench(getDef.value, t.def.id, n.bench.rows, byHand ? HAND_TICKS : AUTO_TICKS)
- : { rows: [], pass: 0, fail: 0, error: 'Dock it to a component: drop it on one, or pick one in its tests' }
+ if (!def.value.nodes.some(x => x.id === id && x.kind === 'bench')) return
+ const res = runBench(getDef.value, def.value.id, id, byHand ? HAND_TICKS : AUTO_TICKS)
benchResults.value.set(id, res)
benchResults.value = new Map(benchResults.value)
if (byHand) play(res.fail || res.error ? 'error' : 'connect')
@@ -1530,16 +1521,49 @@ function create() {
}, 300)
}
- /** Changes a bench's tests (an undo step) and runs them again. */
- function setBench(id: string, change: (b: Bench) => void) {
+ /** Changes a bench (an undo step) and runs it again; columns change its pins. */
+ function setBench(id: string, change: (b: Bench) => void, structural = false) {
const n = def.value.nodes.find(x => x.id === id)
if (!n?.bench) return
change(n.bench)
- commit(false)
+ commit(structural)
scheduleBenches()
}
- // ── Assembler ─────────────────────────────────────────────────────
+ /** A bench's outputs in the running circuit: the row picked (pulses given once), or all 0. */
+ function feedBench(id: string, s = sim.value) {
+ const n = def.value.nodes.find(x => x.id === id)
+ if (!s || !n?.bench) return
+ const i = benchLive.value.get(id)
+ const row = i === undefined ? undefined : n.bench.rows[i]
+ const pulses: string[] = []
+ for (const c of n.bench.cols ?? []) {
+ if (c.dir !== 'drive') continue
+ const v = row ? parseCell(row.set?.[c.id], c.bits, true) : 0
+ const keys = colKeys(c).map(k => `${id}:${k}`)
+ if (v === 'P') pulses.push(...keys)
+ if (typeof v === 'number') keys.forEach((k, b) => s.setSource(k, Math.floor(v / 2 ** b) % 2 === 1))
+ else if (v === 'P') keys.forEach(k => s.setSource(k, false))
+ }
+ if (pulses.length) {
+ s.run(BUDGET)
+ pulses.forEach(k => s.setSource(k, true))
+ s.run(BUDGET)
+ pulses.forEach(k => s.setSource(k, false))
+ }
+ tick.value++
+ }
+
+ /** Clicking a row on a bench: the running circuit gets that row (again: back to 0). */
+ function applyBenchRow(id: string, i: number) {
+ const m = new Map(benchLive.value)
+ if (m.get(id) === i) m.delete(id)
+ else m.set(id, i)
+ benchLive.value = m
+ feedBench(id)
+ }
+
+ // ── Assembler ─────────────────────────────────────────────────────
/** The assembler's texts, kept in the project (not undo steps). */
const asmDoc = computed(() => project.value.asm ?? { ...ASM_EXAMPLE })
function saveAsm(patch: Partial) {
@@ -3114,10 +3138,10 @@ function create() {
setRgb,
benchResults,
benchOpen,
- benchTarget,
+ applyBenchRow,
+ benchLive,
runBenchNow,
setBench,
- dockBench,
dropBench,
screens,
keyQueues,
diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts
index 05bf21a..9393944 100644
--- a/app/composables/useMenu.ts
+++ b/app/composables/useMenu.ts
@@ -149,7 +149,7 @@ export function useMenu() {
}
if (n.kind === 'bench') {
out.push(
- { label: 'Edit the tests', icon: 'lucide:table', keys: 'Double-click', run: () => (ed.benchOpen.value = n.id) },
+ { label: 'Columns and rows', icon: 'lucide:table', keys: 'Double-click', run: () => (ed.benchOpen.value = n.id) },
{ label: 'Run the tests', icon: 'lucide:play', run: () => ed.runBenchNow(n.id, true) },
)
}
diff --git a/app/composables/useParts.ts b/app/composables/useParts.ts
index e60ba33..1b67d4b 100644
--- a/app/composables/useParts.ts
+++ b/app/composables/useParts.ts
@@ -62,7 +62,7 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
kind: 'bench',
name: 'Test bench',
icon: 'lucide:flask-conical',
- hint: 'Drop it on a component: a table of tests for it. Every combination, clock pulses, or ticks until the outputs are right.',
+ hint: 'A table of tests on its box: its outputs drive what you wire them to, its inputs check what comes back. Drop it on a component to wire it to every pin.',
aka: 'test truth table check verify unit',
},
],
diff --git a/app/lib/logic/bench.ts b/app/lib/logic/bench.ts
index 2e72bd2..2a4d3c5 100644
--- a/app/lib/logic/bench.ts
+++ b/app/lib/logic/bench.ts
@@ -1,30 +1,27 @@
-// Test benches: a table of tests docked to a placed component. Each row sets
-// its inputs, gives it clock ticks if asked, and checks its outputs. The
-// component runs on its own (no wires to the circuit around it), from all
-// zeros, its state carried from row to row, so a row can test memory, a
-// counter, or a whole computer running until it is done.
+// 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.
//
-// Pins A0, A1, … make one column A that takes a number. An input cell is a
-// number (12, 0x0C, 0b1100), P for a clock pulse, or empty to leave it as
-// it was. An output cell is the number it should show, empty for any.
-// Ticks: N pulses (the P inputs and the component's own clocks) before the
-// check; ≤N gives up to N, checking after each, until the outputs match.
+// 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 } from './compile'
+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, BenchRow, ComponentDef } from './types'
-
-export interface BenchColumn {
- name: string
- /** Pin keys, bit 0 first. */
- keys: string[]
-}
+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
- /** Outputs after the row, by column. */
+ /** What the check columns read after the row, by column id. */
got: Record
/** Ticks the row ran. */
ticks: number
@@ -39,61 +36,33 @@ export interface BenchResult {
}
const SETTLE = 2_000_000
-/** Ticks a run gives in all, at most (a run in the editor stays short; by hand it may go longer). */
+/** 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
-/** Rows "every combination" makes, at most (10 input bits). */
+/** "Every combination" makes rows for this many drive bits at most. */
export const MAX_COMBO_BITS = 10
-const SERIES = /^(.*?)(\d+)$/
+export { colKeys, colPinNames }
-/** Pins as columns: A0…An (numbered from 0, none missing) make one column A, any other pin is its own. */
-export function groupPins(pins: { key: string; label: string }[]): BenchColumn[] {
- 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: BenchColumn[] = []
- const done = new Set()
- for (const p of pins) {
- const m = SERIES.exec(p.label.trim())
- const name = m?.[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
-}
+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')
-export function benchColumns(def: ComponentDef): { ins: BenchColumn[]; outs: BenchColumn[] } {
- const pins = chipPins(def)
- return { ins: groupPins(pins.inputs), outs: groupPins(pins.outputs) }
-}
-
-/** A cell as a number, P (inputs only), or null when empty or a don't-care. */
-export function parseCell(s: string | undefined, bits: number, input: boolean): number | 'P' | null | { error: string } {
+/** 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 (input && /^(p|↑)$/i.test(t)) return 'P'
+ 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${input ? ' or P' : ''}` }
+ 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 outputs. Empty: one pulse when the row has a P, else none. */
+/** 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
@@ -104,18 +73,31 @@ export function parseTicks(s: string | undefined): { n: number; wait: boolean }
return { n, wait: !!m[1] }
}
-/** Runs a bench's rows on the component, in order. */
-export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], maxTicks = AUTO_TICKS): BenchResult {
- const def = getDef(defId)
+/** 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) return { ...res, error: 'The component it tests no longer exists' }
- const cols = benchColumns(def)
- const sim = new Simulator(compile(getDef, defId))
+ 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 read = (c: BenchColumn) => c.keys.reduce((v, k, i) => v + (sim.output(k) ? 2 ** i : 0), 0)
- for (const row of rows) {
+ 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) => {
@@ -123,22 +105,22 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
out.error = error
res.fail++
}
- // Inputs, pulses held low for now.
- const pulses: BenchColumn[] = []
+ // Drive columns; pulses held low for now.
+ const pulses: BenchCol[] = []
let bad = ''
- for (const c of cols.ins) {
- const v = parseCell(row.set?.[c.name], c.keys.length, true)
+ 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)
- c.keys.forEach(k => sim.setSource(k, false))
- } else if (v !== null) c.keys.forEach((k, i) => sim.setSource(k, Math.floor(v / 2 ** i) % 2 === 1))
+ put(c, 0)
+ } else if (v !== null) put(c, v)
}
- const checks: { c: BenchColumn; want: number }[] = []
- for (const c of cols.outs) {
- const v = parseCell(row.expect?.[c.name], c.keys.length, false)
+ 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') checks.push({ c, want: v })
+ else if (typeof v === 'number') want.push({ c, v })
}
const ticks = parseTicks(row.ticks)
if (ticks && 'error' in ticks) bad ||= ticks.error
@@ -148,25 +130,25 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
}
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: give a clock input P, or a clock inside')
+ 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 = () => checks.every(({ c, want }) => read(c) === want)
+ const matches = () => want.every(({ c, v }) => read(c) === v)
const tick = (): boolean => {
- for (const c of pulses) c.keys.forEach(k => sim.setSource(k, true))
+ 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) c.keys.forEach(k => sim.setSource(k, 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 && checks.length && matches()) break
+ if (spec.wait && want.length && matches()) break
if (left-- <= 0) {
stopped = `Stopped after ${maxTicks.toLocaleString('en')} ticks in all`
break
@@ -177,7 +159,7 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
}
out.ticks++
}
- for (const c of cols.outs) out.got[c.name] = read(c)
+ for (const c of checks) out.got[c.id] = read(c)
if (stopped) {
fail(stopped)
if (left <= 0) {
@@ -186,7 +168,7 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
}
continue
}
- if (!checks.length) continue
+ if (!want.length) continue
out.ok = matches()
if (out.ok) res.pass++
else {
@@ -197,21 +179,20 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
return res
}
-/** Every combination of the inputs, counting up (the first column the highest), outputs left to fill. */
-export function combinationRows(def: ComponentDef): BenchRow[] | { error: string } {
- const { ins } = benchColumns(def)
- const bits = ins.reduce((n, c) => n + c.keys.length, 0)
- if (!ins.length) return { error: 'It has no inputs' }
- if (bits > MAX_COMBO_BITS) return { error: `${bits} input bits are ${2 ** bits} combinations: at most ${MAX_COMBO_BITS} bits` }
+/** 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 = ins.length - 1; k >= 0; k--) {
- const c = ins[k]!
- const n = 2 ** c.keys.length
- set[c.name] = String(rest % n)
- rest = Math.floor(rest / n)
+ 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 })
}
@@ -219,22 +200,102 @@ export function combinationRows(def: ComponentDef): BenchRow[] | { error: string
}
/**
- * The rows with what the component shows now in their empty output cells
- * (to keep it working the same). Outputs already filled in stay as they are,
- * so a row that waits for them waits the same.
+ * 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(getDef: DefLookup, defId: string, rows: BenchRow[]): BenchRow[] {
- const r = runBench(getDef, defId, rows, HAND_TICKS)
+export function recordExpected(r: BenchResult, rows: BenchRow[]): BenchRow[] {
return rows.map((row, i) => {
- const got = r.rows[i]?.got
- if (!got || (r.rows[i]?.error && r.rows[i]?.ok !== false)) return row
+ 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(got)) if (!expect[k]?.trim()) expect[k] = String(v)
+ for (const [k, v] of Object.entries(res.got)) if (!expect[k]?.trim()) expect[k] = String(v)
return { ...row, expect }
})
}
-/** A bench cell's value for a column, by name. */
-export const cellOf = (row: BenchRow, side: 'set' | 'expect', name: string) => row[side]?.[name] ?? ''
+// ── Columns for a component ──────────────────────────────────────────
-export type { Bench, BenchRow }
+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 })
+ }
+}
diff --git a/app/lib/logic/benchLayout.ts b/app/lib/logic/benchLayout.ts
new file mode 100644
index 0000000..150d27c
--- /dev/null
+++ b/app/lib/logic/benchLayout.ts
@@ -0,0 +1,75 @@
+// Where everything on a test bench's box goes: check pins down the left,
+// drive pins down the right, the title bar with its run button, and the
+// table between them. The shape (pins) and the drawing both use this.
+
+import type { BenchCol, CircuitNode } from './types'
+
+/** Pin keys of a column, bit 0 first. */
+export const colKeys = (c: BenchCol) => Array.from({ length: c.bits }, (_, i) => `${c.id}.${i}`)
+
+/** A column's pin names: its name, numbered when it has several bits. */
+export const colPinNames = (c: BenchCol) => (c.bits === 1 ? [c.name] : Array.from({ length: c.bits }, (_, i) => `${c.name}${i}`))
+
+/** Rows the box shows; more are in the dialog. */
+export const BENCH_ROWS_SHOWN = 24
+const CHAR = 0.4 // grid units per character at the table's size
+const TITLE_H = 1.4
+
+export interface BenchCell {
+ key: string
+ /** Column id, '#' for the row number, 'ticks', or 'state'. */
+ col: string
+ x: number
+ w: number
+ head: string
+ drive?: boolean
+}
+
+export interface BenchLayout {
+ w: number
+ h: number
+ /** Pin rows on each side: key and name. */
+ left: { key: string; label: string }[]
+ right: { key: string; label: string }[]
+ /** Table: left edge, top of the header row, its columns, rows shown, rows not shown. */
+ x: number
+ top: number
+ cols: BenchCell[]
+ shown: number
+ more: number
+ tableW: number
+}
+
+export function benchLayout(node: CircuitNode): BenchLayout {
+ const b = node.bench
+ const cols = b?.cols ?? []
+ const rows = b?.rows ?? []
+ const checks = cols.filter(c => c.dir === 'check')
+ const drives = cols.filter(c => c.dir === 'drive')
+ const left = checks.flatMap(c => colKeys(c).map((key, i) => ({ key, label: colPinNames(c)[i]! })))
+ const right = drives.flatMap(c => colKeys(c).map((key, i) => ({ key, label: colPinNames(c)[i]! })))
+ const labelW = (list: { label: string }[]) => (list.length ? Math.max(...list.map(p => p.label.length)) * CHAR + 0.7 : 0.3)
+ const lw = labelW(left)
+ const rw = labelW(right)
+ const shown = Math.min(rows.length, BENCH_ROWS_SHOWN)
+ const width = (head: string, cells: string[]) => Math.max(head.length, 1, ...cells.slice(0, shown).map(s => s.length)) * CHAR + 0.6
+ const table: Omit[] = [{ key: '#', col: '#', w: width('#', [String(shown)]), head: '#' }]
+ for (const c of [...drives, ...checks]) {
+ const cells = rows.map(r => (c.dir === 'drive' ? r.set?.[c.id] : r.expect?.[c.id]) ?? '')
+ table.push({ key: c.id, col: c.id, w: width(c.name, cells), head: c.name, drive: c.dir === 'drive' })
+ }
+ if (rows.some(r => r.ticks)) table.push({ key: 'ticks', col: 'ticks', w: width('Ticks', rows.map(r => r.ticks ?? '')), head: 'Ticks' })
+ table.push({ key: 'state', col: 'state', w: 1, head: '' })
+ let x = lw + 0.2
+ const placed = table.map(c => {
+ const out = { ...c, x }
+ x += c.w
+ return out
+ })
+ const tableW = x - lw - 0.2
+ const w = Math.ceil(Math.max(lw + 0.2 + Math.max(tableW, 9) + 0.2 + rw, 10))
+ const more = rows.length - shown
+ const tableH = cols.length ? 1 + shown + (more ? 1 : 0) : 1.2
+ const h = Math.ceil(Math.max(left.length, right.length, TITLE_H + tableH + 0.4))
+ return { w, h, left, right, x: lw + 0.2, top: -0.5 + TITLE_H, cols: placed, shown, more, tableW }
+}
diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts
index 1f192e9..25c5232 100644
--- a/app/lib/logic/compile.ts
+++ b/app/lib/logic/compile.ts
@@ -3,6 +3,7 @@
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
import { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry'
+import { colKeys } from './benchLayout'
import { DATA_KEYS } from './devices'
import type { CircuitNode, ComponentDef, Wire } from './types'
@@ -58,6 +59,8 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return [...DATA_KEYS, 'wr', 'clr']
case 'keyboard':
return ['next']
+ case 'bench':
+ return (node.bench?.cols ?? []).filter(c => c.dir === 'check').flatMap(colKeys)
case 'outpanel':
return (node.rows ?? []).map(r => r.id)
case 'bundle':
@@ -98,6 +101,8 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return ['q0', 'q1', 'q2', 'q3']
case 'keyboard':
return [...DATA_KEYS, 'rdy']
+ case 'bench':
+ return (node.bench?.cols ?? []).filter(c => c.dir === 'drive').flatMap(colKeys)
case 'panel':
case 'outpanel':
return (node.rows ?? []).map(r => r.id)
@@ -254,8 +259,9 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
case 'button':
if (!inNets) sources.set(n.id, q)
break
+ case 'bench':
case 'keyboard':
- // The keys typed, in the open circuit; inside a component it is all 0.
+ // Set from outside (the keys typed, a bench's row), in the open circuit; inside a component it is all 0.
if (!inNets) for (const k of outputKeys(n)) sources.set(`${n.id}:${k}`, outNet.get(`${n.id}:${k}`)!)
break
case 'high':
diff --git a/app/lib/logic/geometry.ts b/app/lib/logic/geometry.ts
index 91b584d..f537a09 100644
--- a/app/lib/logic/geometry.ts
+++ b/app/lib/logic/geometry.ts
@@ -2,6 +2,7 @@
// (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
+import { benchLayout } from './benchLayout'
import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices'
export const GRID = 16
@@ -727,7 +728,14 @@ const TERMINAL_SHAPE: Shape = {
outputs: [],
}
-const BENCH_SHAPE: Shape = { body: { x: 0, y: -0.5, w: 9, h: 2 }, inputs: [], outputs: [] }
+function benchShape(node: CircuitNode): Shape {
+ const l = benchLayout(node)
+ return {
+ body: { x: 0, y: -0.5, w: l.w, h: l.h },
+ inputs: l.left.map((p, i) => ({ key: p.key, label: p.label, dx: 0, dy: i })),
+ outputs: l.right.map((p, i) => ({ key: p.key, label: p.label, dx: l.w, dy: i })),
+ }
+}
const KEYBOARD_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 7, h: 9 },
@@ -834,7 +842,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
case 'terminal':
return TERMINAL_SHAPE
case 'bench':
- return BENCH_SHAPE
+ return benchShape(node)
case 'keyboard':
return KEYBOARD_SHAPE
case 'outpanel':
diff --git a/app/lib/logic/labels.ts b/app/lib/logic/labels.ts
index d361486..af2bb88 100644
--- a/app/lib/logic/labels.ts
+++ b/app/lib/logic/labels.ts
@@ -3,6 +3,7 @@
// name of the component pin it is wired to.
import { chipPins, splitLines, type DefLookup } from './geometry'
+import { colPinNames } from './benchLayout'
import { DEVICE_PIN_NAMES } from './devices'
import type { CircuitNode, ComponentDef, NodeKind } from './types'
@@ -84,6 +85,11 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
// A wire of a cable carries the name of its signal (the cable pin itself has none).
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
if (node.kind === 'terminal' || node.kind === 'keyboard') return DEVICE_PIN_NAMES[pin]
+ if (node.kind === 'bench') {
+ const [id, bit] = pin.split('.')
+ const c = node.bench?.cols?.find(x => x.id === id)
+ return c ? colPinNames(c)[Number(bit)] : undefined
+ }
if (node.kind !== 'chip' || !node.chip) return undefined
const def = get(node.chip)
// A line of a port split on the box: port.line, named after the line.
diff --git a/app/lib/logic/ops.ts b/app/lib/logic/ops.ts
index f235513..8a20ef3 100644
--- a/app/lib/logic/ops.ts
+++ b/app/lib/logic/ops.ts
@@ -264,11 +264,6 @@ function redock(nodes: CircuitNode[], ids: Map) {
if (to) n[k] = to
else delete n[k]
}
- if (n.bench?.on) {
- const to = ids.get(n.bench.on)
- if (to) n.bench.on = to
- else delete n.bench.on
- }
if (!n.attach) continue
const to = ids.get(n.attach)
if (to) n.attach = to
diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts
index 231c0e5..e7017eb 100644
--- a/app/lib/logic/project.ts
+++ b/app/lib/logic/project.ts
@@ -54,8 +54,15 @@ function cleanNode(n: CircuitNode) {
const cells = (r: unknown) => (r && typeof r === 'object' && !Array.isArray(r) ? Object.fromEntries(Object.entries(r).filter(([, v]) => typeof v === 'string').slice(0, 256)) : undefined)
if (!b || typeof b !== 'object' || !Array.isArray(b.rows)) delete n.bench
else {
+ const cols = Array.isArray(b.cols)
+ ? b.cols
+ .filter(c => c && typeof c.id === 'string' && typeof c.name === 'string' && (c.dir === 'drive' || c.dir === 'check'))
+ .slice(0, 64)
+ .map(c => ({ id: c.id, name: c.name.slice(0, 40), bits: Number.isInteger(c.bits) && c.bits >= 1 && c.bits <= 32 ? c.bits : 1, dir: c.dir }))
+ : undefined
n.bench = {
...(typeof b.on === 'string' ? { on: b.on } : {}),
+ ...(cols ? { cols } : {}),
rows: b.rows.slice(0, 4096).filter(r => r && typeof r === 'object').map(r => ({
...(cells(r.set) ? { set: cells(r.set) } : {}),
...(cells(r.expect) ? { expect: cells(r.expect) } : {}),
diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts
index 0a54224..2ee49c7 100644
--- a/app/lib/logic/types.ts
+++ b/app/lib/logic/types.ts
@@ -24,7 +24,7 @@ export type BuiltinKind =
| 'ref' // carries the signal of the tag with the same name in this circuit, without a wire
| 'terminal' // a text screen: writes the character on D0–D7 at a rising WR, clears at a rising CLR
| 'keyboard' // the keys you type: the first waiting one on D0–D7, RDY while one waits, a rising NEXT takes it
- | 'bench' // a table of tests for the placed component it is docked to (no pins)
+ | 'bench' // a table of tests: drives the circuit from its outputs, checks what comes back on its inputs
export type NodeKind = BuiltinKind | 'chip'
@@ -87,15 +87,26 @@ export interface CircuitNode {
/** A test bench (see lib/logic/bench). */
export interface Bench {
- /** The placed component it is docked to (a chip node in the same circuit). */
- on?: string
+ /** Its columns: each a group of pins, as many bits as it has. */
+ cols?: BenchCol[]
rows: BenchRow[]
+ /** Left from the first version, which tested the component it was docked to: that chip node. Turned into columns and wires on loading. */
+ on?: string
+}
+
+export interface BenchCol {
+ /** Stays when the column is renamed, so its wires stay too. */
+ id: string
+ name: string
+ bits: number
+ /** 'drive': output pins the bench sets; 'check': input pins it reads and checks. */
+ dir: 'drive' | 'check'
}
export interface BenchRow {
- /** Input cells by column name: a number, P for a pulse; empty leaves it. */
+ /** Cells of the drive columns by column id: a number, P for a pulse; empty leaves it. */
set?: Record
- /** Output cells by column name: the number it should show; empty for any. */
+ /** Cells of the check columns by column id: the number it should read; empty for any. */
expect?: Record
/** N ticks before the check, or ≤N to wait up to N. */
ticks?: string
diff --git a/tests/bench.test.ts b/tests/bench.test.ts
index c9fb607..6410c91 100644
--- a/tests/bench.test.ts
+++ b/tests/bench.test.ts
@@ -1,95 +1,97 @@
import { describe, expect, it } from 'vitest'
-import { benchColumns, combinationRows, groupPins, parseCell, parseTicks, recordExpected, runBench } from '../app/lib/logic/bench'
-import { createProject, lookup } from '../app/lib/logic/ops'
-import type { Project } from '../app/lib/logic/types'
+import { benchFor, checkCols, combinationRows, driveCols, groupPins, parseCell, parseTicks, recordExpected, runBench, upgradeBenches } from '../app/lib/logic/bench'
+import { benchLayout } from '../app/lib/logic/benchLayout'
+import { compile } from '../app/lib/logic/compile'
+import { shapeOf } from '../app/lib/logic/geometry'
+import { createProject, lookup, uid } from '../app/lib/logic/ops'
+import type { CircuitNode, ComponentDef, Project } from '../app/lib/logic/types'
-/** Examples: a half adder, and the 4-bit counter (CLK, RST in; Q0–Q3 out). */
-function project(): Project {
- return createProject({ examples: true })
+/** A circuit with one placed example component and a bench wired to all its pins. */
+function rig(chipId: string): { p: Project; def: ComponentDef; bench: CircuitNode } {
+ const p = createProject({ examples: true })
+ const bench: CircuitNode = { id: 'tb', kind: 'bench', x: 0, y: 0, bench: { cols: [], rows: [] } }
+ const chip: CircuitNode = { id: 'u', kind: 'chip', chip: chipId, x: 20, y: 0 }
+ const def: ComponentDef = { id: 'rig', name: 'Rig', symbol: 'box', nodes: [bench, chip], wires: [] }
+ p.components.push(def)
+ for (const w of benchFor(def, bench, chip, lookup(p)(chipId)!)) def.wires.push({ id: uid('w'), ...w })
+ return { p, def, bench }
}
+const col = (b: CircuitNode, name: string) => b.bench!.cols!.find(c => c.name === name)!.id
-describe('test bench columns and cells', () => {
- it('A0…An make one number column; other pins stay single', () => {
- const cols = groupPins([
- { key: 'a1', label: 'A1' },
- { key: 'a0', label: 'A0' },
- { key: 'c', label: 'Cin' },
- { key: 'x2', label: 'X2' },
- ])
- expect(cols).toEqual([
+describe('test bench cells', () => {
+ it('A0…An make one group; other pins stay single', () => {
+ expect(groupPins([{ key: 'a1', label: 'A1' }, { key: 'a0', label: 'A0' }, { key: 'c', label: 'Cin' }, { key: 'x2', label: 'X2' }])).toEqual([
{ name: 'A', keys: ['a0', 'a1'] },
{ name: 'Cin', keys: ['c'] },
{ name: 'X2', keys: ['x2'] },
])
})
- it('cells: numbers in three bases, P, don’t care, and what does not fit', () => {
- expect(parseCell('12', 4, true)).toBe(12)
+ it('numbers in three bases, P, don’t care, what does not fit; ticks', () => {
expect(parseCell('0x0C', 4, true)).toBe(12)
expect(parseCell('0b1100', 4, true)).toBe(12)
expect(parseCell('-1', 4, false)).toBe(15)
expect(parseCell('p', 1, true)).toBe('P')
- expect(parseCell('', 1, false)).toBeNull()
expect(parseCell('x', 1, false)).toBeNull()
expect(parseCell('16', 4, true)).toHaveProperty('error')
expect(parseCell('P', 1, false)).toHaveProperty('error')
- expect(parseTicks('5')).toEqual({ n: 5, wait: false })
expect(parseTicks('≤100')).toEqual({ n: 100, wait: true })
- expect(parseTicks('<= 7')).toEqual({ n: 7, wait: true })
expect(parseTicks('soon')).toHaveProperty('error')
})
})
-describe('running a test bench', () => {
- it('a truth table: every combination, recorded, then passing; a wrong row fails', () => {
- const p = project()
- const ha = p.components.find(c => c.id === 'ex-ha')!
- const rows = combinationRows(ha)
+describe('a wired test bench', () => {
+ it('has pins: check columns on the left, drive columns on the right', () => {
+ const { p, bench } = rig('ex-ha')
+ const shape = shapeOf(bench, lookup(p))
+ expect(shape.inputs.map(x => x.label)).toEqual(checkCols(bench.bench).map(c => c.name))
+ expect(shape.outputs.map(x => x.label)).toEqual(driveCols(bench.bench).map(c => c.name))
+ expect(shape.outputs.every(x => x.dx === benchLayout(bench).w)).toBe(true)
+ const nl = compile(lookup(p), 'rig')
+ expect(nl.sources.size).toBe(shape.outputs.length)
+ })
+
+ it('a truth table: every combination, taken, passing; a wrong row fails', () => {
+ const { p, bench } = rig('ex-ha')
+ const rows = combinationRows(bench.bench!)
if ('error' in rows) throw new Error(rows.error)
expect(rows.length).toBe(4)
- const filled = recordExpected(lookup(p), ha.id, rows)
- const r = runBench(lookup(p), ha.id, filled)
- expect(r).toMatchObject({ pass: 4, fail: 0 })
- const cols = benchColumns(ha)
- const outName = cols.outs[0]!.name
- // Filled cells stay: taking again changes nothing.
- expect(recordExpected(lookup(p), ha.id, filled)).toEqual(filled)
- filled[3] = { ...filled[3], expect: { ...filled[3]!.expect, [outName]: filled[3]!.expect![outName] === '1' ? '0' : '1' } }
- const r2 = runBench(lookup(p), ha.id, filled)
- expect(r2.fail).toBe(1)
- expect(r2.rows[3]!.ok).toBe(false)
+ bench.bench!.rows = rows
+ bench.bench!.rows = recordExpected(runBench(lookup(p), 'rig', 'tb'), rows)
+ // Half adder, A B → S C: 1 + 1 is S 0, C 1.
+ const last = bench.bench!.rows[3]!
+ expect([last.expect![col(bench, 'S')], last.expect![col(bench, 'C')]]).toEqual(['0', '1'])
+ expect(runBench(lookup(p), 'rig', 'tb')).toMatchObject({ pass: 4, fail: 0 })
+ last.expect![col(bench, 'C')] = '0'
+ const r = runBench(lookup(p), 'rig', 'tb')
+ expect(r.fail).toBe(1)
+ expect(r.rows[3]).toMatchObject({ ok: false })
})
it('a counter: pulses, ticks, and waiting until it gets there', () => {
- const p = project()
- const counter = p.components.find(c => c.id === 'ex-cnt4')!
- const { ins, outs } = benchColumns(counter)
- const clk = ins.find(c => /clk/i.test(c.name))!.name
- const rst = ins.find(c => /r/i.test(c.name) && c.name !== clk)?.name
- const q = outs[0]!
- const rows = [
- { set: { [clk]: 'P', ...(rst ? { [rst]: '0' } : {}) } },
- { set: { [clk]: 'P' }, ticks: '2' },
- { set: { [clk]: 'P' }, ticks: '≤50', expect: { [q.name]: '9' } },
- ]
- const r = runBench(lookup(p), counter.id, rows)
- expect(q.keys.length).toBe(4)
- expect(r.rows[0]!.ticks).toBe(1)
- expect(r.rows[1]!.ticks).toBe(2)
- expect(r.rows[1]!.got[q.name]).toBe(3)
+ const { p, bench } = rig('ex-cnt4')
+ const clk = col(bench, 'CLK')
+ const q = col(bench, 'Q')
+ bench.bench!.rows = [{ set: { [clk]: 'P' } }, { set: { [clk]: 'P' }, ticks: '2' }, { set: { [clk]: 'P' }, ticks: '≤50', expect: { [q]: '9' } }]
+ const r = runBench(lookup(p), 'rig', 'tb')
+ expect(r.rows[1]!.got[q]).toBe(3)
expect(r.rows[2]).toMatchObject({ ok: true, ticks: 6 })
- // Too few ticks to get there.
- const r2 = runBench(lookup(p), counter.id, [{ set: { [clk]: 'P' }, ticks: '≤3', expect: { [q.name]: '9' } }])
- expect(r2.rows[0]).toMatchObject({ ok: false, error: 'Not within 3 ticks' })
+ bench.bench!.rows = [{ set: { [clk]: 'P' }, ticks: '≤3', expect: { [q]: '9' } }]
+ expect(runBench(lookup(p), 'rig', 'tb').rows[0]).toMatchObject({ ok: false, error: 'Not within 3 ticks' })
+ bench.bench!.rows = [{ set: { [clk]: 'P' }, ticks: '100' }]
+ expect(runBench(lookup(p), 'rig', 'tb', 10).error).toMatch(/Stopped after 10 ticks/)
})
- it('stops a run that goes on too long, and says why rows are broken', () => {
- const p = project()
- const counter = p.components.find(c => c.id === 'ex-cnt4')!
- const clk = benchColumns(counter).ins.find(c => /clk/i.test(c.name))!.name
- const r = runBench(lookup(p), counter.id, [{ set: { [clk]: 'P' }, ticks: '100' }], 10)
- expect(r.error).toMatch(/Stopped after 10 ticks/)
- const r2 = runBench(lookup(p), counter.id, [{ set: { [clk]: 'nope' } }])
- expect(r2.rows[0]!.error).toMatch(/not a number/)
+ it('a bench from the first version (docked, keyed by names) gets columns and wires', () => {
+ const p = createProject({ examples: true })
+ const chip: CircuitNode = { id: 'u', kind: 'chip', chip: 'ex-ha', x: 20, y: 0 }
+ const old: CircuitNode = { id: 'tb', kind: 'bench', x: 0, y: 0, bench: { on: 'u', rows: [{ set: { A: '1', B: '1' }, expect: { S: '0', C: '1' } }] } }
+ const def: ComponentDef = { id: 'rig', name: 'Rig', symbol: 'box', nodes: [old, chip], wires: [] }
+ p.components.push(def)
+ upgradeBenches(def, lookup(p))
+ expect(old.bench!.on).toBeUndefined()
+ expect(old.bench!.cols!.map(c => `${c.dir}:${c.name}`)).toEqual(['drive:A', 'drive:B', 'check:S', 'check:C'])
+ expect(def.wires.length).toBe(4)
+ expect(runBench(lookup(p), 'rig', 'tb')).toMatchObject({ pass: 1, fail: 0 })
})
})