R test bench is a wired part: drive and check columns as pins, its table on the box with a run button, failing rows red, a click puts a row on the circuit; dropped on a component it wires itself to every pin; docked benches upgrade

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 13:30:07 +01:00
parent 9528047f44
commit 0d6758c8c9
16 changed files with 737 additions and 359 deletions

View File

@ -6085,31 +6085,28 @@ button.tile:hover {
/* Test bench */ /* Test bench */
.node .bench-body { .node .bench-body {
fill: #141c24; fill: #121921;
stroke: #3b4554; stroke: #3b4554;
stroke-dasharray: 4 3;
} }
.node .bench-body.pass { .node .bench-body.pass {
stroke: var(--on); stroke: var(--on);
stroke-dasharray: none;
} }
.node .bench-body.fail { .node .bench-body.fail {
stroke: var(--danger); stroke: var(--danger);
stroke-dasharray: none;
} }
.node .bench-title { .node .bench-title {
fill: var(--text); fill: var(--text);
font-size: 10px; font-size: 10px;
font-weight: 600; font-weight: 700;
pointer-events: none; pointer-events: none;
} }
.node .bench-line { .node .bench-line {
fill: var(--muted); fill: var(--muted);
font-size: 10px; font-size: 9.5px;
pointer-events: none; pointer-events: none;
} }
@ -6121,6 +6118,117 @@ button.tile:hover {
fill: var(--danger); 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 { .modal.bench {
width: min(1100px, 100%); width: min(1100px, 100%);
} }
@ -6139,14 +6247,6 @@ button.tile:hover {
margin: 10px 0 8px; margin: 10px 0 8px;
} }
.bench-target {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 600;
}
.bench-summary { .bench-summary {
margin-bottom: 6px; margin-bottom: 6px;
font-size: 13px; font-size: 13px;

View File

@ -1,24 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
// The tests of a test bench: a row per test, the component's inputs on the // A test bench's columns and rows. Drive columns are its output pins (it
// left, what its outputs should show on the right, ticks to give it, and // sets them), check columns its input pins (it reads and checks them). Each
// how each row went. They run again after every change. // row sets the drive columns, gives the circuit ticks, then checks.
import { benchColumns, cellOf, combinationRows, recordExpected } from '~/lib/logic/bench' import { checkCols, combinationRows, driveCols, recordExpected } from '~/lib/logic/bench'
import type { BenchRow } from '~/lib/logic/types' import { uid } from '~/lib/logic/ops'
import type { BenchCol, BenchRow } from '~/lib/logic/types'
const ed = useEditor() const ed = useEditor()
const close = () => (ed.benchOpen.value = null) const close = () => (ed.benchOpen.value = null)
const node = computed(() => ed.def.value.nodes.find(n => n.id === ed.benchOpen.value && n.kind === 'bench')) const node = computed(() => ed.def.value.nodes.find(n => n.id === ed.benchOpen.value && n.kind === 'bench'))
watch(node, n => !n && close()) watch(node, n => !n && close())
const target = computed(() => (node.value ? ed.benchTarget(node.value) : undefined)) const cols = computed(() => node.value?.bench?.cols ?? [])
const cols = computed(() => (target.value ? benchColumns(target.value.def) : { ins: [], outs: [] })) const drives = computed(() => driveCols(node.value?.bench))
const checks = computed(() => checkCols(node.value?.bench))
const rows = computed(() => node.value?.bench?.rows ?? []) const rows = computed(() => node.value?.bench?.rows ?? [])
const result = computed(() => (node.value ? ed.benchResults.value.get(node.value.id) : undefined)) const result = computed(() => (node.value ? ed.benchResults.value.get(node.value.id) : undefined))
/** Components in this circuit it can be docked to. */
const chips = computed(() =>
ed.def.value.nodes
.filter(n => n.kind === 'chip' && n.chip)
.map(n => ({ id: n.id, name: `${ed.getDef.value(n.chip!)?.name ?? 'Missing'}${n.label?.trim() && !n.autoLabel ? ` · ${n.label.trim()}` : ''}` })),
)
function onKey(e: KeyboardEvent) { function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') close() if (e.key === 'Escape') close()
@ -30,14 +26,36 @@ onMounted(() => {
onBeforeUnmount(() => window.removeEventListener('keydown', onKey)) onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
const id = () => node.value!.id const id = () => node.value!.id
const dock = (chipId: string) => ed.dockBench(id(), chipId || null) /** Columns change the bench's pins: a structural change. */
function setCell(i: number, side: 'set' | 'expect', name: string, v: string) { const setCols = (f: (c: BenchCol[]) => void) => ed.setBench(id(), b => f((b.cols ??= [])), true)
function addCol(dir: BenchCol['dir']) {
const used = new Set(cols.value.map(c => c.name))
let k = cols.value.filter(c => c.dir === dir).length
const base = dir === 'drive' ? 'IN' : 'OUT'
while (used.has(`${base}${k}`)) k++
setCols(c => c.push({ id: uid('c'), name: `${base}${k}`, bits: 1, dir }))
}
const renameCol = (i: number, name: string) => name.trim() && setCols(c => (c[i]!.name = name.trim().slice(0, 40)))
function setBits(i: number, v: string) {
const n = Math.round(Number(v))
if (n >= 1 && n <= 32) setCols(c => (c[i]!.bits = n))
}
const removeCol = (i: number) => setCols(c => c.splice(i, 1))
function moveCol(i: number, by: number) {
setCols(c => {
const j = i + by
if (j < 0 || j >= c.length) return
;[c[i], c[j]] = [c[j]!, c[i]!]
})
}
function setCell(i: number, side: 'set' | 'expect', colId: string, v: string) {
ed.setBench(id(), b => { ed.setBench(id(), b => {
const row = b.rows[i] const row = b.rows[i]
if (!row) return if (!row) return
const cells = { ...(row[side] ?? {}) } const cells = { ...(row[side] ?? {}) }
if (v.trim()) cells[name] = v.trim() if (v.trim()) cells[colId] = v.trim()
else delete cells[name] else delete cells[colId]
if (Object.keys(cells).length) row[side] = cells if (Object.keys(cells).length) row[side] = cells
else delete row[side] else delete row[side]
}) })
@ -58,29 +76,28 @@ function addRow(at = rows.value.length) {
} }
const removeRow = (i: number) => ed.setBench(id(), b => b.rows.splice(i, 1)) const removeRow = (i: number) => ed.setBench(id(), b => b.rows.splice(i, 1))
function combinations() { function combinations() {
const t = target.value const b = node.value?.bench
if (!t) return if (!b) return
const r = combinationRows(t.def) const r = combinationRows(b)
if ('error' in r) return ed.notify(r.error, 'error') if ('error' in r) return ed.notify(r.error, 'error')
ed.setBench(id(), b => (b.rows = r)) ed.setBench(id(), x => (x.rows = r))
ed.notify(`${r.length} rows: one for every input combination. Fill in what it should show, or take what it does now.`) ed.notify(`${r.length} rows, one for every combination. Fill in what it should read, or take what it does.`)
} }
function takeExpected() { function takeExpected() {
const t = target.value ed.runBenchNow(id(), true)
if (!t || !rows.value.length) return const r = result.value
const filled = recordExpected(ed.getDef.value, t.def.id, rows.value) if (!r) return
ed.setBench(id(), b => (b.rows = filled)) ed.setBench(id(), b => (b.rows = recordExpected(r, b.rows)))
ed.notify('Expected outputs set to what it shows now: the tests keep it that way') ed.notify('Empty checks set to what it reads now: the tests keep it that way')
} }
/** The value a failing output cell showed, when it differs. */ /** What a failing check cell read, when it differs. */
function gotNote(i: number, name: string): string { function gotNote(i: number, colId: string): string {
const r = result.value?.rows[i] const r = result.value?.rows[i]
if (!r || r.ok !== false) return '' const want = rows.value[i]?.expect?.[colId] ?? ''
const want = cellOf(rows.value[i]!, 'expect', name) const got = r?.got[colId]
const got = r.got[name] if (!r || r.ok !== false || got === undefined || !want) return ''
if (got === undefined || !want) return '' return Number(want) === got ? '' : `is ${got}`
return String(got) === want || (/^0[xb]/i.test(want) && Number(want) === got) ? '' : `is ${got}`
} }
</script> </script>
@ -88,45 +105,55 @@ function gotNote(i: number, name: string): string {
<div class="modal-backdrop" @click.self="close"> <div class="modal-backdrop" @click.self="close">
<div class="modal bench" role="dialog" aria-labelledby="bench-title"> <div class="modal bench" role="dialog" aria-labelledby="bench-title">
<div class="flex items-start justify-between gap-4"> <div class="flex items-start justify-between gap-4">
<h2 id="bench-title">Tests</h2> <h2 id="bench-title">{{ node?.label?.trim() || 'Test bench' }}</h2>
<button class="tb-btn" title="Close (Esc)" @click="close"><Icon name="lucide:x" class="size-4" /></button> <button class="tb-btn" title="Close (Esc)" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div> </div>
<p class="hint"> <p class="hint">
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. Wire its pins to what you test: <strong>drive</strong> columns are its outputs (on the right of its box), <strong>check</strong> columns its inputs (on the left).
Inputs: a number (12, 0x0C, 0b1100), <code>P</code> for a clock pulse, empty to leave it. Outputs: what it should show, empty for any. 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.
Ticks: <code>5</code> pulses (the P inputs and its own clocks), or <code>≤1000</code> to wait until the outputs are right. Drive: a number (12, 0x0C, 0b1100), <code>P</code> for a clock pulse, empty to leave it. Check: what it should read, empty for any.
Ticks: <code>5</code> pulses (P columns and the circuit's clocks), or <code>≤1000</code> to wait until the checks hold. Click a row on the box to put it on the running circuit.
</p> </p>
<div class="bench-bar"> <h3>Columns</h3>
<label class="bench-target"> <div class="bench-cols">
<span>Tests</span> <div v-for="(c, i) in cols" :key="c.id" class="bench-col" :class="c.dir">
<select class="tb-select" :value="node?.bench?.on ?? ''" @change="dock(($event.target as HTMLSelectElement).value)"> <span class="bench-col-dir">{{ c.dir === 'drive' ? 'Drive' : 'Check' }}</span>
<option value="">nothing yet</option> <input class="field-input" :value="c.name" spellcheck="false" @change="renameCol(i, ($event.target as HTMLInputElement).value)" />
<option v-for="c in chips" :key="c.id" :value="c.id">{{ c.name }}</option> <label title="Bits: one pin each">
</select> <input class="field-input bench-bits" type="number" min="1" max="32" :value="c.bits" @change="setBits(i, ($event.target as HTMLInputElement).value)" />
bits
</label> </label>
<span class="grow" /> <button class="icon-btn" title="Further left" :disabled="i === 0" @click="moveCol(i, -1)"><Icon name="lucide:chevron-up" class="size-3.5" /></button>
<button class="btn-sm" :disabled="!target" title="A row for every combination of the inputs" @click="combinations"><Icon name="lucide:grid-3x3" class="size-3.5" /> Every combination</button> <button class="icon-btn" title="Further right" :disabled="i === cols.length - 1" @click="moveCol(i, 1)"><Icon name="lucide:chevron-down" class="size-3.5" /></button>
<button class="btn-sm" :disabled="!target || !rows.length" title="Expected outputs: what it shows now" @click="takeExpected"><Icon name="lucide:camera" class="size-3.5" /> Take what it does</button> <button class="icon-btn" title="Remove the column (and its pins)" @click="removeCol(i)"><Icon name="lucide:trash-2" class="size-3.5" /></button>
<button class="btn-sm" :disabled="!target || !rows.length" title="Run again, longer runs allowed" @click="node && ed.runBenchNow(node.id, true)"><Icon name="lucide:play" class="size-3.5" /> Run</button> </div>
<div class="bench-bar">
<button class="btn-sm" @click="addCol('drive')"><Icon name="lucide:plus" class="size-3.5" /> Drive column</button>
<button class="btn-sm" @click="addCol('check')"><Icon name="lucide:plus" class="size-3.5" /> Check column</button>
</div>
</div> </div>
<p v-if="!target" class="hint bench-empty">Pick the component it tests above, or drop the bench on one.</p> <h3>Rows</h3>
<template v-else> <div class="bench-bar">
<p v-if="result" class="bench-summary" :class="result.fail || result.error ? 'fail' : result.pass ? 'pass' : ''"> <p v-if="result" class="bench-summary" :class="result.fail || result.error ? 'fail' : result.pass ? 'pass' : ''">
<template v-if="result.error">{{ result.error }}. </template> <template v-if="result.error">{{ result.error }}. </template>
<template v-if="result.fail">{{ result.fail }} failing, {{ result.pass }} pass</template> <template v-if="result.fail">{{ result.fail }} failing, {{ result.pass }} pass</template>
<template v-else-if="result.pass">All {{ result.pass }} pass</template> <template v-else-if="result.pass">All {{ result.pass }} pass</template>
<template v-else-if="!result.error">Nothing checked yet</template>
</p> </p>
<div class="bench-table-wrap"> <span class="grow" />
<button class="btn-sm" :disabled="!drives.length" title="A row for every combination of the drive columns" @click="combinations"><Icon name="lucide:grid-3x3" class="size-3.5" /> Every combination</button>
<button class="btn-sm" :disabled="!rows.length || !checks.length" title="Empty checks: what it reads now" @click="takeExpected"><Icon name="lucide:camera" class="size-3.5" /> Take what it does</button>
<button class="btn-sm" :disabled="!rows.length" title="Run again, longer runs allowed" @click="node && ed.runBenchNow(node.id, true)"><Icon name="lucide:play" class="size-3.5" /> Run</button>
</div>
<div v-if="cols.length" class="bench-table-wrap">
<table class="bench-table"> <table class="bench-table">
<thead> <thead>
<tr> <tr>
<th class="bench-num">#</th> <th class="bench-num">#</th>
<th v-for="c in cols.ins" :key="`i-${c.name}`" :title="c.keys.length > 1 ? `${c.keys.length} bits` : ''">{{ c.name }}<small v-if="c.keys.length > 1">{{ c.keys.length }}</small></th> <th v-for="c in drives" :key="c.id" :title="`${c.bits} bit${c.bits === 1 ? '' : 's'}`">{{ c.name }}</th>
<th class="bench-arrow">→</th> <th class="bench-arrow">→</th>
<th v-for="c in cols.outs" :key="`o-${c.name}`" class="out" :title="c.keys.length > 1 ? `${c.keys.length} bits` : ''">{{ c.name }}<small v-if="c.keys.length > 1">{{ c.keys.length }}</small></th> <th v-for="c in checks" :key="c.id" class="out" :title="`${c.bits} bit${c.bits === 1 ? '' : 's'}`">{{ c.name }}</th>
<th>Ticks</th> <th>Ticks</th>
<th /> <th />
</tr> </tr>
@ -134,19 +161,19 @@ function gotNote(i: number, name: string): string {
<tbody> <tbody>
<tr v-for="(row, i) in rows" :key="i" :class="result?.rows[i]?.ok === false ? 'fail' : result?.rows[i]?.ok ? 'pass' : ''"> <tr v-for="(row, i) in rows" :key="i" :class="result?.rows[i]?.ok === false ? 'fail' : result?.rows[i]?.ok ? 'pass' : ''">
<td class="bench-num tabular-nums">{{ i + 1 }}</td> <td class="bench-num tabular-nums">{{ i + 1 }}</td>
<td v-for="c in cols.ins" :key="`i-${c.name}`"> <td v-for="c in drives" :key="c.id">
<input :value="cellOf(row, 'set', c.name)" class="bench-cell" spellcheck="false" @change="setCell(i, 'set', c.name, ($event.target as HTMLInputElement).value)" /> <input :value="row.set?.[c.id] ?? ''" class="bench-cell" spellcheck="false" @change="setCell(i, 'set', c.id, ($event.target as HTMLInputElement).value)" />
</td> </td>
<td class="bench-arrow" :title="result?.rows[i]?.error ?? ''"> <td class="bench-arrow" :title="result?.rows[i]?.error ?? ''">
<Icon v-if="result?.rows[i]?.ok === false" name="lucide:x" class="size-3.5 text-(--danger)" /> <Icon v-if="result?.rows[i]?.ok === false" name="lucide:x" class="size-3.5 text-(--danger)" />
<Icon v-else-if="result?.rows[i]?.ok" name="lucide:check" class="size-3.5 text-(--on)" /> <Icon v-else-if="result?.rows[i]?.ok" name="lucide:check" class="size-3.5 text-(--on)" />
</td> </td>
<td v-for="c in cols.outs" :key="`o-${c.name}`" class="out"> <td v-for="c in checks" :key="c.id" class="out">
<input :value="cellOf(row, 'expect', c.name)" class="bench-cell" spellcheck="false" :placeholder="String(result?.rows[i]?.got[c.name] ?? '')" @change="setCell(i, 'expect', c.name, ($event.target as HTMLInputElement).value)" /> <input :value="row.expect?.[c.id] ?? ''" class="bench-cell" spellcheck="false" :placeholder="String(result?.rows[i]?.got[c.id] ?? '')" @change="setCell(i, 'expect', c.id, ($event.target as HTMLInputElement).value)" />
<span v-if="gotNote(i, c.name)" class="bench-got">{{ gotNote(i, c.name) }}</span> <span v-if="gotNote(i, c.id)" class="bench-got">{{ gotNote(i, c.id) }}</span>
</td> </td>
<td> <td>
<input :value="row.ticks ?? ''" class="bench-cell ticks" spellcheck="false" :placeholder="result?.rows[i]?.ticks ? String(result.rows[i]!.ticks) : ''" @change="setTicks(i, ($event.target as HTMLInputElement).value)" /> <input :value="row.ticks ?? ''" class="bench-cell" spellcheck="false" :placeholder="result?.rows[i]?.ticks ? String(result.rows[i]!.ticks) : ''" @change="setTicks(i, ($event.target as HTMLInputElement).value)" />
</td> </td>
<td class="bench-actions"> <td class="bench-actions">
<span v-if="result?.rows[i]?.error" class="bench-err" :title="result.rows[i]!.error">{{ result.rows[i]!.error }}</span> <span v-if="result?.rows[i]?.error" class="bench-err" :title="result.rows[i]!.error">{{ result.rows[i]!.error }}</span>
@ -157,8 +184,8 @@ function gotNote(i: number, name: string): string {
</tbody> </tbody>
</table> </table>
</div> </div>
<button class="btn-sm bench-add" @click="addRow()"><Icon name="lucide:plus" class="size-3.5" /> Row</button> <p v-else class="hint">Add columns first, or drop the bench on a component to get one for each of its pins.</p>
</template> <button v-if="cols.length" class="btn-sm bench-add" @click="addRow()"><Icon name="lucide:plus" class="size-3.5" /> Row</button>
</div> </div>
</div> </div>
</template> </template>

View File

@ -660,6 +660,8 @@ type Drag =
node: CircuitNode node: CircuitNode
toggle: boolean toggle: boolean
row?: PanelRow 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. */ /** How many parts were picked up (followers not counted): one part may snap to a pin a square away. */
grabbed: number grabbed: number
/** Pins of the parts staying put, and of the moving parts where they started; filled once the drag moves. */ /** 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, node,
toggle: (node.kind === 'input' || node.kind === 'keyboard' || !!row) && !multi, toggle: (node.kind === 'input' || node.kind === 'keyboard' || !!row) && !multi,
row, row,
benchHit: benchHitAt(target, node, multi),
grabbed: selected.value.has(id) ? ed.selection.value.length : 1, grabbed: selected.value.has(id) ? ed.selection.value.length : 1,
} }
return return
@ -1172,7 +1175,9 @@ function onPointerUp(e: PointerEvent) {
} else if (d.moved) { } else if (d.moved) {
ed.unplugMoved(new Set(d.orig.nodes.keys())) ed.unplugMoved(new Set(d.orig.nodes.keys()))
if (d.node.kind !== 'bench' || !ed.dropBench(d.node)) ed.commit(false) 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 && d.node.kind === 'keyboard') ed.typeInto(d.node.id)
else if (d.toggle) ed.toggleInput(d.node) else if (d.toggle) ed.toggleInput(d.node)
break 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) { function onDoubleClick(node: CircuitNode) {
if (node.kind === 'chip' && node.chip) ed.open(node.chip) if (node.kind === 'chip' && node.chip) ed.open(node.chip)
else if (node.kind === 'bench') ed.benchOpen.value = node.id else if (node.kind === 'bench') ed.benchOpen.value = node.id

View File

@ -3,6 +3,7 @@ import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables' import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide' 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 { 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 { keyLabel, TERMINAL_COLS, TERMINAL_LINES } from '~/lib/logic/devices'
import type { CircuitNode } from '~/lib/logic/types' 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). */ /** 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 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')) : '')) const rgbNow = computed(() => (props.node.rgb ? rgbHex(v('r'), v('g'), v('b')) : ''))
// Test bench: its target and the last run. // Test bench: the layout of its box, its rows and how they went.
const benchSum = computed(() => { interface BenchRowView {
if (props.node.kind !== 'bench') return { title: '', line: '', state: '' } i: number
const target = ed.benchTarget(props.node) state: string
const title = target ? `Tests: ${target.def.name}` : 'Test bench' live: boolean
const rows = props.node.bench?.rows.length ?? 0 cells: { key: string; x: number; text: string; cls: string }[]
const r = props.ghost ? undefined : ed.benchResults.value.get(props.node.id) title: string
if (!target) return { title, line: 'drop on a component', state: 'idle' } }
if (!rows) return { title, line: 'no tests yet: double-click', state: 'idle' } const bl = computed(() => benchLayout(props.node))
if (!r) return { title, line: `${rows} tests`, state: 'idle' } const benchTitleW = computed(() => ((props.node.label?.trim() || 'Test bench').length * 6.4 + 10))
if (r.error && !r.fail) return { title, line: r.error, state: 'fail' } const bench = computed(() => {
if (r.fail) return { title, line: `✗ ${r.fail} failing, ${r.pass} pass`, state: 'fail' } const n = props.node
return { title, line: r.pass ? `✓ all ${r.pass} pass` : `${rows} rows, nothing checked`, state: r.pass ? 'pass' : 'idle' } 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. // Terminal and keyboard: what the store keeps for this part.
@ -436,11 +462,28 @@ const title = computed(() => {
<text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text> <text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text>
</template> </template>
<!-- Test bench: how the tests of the component it is docked to went --> <!-- Test bench: its table on the box, run button in the title bar -->
<template v-else-if="node.kind === 'bench'"> <template v-else-if="node.kind === 'bench'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body bench-body" :class="benchSum.state" /> <rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="4" class="body bench-body" :class="bench.state" />
<text :x="0.5 * G" :y="0.15 * G" class="bench-title">{{ benchSum.title }}</text> <text :x="bl.x * G + 2" :y="0.45 * G" class="bench-title">{{ node.label?.trim() || 'Test bench' }}</text>
<text :x="0.5 * G" :y="1.05 * G" class="bench-line" :class="benchSum.state">{{ benchSum.line }}</text> <text :x="bl.x * G + 2 + benchTitleW" :y="0.45 * G" class="bench-line" :class="bench.state">{{ bench.line }}</text>
<g v-if="bench.cols" data-bench-run class="bench-run" :transform="`translate(${(bench.right - 0.75) * G} ${0.2 * G})`">
<title>Run the tests</title>
<circle r="7" />
<path d="M-2.2 -3.6 L3.8 0 L-2.2 3.6 Z" />
</g>
<template v-if="bench.cols">
<text v-for="c in bl.cols" :key="c.key" :x="(c.x + 0.25) * G" :y="(bl.top + 0.72) * G" class="bench-head" :class="{ drive: c.drive }">{{ c.head }}</text>
<g v-for="r in bench.rows" :key="r.i" :data-bench-row="r.i" class="bench-row" :class="[r.state, { live: r.live }]">
<title>{{ r.title }}</title>
<rect :x="bl.x * G" :y="(bl.top + 1 + r.i) * G + 0.5" :width="bl.tableW * G" :height="G - 1" rx="2" class="bench-row-bg" />
<text v-for="c in r.cells" :key="c.key" :x="(c.x + 0.25) * G" :y="(bl.top + 1.72 + r.i) * G" class="bench-cell-text" :class="c.cls">{{ c.text }}</text>
</g>
<text v-if="bl.more" :x="bl.x * G + 4" :y="(bl.top + 1.72 + bl.shown) * G" class="bench-line">+ {{ bl.more }} more rows (double-click)</text>
</template>
<text v-else :x="bl.x * G + 2" :y="(bl.top + 0.8) * G" class="bench-line">Drop on a component, or double-click to set up</text>
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 4" :y="p.dy * G + 3" text-anchor="end" class="pin-label tiny">{{ p.label }}</text>
</template> </template>
<!-- Terminal: a text screen the circuit writes to --> <!-- Terminal: a text screen the circuit writes to -->

View File

@ -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 { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { probeValue } from '~/lib/logic/probes' import { probeValue } from '~/lib/logic/probes'
import { bitsCode, codeBits, DATA_KEYS, KEY_QUEUE, putChar } from '~/lib/logic/devices' 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 { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' 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' 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() { function rebuild() {
const d = def.value 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 nl = compile(getDef.value, d.id)
const key = `${meta.value.id}/${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. // 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() 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) devTerms = d.nodes.filter(n => n.kind === 'terminal').map(n => n.id)
devKbs = d.nodes.filter(n => n.kind === 'keyboard').map(n => n.id) devKbs = d.nodes.filter(n => n.kind === 'keyboard').map(n => n.id)
if (!devKbs.includes(typingInto.value ?? '')) typingInto.value = null 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 === '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 === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows()
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4 if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
if (p.kind === 'bench') { if (p.kind === 'bench') node.bench = { cols: [], rows: [] }
node.bench = { rows: [] }
// Dropped on (or next to) a component: docks below it.
const chip = benchSpot(node)
if (chip) dockAt(node, chip)
}
// A new pixel is like the one placed last: building a colour screen, every pixel comes in colour. // 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 if (p.kind === 'pixel' && def.value.nodes.findLast(n => n.kind === 'pixel')?.rgb) node.rgb = true
def.value.nodes.push(node) 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) rememberPart(p.kind, p.chip)
const swap = (r: PinRef) => (r.node === 'ghost' ? { node: node.id, pin: r.pin } : r) 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 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; ) { for (let size = -1; size !== set.size; ) {
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 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 return set
} }
@ -1448,9 +1452,11 @@ function create() {
const benchResults = shallowRef(new Map<string, BenchResult>()) const benchResults = shallowRef(new Map<string, BenchResult>())
/** The bench whose tests are open in the dialog. */ /** The bench whose tests are open in the dialog. */
const benchOpen = ref<string | null>(null) const benchOpen = ref<string | null>(null)
/** The row each bench applies to the running circuit (none: its outputs are 0). */
const benchLive = shallowRef(new Map<string, number>())
let benchTimer: ReturnType<typeof setTimeout> | undefined let benchTimer: ReturnType<typeof setTimeout> | 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 { function benchSpot(bench: CircuitNode): CircuitNode | undefined {
const own = shapeOf(bench, getDef.value).body const own = shapeOf(bench, getDef.value).body
const x = bench.x + own.x + own.w / 2 const x = bench.x + own.x + own.w / 2
@ -1458,7 +1464,7 @@ function create() {
let best: CircuitNode | undefined let best: CircuitNode | undefined
let bestD = 2.01 let bestD = 2.01
for (const n of def.value.nodes) { 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 b = shapeOf(n, getDef.value).body
const dx = Math.max(n.x + b.x - x, 0, x - (n.x + b.x + b.w)) 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)) 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 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 const b = shapeOf(chip, getDef.value).body
bench.bench = { rows: bench.bench?.rows ?? [], on: chip.id } bench.x = chip.x + b.x - own.w - 6
bench.x = chip.x + b.x bench.y = chip.y
bench.y = Math.ceil(chip.y + b.y + b.h + 1.5) for (const w of wires) addWire(w.from, w.to)
}
/** 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'}`)
return true return true
} }
/** Docks a bench to a component of this circuit (or undocks it) and runs its tests. */ /** A bench let go after a drag: an empty one onto a component is set up for it. */
function dockBench(id: string, chipId: string | null) { function dropBench(bench: CircuitNode) {
const n = def.value.nodes.find(x => x.id === id) const chip = benchSpot(bench)
const chip = chipId ? def.value.nodes.find(x => x.id === chipId && x.kind === 'chip') : undefined if (!chip || !benchOnto(bench, chip)) return false
if (!n?.bench) return commit()
if (chip) dockAt(n, chip)
else delete n.bench.on
commit(false)
scheduleBenches() scheduleBenches()
} notify(`Wired to ${getDef.value(chip.chip ?? '')?.name ?? 'the component'}: a column for each of its pins`)
return true
/** 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
} }
/** Runs a bench's tests now; by hand they may run longer. */ /** Runs a bench's tests now; by hand they may run longer. */
function runBenchNow(id: string, byHand = false) { function runBenchNow(id: string, byHand = false) {
const n = def.value.nodes.find(x => x.id === id) if (!def.value.nodes.some(x => x.id === id && x.kind === 'bench')) return
if (!n?.bench) return const res = runBench(getDef.value, def.value.id, id, byHand ? HAND_TICKS : AUTO_TICKS)
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' }
benchResults.value.set(id, res) benchResults.value.set(id, res)
benchResults.value = new Map(benchResults.value) benchResults.value = new Map(benchResults.value)
if (byHand) play(res.fail || res.error ? 'error' : 'connect') if (byHand) play(res.fail || res.error ? 'error' : 'connect')
@ -1530,15 +1521,48 @@ function create() {
}, 300) }, 300)
} }
/** Changes a bench's tests (an undo step) and runs them again. */ /** Changes a bench (an undo step) and runs it again; columns change its pins. */
function setBench(id: string, change: (b: Bench) => void) { function setBench(id: string, change: (b: Bench) => void, structural = false) {
const n = def.value.nodes.find(x => x.id === id) const n = def.value.nodes.find(x => x.id === id)
if (!n?.bench) return if (!n?.bench) return
change(n.bench) change(n.bench)
commit(false) commit(structural)
scheduleBenches() scheduleBenches()
} }
/** 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 ───────────────────────────────────────────────────── // ── Assembler ─────────────────────────────────────────────────────
/** The assembler's texts, kept in the project (not undo steps). */ /** The assembler's texts, kept in the project (not undo steps). */
const asmDoc = computed<AsmDoc>(() => project.value.asm ?? { ...ASM_EXAMPLE }) const asmDoc = computed<AsmDoc>(() => project.value.asm ?? { ...ASM_EXAMPLE })
@ -3114,10 +3138,10 @@ function create() {
setRgb, setRgb,
benchResults, benchResults,
benchOpen, benchOpen,
benchTarget, applyBenchRow,
benchLive,
runBenchNow, runBenchNow,
setBench, setBench,
dockBench,
dropBench, dropBench,
screens, screens,
keyQueues, keyQueues,

View File

@ -149,7 +149,7 @@ export function useMenu() {
} }
if (n.kind === 'bench') { if (n.kind === 'bench') {
out.push( 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) }, { label: 'Run the tests', icon: 'lucide:play', run: () => ed.runBenchNow(n.id, true) },
) )
} }

View File

@ -62,7 +62,7 @@ export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
kind: 'bench', kind: 'bench',
name: 'Test bench', name: 'Test bench',
icon: 'lucide:flask-conical', 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', aka: 'test truth table check verify unit',
}, },
], ],

View File

@ -1,30 +1,27 @@
// Test benches: a table of tests docked to a placed component. Each row sets // Test benches: a part with a table of tests. Its drive columns are output
// its inputs, gives it clock ticks if asked, and checks its outputs. The // pins it sets, its check columns input pins it reads; wire them to whatever
// component runs on its own (no wires to the circuit around it), from all // is tested. Each row sets the drive columns, gives the circuit clock ticks
// zeros, its state carried from row to row, so a row can test memory, a // if asked, and checks what comes back. A run takes the whole circuit the
// counter, or a whole computer running until it is done. // 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 // A drive cell is a number (12, 0x0C, 0b1100), P for a clock pulse, or empty
// number (12, 0x0C, 0b1100), P for a clock pulse, or empty to leave it as // to leave it as it was. A check cell is the number it should read, empty
// it was. An output cell is the number it should show, empty for any. // for any. Ticks: N pulses (the P columns and the circuit's own clocks)
// Ticks: N pulses (the P inputs and the component's own clocks) before the // before the check; ≤N gives up to N, checking after each, until it matches.
// check; ≤N gives up to N, checking after each, until the outputs match.
import { compile } from './compile' import { compile, rowSource } from './compile'
import { colKeys, colPinNames } from './benchLayout'
import { chipPins, type DefLookup } from './geometry' import { chipPins, type DefLookup } from './geometry'
import { uid } from './ops'
import { Simulator } from './sim' import { Simulator } from './sim'
import type { Bench, BenchRow, ComponentDef } from './types' import type { Bench, BenchCol, BenchRow, CircuitNode, ComponentDef } from './types'
export interface BenchColumn {
name: string
/** Pin keys, bit 0 first. */
keys: string[]
}
export interface RowResult { export interface RowResult {
/** True all checks hold, false one does not, null nothing to check. */ /** True all checks hold, false one does not, null nothing to check. */
ok: boolean | null ok: boolean | null
/** Outputs after the row, by column. */ /** What the check columns read after the row, by column id. */
got: Record<string, number> got: Record<string, number>
/** Ticks the row ran. */ /** Ticks the row ran. */
ticks: number ticks: number
@ -39,61 +36,33 @@ export interface BenchResult {
} }
const SETTLE = 2_000_000 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 AUTO_TICKS = 20_000
export const HAND_TICKS = 500_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 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 const driveCols = (b: Bench | undefined) => (b?.cols ?? []).filter(c => c.dir === 'drive')
export function groupPins(pins: { key: string; label: string }[]): BenchColumn[] { export const checkCols = (b: Bench | undefined) => (b?.cols ?? []).filter(c => c.dir === 'check')
const series = new Map<string, Map<number, string>>()
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<number, string>()
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<string>()
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 function benchColumns(def: ComponentDef): { ins: BenchColumn[]; outs: BenchColumn[] } { /** A cell as a number, P (drive columns only), or null when empty or a don't-care. */
const pins = chipPins(def) export function parseCell(s: string | undefined, bits: number, drive: boolean): number | 'P' | null | { error: string } {
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 } {
const t = (s ?? '').trim() const t = (s ?? '').trim()
if (!t || t === '-' || t.toLowerCase() === 'x') return null 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 let v: number
if (/^\d+$/.test(t)) v = parseInt(t, 10) 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 (/^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 (/^0b[01]+$/i.test(t)) v = parseInt(t.slice(2), 2)
else if (/^-\d+$/.test(t)) v = 2 ** bits + parseInt(t, 10) 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'}` } if (v < 0 || v >= 2 ** bits) return { error: `${t} does not fit in ${bits} bit${bits === 1 ? '' : 's'}` }
return v 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 } { export function parseTicks(s: string | undefined): { n: number; wait: boolean } | null | { error: string } {
const t = (s ?? '').trim() const t = (s ?? '').trim()
if (!t) return null if (!t) return null
@ -104,18 +73,31 @@ export function parseTicks(s: string | undefined): { n: number; wait: boolean }
return { n, wait: !!m[1] } return { n, wait: !!m[1] }
} }
/** Runs a bench's rows on the component, in order. */ /** Sets the circuit's own switches the way they stand (buttons up, keyboards empty). */
export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], maxTicks = AUTO_TICKS): BenchResult { export function setSwitches(sim: Simulator, def: ComponentDef) {
const def = getDef(defId) 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 } const res: BenchResult = { rows: [], pass: 0, fail: 0 }
if (!def) return { ...res, error: 'The component it tests no longer exists' } if (!def || !bench) return { ...res, error: 'The bench is gone' }
const cols = benchColumns(def) const drives = driveCols(bench)
const sim = new Simulator(compile(getDef, defId)) 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) sim.run(SETTLE)
const clocks = sim.nl.clocks.length > 0 const clocks = sim.nl.clocks.length > 0
let left = maxTicks let left = maxTicks
const read = (c: BenchColumn) => c.keys.reduce((v, k, i) => v + (sim.output(k) ? 2 ** i : 0), 0) const put = (c: BenchCol, v: number) => colKeys(c).forEach((k, i) => sim.setSource(`${benchId}:${k}`, Math.floor(v / 2 ** i) % 2 === 1))
for (const row of rows) { 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 } const out: RowResult = { ok: null, got: {}, ticks: 0 }
res.rows.push(out) res.rows.push(out)
const fail = (error: string) => { const fail = (error: string) => {
@ -123,22 +105,22 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
out.error = error out.error = error
res.fail++ res.fail++
} }
// Inputs, pulses held low for now. // Drive columns; pulses held low for now.
const pulses: BenchColumn[] = [] const pulses: BenchCol[] = []
let bad = '' let bad = ''
for (const c of cols.ins) { for (const c of drives) {
const v = parseCell(row.set?.[c.name], c.keys.length, true) const v = parseCell(row.set?.[c.id], c.bits, true)
if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}` if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}`
else if (v === 'P') { else if (v === 'P') {
pulses.push(c) pulses.push(c)
c.keys.forEach(k => sim.setSource(k, false)) put(c, 0)
} else if (v !== null) c.keys.forEach((k, i) => sim.setSource(k, Math.floor(v / 2 ** i) % 2 === 1)) } else if (v !== null) put(c, v)
} }
const checks: { c: BenchColumn; want: number }[] = [] const want: { c: BenchCol; v: number }[] = []
for (const c of cols.outs) { for (const c of checks) {
const v = parseCell(row.expect?.[c.name], c.keys.length, false) const v = parseCell(row.expect?.[c.id], c.bits, false)
if (v && typeof v === 'object') bad ||= `${c.name}: ${v.error}` 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) const ticks = parseTicks(row.ticks)
if (ticks && 'error' in ticks) bad ||= ticks.error 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 } const spec = (ticks as { n: number; wait: boolean } | null) ?? { n: pulses.length ? 1 : 0, wait: false }
if (spec.n && !pulses.length && !clocks) { 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 continue
} }
if (!sim.run(SETTLE)) { if (!sim.run(SETTLE)) {
fail('It oscillates and never settles') fail('It oscillates and never settles')
continue continue
} }
const matches = () => checks.every(({ c, want }) => read(c) === want) const matches = () => want.every(({ c, v }) => read(c) === v)
const tick = (): boolean => { 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 (clocks) sim.setClock(1)
if (!sim.run(SETTLE)) return false 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) if (clocks) sim.setClock(0)
return sim.run(SETTLE) return sim.run(SETTLE)
} }
let stopped = '' let stopped = ''
for (let t = 0; t < spec.n; t++) { 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) { if (left-- <= 0) {
stopped = `Stopped after ${maxTicks.toLocaleString('en')} ticks in all` stopped = `Stopped after ${maxTicks.toLocaleString('en')} ticks in all`
break break
@ -177,7 +159,7 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
} }
out.ticks++ 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) { if (stopped) {
fail(stopped) fail(stopped)
if (left <= 0) { if (left <= 0) {
@ -186,7 +168,7 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
} }
continue continue
} }
if (!checks.length) continue if (!want.length) continue
out.ok = matches() out.ok = matches()
if (out.ok) res.pass++ if (out.ok) res.pass++
else { else {
@ -197,21 +179,20 @@ export function runBench(getDef: DefLookup, defId: string, rows: BenchRow[], max
return res return res
} }
/** Every combination of the inputs, counting up (the first column the highest), outputs left to fill. */ /** Every combination of the drive columns, counting up (the first column the highest). */
export function combinationRows(def: ComponentDef): BenchRow[] | { error: string } { export function combinationRows(bench: Bench): BenchRow[] | { error: string } {
const { ins } = benchColumns(def) const drives = driveCols(bench)
const bits = ins.reduce((n, c) => n + c.keys.length, 0) const bits = drives.reduce((n, c) => n + c.bits, 0)
if (!ins.length) return { error: 'It has no inputs' } if (!drives.length) return { error: 'Add a drive column first' }
if (bits > MAX_COMBO_BITS) return { error: `${bits} input bits are ${2 ** bits} combinations: at most ${MAX_COMBO_BITS} bits` } if (bits > MAX_COMBO_BITS) return { error: `${bits} drive bits are ${2 ** bits} combinations: at most ${MAX_COMBO_BITS} bits` }
const rows: BenchRow[] = [] const rows: BenchRow[] = []
for (let i = 0; i < 2 ** bits; i++) { for (let i = 0; i < 2 ** bits; i++) {
let rest = i let rest = i
const set: Record<string, string> = {} const set: Record<string, string> = {}
for (let k = ins.length - 1; k >= 0; k--) { for (let k = drives.length - 1; k >= 0; k--) {
const c = ins[k]! const c = drives[k]!
const n = 2 ** c.keys.length set[c.id] = String(rest % 2 ** c.bits)
set[c.name] = String(rest % n) rest = Math.floor(rest / 2 ** c.bits)
rest = Math.floor(rest / n)
} }
rows.push({ set }) 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 * The rows with what the circuit reads now in their empty check cells (to
* (to keep it working the same). Outputs already filled in stay as they are, * keep it working the same). Cells already filled in stay, so a row that
* so a row that waits for them waits the same. * waits for them waits the same.
*/ */
export function recordExpected(getDef: DefLookup, defId: string, rows: BenchRow[]): BenchRow[] { export function recordExpected(r: BenchResult, rows: BenchRow[]): BenchRow[] {
const r = runBench(getDef, defId, rows, HAND_TICKS)
return rows.map((row, i) => { return rows.map((row, i) => {
const got = r.rows[i]?.got const res = r.rows[i]
if (!got || (r.rows[i]?.error && r.rows[i]?.ok !== false)) return row if (!res || (res.error && res.ok !== false)) return row
const expect = { ...row.expect } 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 } return { ...row, expect }
}) })
} }
/** A bench cell's value for a column, by name. */ // ── Columns for a component ──────────────────────────────────────────
export const cellOf = (row: BenchRow, side: 'set' | 'expect', name: string) => row[side]?.[name] ?? ''
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<string, Map<number, string>>()
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<number, string>()
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<string>()
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<string, string> | 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 })
}
}

View File

@ -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<BenchCell, 'x'>[] = [{ 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 }
}

View File

@ -3,6 +3,7 @@
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH. // 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 { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry'
import { colKeys } from './benchLayout'
import { DATA_KEYS } from './devices' import { DATA_KEYS } from './devices'
import type { CircuitNode, ComponentDef, Wire } from './types' 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'] return [...DATA_KEYS, 'wr', 'clr']
case 'keyboard': case 'keyboard':
return ['next'] return ['next']
case 'bench':
return (node.bench?.cols ?? []).filter(c => c.dir === 'check').flatMap(colKeys)
case 'outpanel': case 'outpanel':
return (node.rows ?? []).map(r => r.id) return (node.rows ?? []).map(r => r.id)
case 'bundle': case 'bundle':
@ -98,6 +101,8 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
return ['q0', 'q1', 'q2', 'q3'] return ['q0', 'q1', 'q2', 'q3']
case 'keyboard': case 'keyboard':
return [...DATA_KEYS, 'rdy'] return [...DATA_KEYS, 'rdy']
case 'bench':
return (node.bench?.cols ?? []).filter(c => c.dir === 'drive').flatMap(colKeys)
case 'panel': case 'panel':
case 'outpanel': case 'outpanel':
return (node.rows ?? []).map(r => r.id) return (node.rows ?? []).map(r => r.id)
@ -254,8 +259,9 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
case 'button': case 'button':
if (!inNets) sources.set(n.id, q) if (!inNets) sources.set(n.id, q)
break break
case 'bench':
case 'keyboard': 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}`)!) if (!inNets) for (const k of outputKeys(n)) sources.set(`${n.id}:${k}`, outNet.get(`${n.id}:${k}`)!)
break break
case 'high': case 'high':

View File

@ -2,6 +2,7 @@
// (x, y). Pins always sit on whole grid points so straight wires line up. // (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 type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
import { benchLayout } from './benchLayout'
import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices' import { DATA_KEYS, DEVICE_PIN_NAMES } from './devices'
export const GRID = 16 export const GRID = 16
@ -727,7 +728,14 @@ const TERMINAL_SHAPE: Shape = {
outputs: [], 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 = { const KEYBOARD_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 7, h: 9 }, body: { x: 0, y: -0.5, w: 7, h: 9 },
@ -834,7 +842,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
case 'terminal': case 'terminal':
return TERMINAL_SHAPE return TERMINAL_SHAPE
case 'bench': case 'bench':
return BENCH_SHAPE return benchShape(node)
case 'keyboard': case 'keyboard':
return KEYBOARD_SHAPE return KEYBOARD_SHAPE
case 'outpanel': case 'outpanel':

View File

@ -3,6 +3,7 @@
// name of the component pin it is wired to. // name of the component pin it is wired to.
import { chipPins, splitLines, type DefLookup } from './geometry' import { chipPins, splitLines, type DefLookup } from './geometry'
import { colPinNames } from './benchLayout'
import { DEVICE_PIN_NAMES } from './devices' import { DEVICE_PIN_NAMES } from './devices'
import type { CircuitNode, ComponentDef, NodeKind } from './types' 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). // 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 === '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 === '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 if (node.kind !== 'chip' || !node.chip) return undefined
const def = get(node.chip) const def = get(node.chip)
// A line of a port split on the box: port.line, named after the line. // A line of a port split on the box: port.line, named after the line.

View File

@ -264,11 +264,6 @@ function redock(nodes: CircuitNode[], ids: Map<string, string>) {
if (to) n[k] = to if (to) n[k] = to
else delete n[k] 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 if (!n.attach) continue
const to = ids.get(n.attach) const to = ids.get(n.attach)
if (to) n.attach = to if (to) n.attach = to

View File

@ -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) 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 if (!b || typeof b !== 'object' || !Array.isArray(b.rows)) delete n.bench
else { 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 = { n.bench = {
...(typeof b.on === 'string' ? { on: b.on } : {}), ...(typeof b.on === 'string' ? { on: b.on } : {}),
...(cols ? { cols } : {}),
rows: b.rows.slice(0, 4096).filter(r => r && typeof r === 'object').map(r => ({ rows: b.rows.slice(0, 4096).filter(r => r && typeof r === 'object').map(r => ({
...(cells(r.set) ? { set: cells(r.set) } : {}), ...(cells(r.set) ? { set: cells(r.set) } : {}),
...(cells(r.expect) ? { expect: cells(r.expect) } : {}), ...(cells(r.expect) ? { expect: cells(r.expect) } : {}),

View File

@ -24,7 +24,7 @@ export type BuiltinKind =
| 'ref' // carries the signal of the tag with the same name in this circuit, without a wire | '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 | '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 | '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' export type NodeKind = BuiltinKind | 'chip'
@ -87,15 +87,26 @@ export interface CircuitNode {
/** A test bench (see lib/logic/bench). */ /** A test bench (see lib/logic/bench). */
export interface Bench { export interface Bench {
/** The placed component it is docked to (a chip node in the same circuit). */ /** Its columns: each a group of pins, as many bits as it has. */
on?: string cols?: BenchCol[]
rows: BenchRow[] 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 { 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<string, string> set?: Record<string, string>
/** 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<string, string> expect?: Record<string, string>
/** N ticks before the check, or ≤N to wait up to N. */ /** N ticks before the check, or ≤N to wait up to N. */
ticks?: string ticks?: string

View File

@ -1,95 +1,97 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { benchColumns, combinationRows, groupPins, parseCell, parseTicks, recordExpected, runBench } from '../app/lib/logic/bench' import { benchFor, checkCols, combinationRows, driveCols, groupPins, parseCell, parseTicks, recordExpected, runBench, upgradeBenches } from '../app/lib/logic/bench'
import { createProject, lookup } from '../app/lib/logic/ops' import { benchLayout } from '../app/lib/logic/benchLayout'
import type { Project } from '../app/lib/logic/types' 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). */ /** A circuit with one placed example component and a bench wired to all its pins. */
function project(): Project { function rig(chipId: string): { p: Project; def: ComponentDef; bench: CircuitNode } {
return createProject({ examples: true }) 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', () => { describe('test bench cells', () => {
it('A0…An make one number column; other pins stay single', () => { it('A0…An make one group; other pins stay single', () => {
const cols = groupPins([ expect(groupPins([{ key: 'a1', label: 'A1' }, { key: 'a0', label: 'A0' }, { key: 'c', label: 'Cin' }, { key: 'x2', label: 'X2' }])).toEqual([
{ key: 'a1', label: 'A1' },
{ key: 'a0', label: 'A0' },
{ key: 'c', label: 'Cin' },
{ key: 'x2', label: 'X2' },
])
expect(cols).toEqual([
{ name: 'A', keys: ['a0', 'a1'] }, { name: 'A', keys: ['a0', 'a1'] },
{ name: 'Cin', keys: ['c'] }, { name: 'Cin', keys: ['c'] },
{ name: 'X2', keys: ['x2'] }, { name: 'X2', keys: ['x2'] },
]) ])
}) })
it('cells: numbers in three bases, P, don’t care, and what does not fit', () => { it('numbers in three bases, P, don’t care, what does not fit; ticks', () => {
expect(parseCell('12', 4, true)).toBe(12)
expect(parseCell('0x0C', 4, true)).toBe(12) expect(parseCell('0x0C', 4, true)).toBe(12)
expect(parseCell('0b1100', 4, true)).toBe(12) expect(parseCell('0b1100', 4, true)).toBe(12)
expect(parseCell('-1', 4, false)).toBe(15) expect(parseCell('-1', 4, false)).toBe(15)
expect(parseCell('p', 1, true)).toBe('P') expect(parseCell('p', 1, true)).toBe('P')
expect(parseCell('', 1, false)).toBeNull()
expect(parseCell('x', 1, false)).toBeNull() expect(parseCell('x', 1, false)).toBeNull()
expect(parseCell('16', 4, true)).toHaveProperty('error') expect(parseCell('16', 4, true)).toHaveProperty('error')
expect(parseCell('P', 1, false)).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('≤100')).toEqual({ n: 100, wait: true })
expect(parseTicks('<= 7')).toEqual({ n: 7, wait: true })
expect(parseTicks('soon')).toHaveProperty('error') expect(parseTicks('soon')).toHaveProperty('error')
}) })
}) })
describe('running a test bench', () => { describe('a wired test bench', () => {
it('a truth table: every combination, recorded, then passing; a wrong row fails', () => { it('has pins: check columns on the left, drive columns on the right', () => {
const p = project() const { p, bench } = rig('ex-ha')
const ha = p.components.find(c => c.id === 'ex-ha')! const shape = shapeOf(bench, lookup(p))
const rows = combinationRows(ha) 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) if ('error' in rows) throw new Error(rows.error)
expect(rows.length).toBe(4) expect(rows.length).toBe(4)
const filled = recordExpected(lookup(p), ha.id, rows) bench.bench!.rows = rows
const r = runBench(lookup(p), ha.id, filled) bench.bench!.rows = recordExpected(runBench(lookup(p), 'rig', 'tb'), rows)
expect(r).toMatchObject({ pass: 4, fail: 0 }) // Half adder, A B → S C: 1 + 1 is S 0, C 1.
const cols = benchColumns(ha) const last = bench.bench!.rows[3]!
const outName = cols.outs[0]!.name expect([last.expect![col(bench, 'S')], last.expect![col(bench, 'C')]]).toEqual(['0', '1'])
// Filled cells stay: taking again changes nothing. expect(runBench(lookup(p), 'rig', 'tb')).toMatchObject({ pass: 4, fail: 0 })
expect(recordExpected(lookup(p), ha.id, filled)).toEqual(filled) last.expect![col(bench, 'C')] = '0'
filled[3] = { ...filled[3], expect: { ...filled[3]!.expect, [outName]: filled[3]!.expect![outName] === '1' ? '0' : '1' } } const r = runBench(lookup(p), 'rig', 'tb')
const r2 = runBench(lookup(p), ha.id, filled) expect(r.fail).toBe(1)
expect(r2.fail).toBe(1) expect(r.rows[3]).toMatchObject({ ok: false })
expect(r2.rows[3]!.ok).toBe(false)
}) })
it('a counter: pulses, ticks, and waiting until it gets there', () => { it('a counter: pulses, ticks, and waiting until it gets there', () => {
const p = project() const { p, bench } = rig('ex-cnt4')
const counter = p.components.find(c => c.id === 'ex-cnt4')! const clk = col(bench, 'CLK')
const { ins, outs } = benchColumns(counter) const q = col(bench, 'Q')
const clk = ins.find(c => /clk/i.test(c.name))!.name bench.bench!.rows = [{ set: { [clk]: 'P' } }, { set: { [clk]: 'P' }, ticks: '2' }, { set: { [clk]: 'P' }, ticks: '≤50', expect: { [q]: '9' } }]
const rst = ins.find(c => /r/i.test(c.name) && c.name !== clk)?.name const r = runBench(lookup(p), 'rig', 'tb')
const q = outs[0]! expect(r.rows[1]!.got[q]).toBe(3)
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)
expect(r.rows[2]).toMatchObject({ ok: true, ticks: 6 }) expect(r.rows[2]).toMatchObject({ ok: true, ticks: 6 })
// Too few ticks to get there. bench.bench!.rows = [{ set: { [clk]: 'P' }, ticks: '≤3', expect: { [q]: '9' } }]
const r2 = runBench(lookup(p), counter.id, [{ set: { [clk]: 'P' }, ticks: '≤3', expect: { [q.name]: '9' } }]) expect(runBench(lookup(p), 'rig', 'tb').rows[0]).toMatchObject({ ok: false, error: 'Not within 3 ticks' })
expect(r2.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', () => { it('a bench from the first version (docked, keyed by names) gets columns and wires', () => {
const p = project() const p = createProject({ examples: true })
const counter = p.components.find(c => c.id === 'ex-cnt4')! const chip: CircuitNode = { id: 'u', kind: 'chip', chip: 'ex-ha', x: 20, y: 0 }
const clk = benchColumns(counter).ins.find(c => /clk/i.test(c.name))!.name 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 r = runBench(lookup(p), counter.id, [{ set: { [clk]: 'P' }, ticks: '100' }], 10) const def: ComponentDef = { id: 'rig', name: 'Rig', symbol: 'box', nodes: [old, chip], wires: [] }
expect(r.error).toMatch(/Stopped after 10 ticks/) p.components.push(def)
const r2 = runBench(lookup(p), counter.id, [{ set: { [clk]: 'nope' } }]) upgradeBenches(def, lookup(p))
expect(r2.rows[0]!.error).toMatch(/not a number/) 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 })
}) })
}) })