183 lines
6.7 KiB
TypeScript
183 lines
6.7 KiB
TypeScript
// Analysis on a compiled component: truth table, NAND count, gate delay,
|
|
// and step-by-step tests (used by challenges).
|
|
|
|
import { compile, type Netlist } from './compile'
|
|
import { chipPins, type DefLookup } from './geometry'
|
|
import { Simulator } from './sim'
|
|
import type { ComponentDef } from './types'
|
|
|
|
const SETTLE_BUDGET = 2_000_000
|
|
|
|
export interface TruthRow {
|
|
ins: number[]
|
|
outs: number[]
|
|
/** False when the circuit kept oscillating for this input. */
|
|
settled: boolean
|
|
}
|
|
|
|
export interface TruthTable {
|
|
inputs: string[]
|
|
outputs: string[]
|
|
rows: TruthRow[]
|
|
}
|
|
|
|
export const MAX_TABLE_INPUTS = 10
|
|
|
|
export function truthTable(getDef: DefLookup, defId: string): TruthTable | { error: string } {
|
|
const def = getDef(defId)
|
|
if (!def) return { error: 'Component not found' }
|
|
const pins = chipPins(def)
|
|
const n = pins.inputs.length
|
|
if (n > MAX_TABLE_INPUTS) return { error: `Too many inputs for a table (${n}, max ${MAX_TABLE_INPUTS})` }
|
|
if (pins.outputs.length === 0) return { error: 'Add at least one output pin' }
|
|
const sim = new Simulator(compile(getDef, defId))
|
|
sim.run(SETTLE_BUDGET)
|
|
const rows: TruthRow[] = []
|
|
for (let i = 0; i < 1 << n; i++) {
|
|
const ins = pins.inputs.map((_, k) => (i >> (n - 1 - k)) & 1)
|
|
pins.inputs.forEach((p, k) => sim.setSource(p.key, ins[k] === 1))
|
|
const settled = sim.run(SETTLE_BUDGET)
|
|
rows.push({ ins, outs: pins.outputs.map(p => sim.pin(p.key, 'a')), settled })
|
|
}
|
|
return { inputs: pins.inputs.map(p => p.label), outputs: pins.outputs.map(p => p.label), rows }
|
|
}
|
|
|
|
const cell = (r: TruthRow, v: number) => (r.settled ? String(v) : '~')
|
|
|
|
/** Comma-separated, for spreadsheets. A row that never settled shows ~ for its outputs. */
|
|
export function tableCsv(t: TruthTable): string {
|
|
const quote = (s: string) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s)
|
|
const lines = [[...t.inputs, ...t.outputs].map(quote).join(',')]
|
|
for (const r of t.rows) lines.push([...r.ins.map(String), ...r.outs.map(v => cell(r, v))].join(','))
|
|
return `${lines.join('\n')}\n`
|
|
}
|
|
|
|
/** Markdown table, which also reads fine as plain text. */
|
|
export function tableMarkdown(t: TruthTable): string {
|
|
const esc = (s: string) => s.replace(/\|/g, '\\|')
|
|
const head = [...t.inputs, ...t.outputs].map(esc)
|
|
const lines = [`| ${head.join(' | ')} |`, `|${head.map(() => ':-:').join('|')}|`]
|
|
for (const r of t.rows) lines.push(`| ${[...r.ins.map(String), ...r.outs.map(v => cell(r, v))].join(' | ')} |`)
|
|
return `${lines.join('\n')}\n`
|
|
}
|
|
|
|
/** A CMOS NAND gate with two inputs: two transistors in parallel to the supply, two in series to ground. */
|
|
export const TRANSISTORS_PER_NAND = 4
|
|
|
|
/**
|
|
* NAND gates per component, counting everything inside it at every depth.
|
|
* Switches, lamps, displays and cables need no gates. Shared work is cached,
|
|
* so a whole library costs one pass; a component that contains itself counts 0.
|
|
*/
|
|
export function nandCounts(components: ComponentDef[]): Map<string, number> {
|
|
const byId = new Map(components.map(d => [d.id, d]))
|
|
const memo = new Map<string, number>()
|
|
const busy = new Set<string>()
|
|
const count = (id: string): number => {
|
|
const known = memo.get(id)
|
|
if (known !== undefined) return known
|
|
const def = byId.get(id)
|
|
if (!def || busy.has(id)) return 0
|
|
busy.add(id)
|
|
let n = 0
|
|
for (const node of def.nodes) {
|
|
if (node.kind === 'nand') n++
|
|
else if (node.kind === 'chip' && node.chip) n += count(node.chip)
|
|
}
|
|
busy.delete(id)
|
|
memo.set(id, n)
|
|
return n
|
|
}
|
|
for (const d of components) count(d.id)
|
|
return memo
|
|
}
|
|
|
|
/** "1,234 transistors" in short form for tight spots: 1.2k. */
|
|
export function shortCount(n: number): string {
|
|
if (n < 1000) return String(n)
|
|
if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '')}k`
|
|
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
|
|
}
|
|
|
|
export interface Stats {
|
|
nands: number
|
|
/** Has feedback loops, so it can store state (latch, flip-flop, counter). */
|
|
sequential: boolean
|
|
/** Longest path in NAND gates; null when there are loops. */
|
|
delay: number | null
|
|
}
|
|
|
|
export function stats(nl: Netlist): Stats {
|
|
const gates = nl.gateOut.length
|
|
const driver = new Int32Array(nl.netCount).fill(-1)
|
|
for (let g = 0; g < gates; g++) driver[nl.gateOut[g]!] = g
|
|
const indeg = new Int32Array(gates)
|
|
for (let g = 0; g < gates; g++) {
|
|
const a = nl.gateA[g]!
|
|
const b = nl.gateB[g]!
|
|
if (driver[a]! >= 0) indeg[g]!++
|
|
if (b !== a && driver[b]! >= 0) indeg[g]!++
|
|
}
|
|
const depth = new Int32Array(gates)
|
|
const queue: number[] = []
|
|
for (let g = 0; g < gates; g++) if (indeg[g] === 0) queue.push(g)
|
|
let done = 0
|
|
let delay = 0
|
|
while (done < queue.length) {
|
|
const g = queue[done++]!
|
|
const d = depth[g]! + 1
|
|
delay = Math.max(delay, d)
|
|
const out = nl.gateOut[g]!
|
|
for (let j = nl.fanStart[out]!; j < nl.fanStart[out + 1]!; j++) {
|
|
const r = nl.fanList[j]!
|
|
depth[r] = Math.max(depth[r]!, d)
|
|
if (--indeg[r]! === 0) queue.push(r)
|
|
}
|
|
}
|
|
const sequential = done < gates
|
|
return { nands: gates, sequential, delay: sequential ? null : delay }
|
|
}
|
|
|
|
/** One test step: set inputs (by pin label), let it settle, check outputs. */
|
|
export interface TestStep {
|
|
set: Record<string, number>
|
|
expect: Record<string, number>
|
|
}
|
|
|
|
export interface TestResult {
|
|
pass: boolean
|
|
message: string
|
|
failedStep?: number
|
|
}
|
|
|
|
export function runSteps(getDef: DefLookup, defId: string, steps: TestStep[]): TestResult {
|
|
const def = getDef(defId)
|
|
if (!def) return { pass: false, message: 'Component not found' }
|
|
const pins = chipPins(def)
|
|
const find = (list: { key: string; label: string }[], label: string) =>
|
|
list.find(p => p.label.toLowerCase() === label.toLowerCase())
|
|
for (const step of steps) {
|
|
for (const l of Object.keys(step.set)) {
|
|
if (!find(pins.inputs, l)) return { pass: false, message: `Missing input pin "${l}"` }
|
|
}
|
|
for (const l of Object.keys(step.expect)) {
|
|
if (!find(pins.outputs, l)) return { pass: false, message: `Missing output pin "${l}"` }
|
|
}
|
|
}
|
|
const sim = new Simulator(compile(getDef, defId))
|
|
sim.run(SETTLE_BUDGET)
|
|
for (let i = 0; i < steps.length; i++) {
|
|
const step = steps[i]!
|
|
for (const [l, v] of Object.entries(step.set)) sim.setSource(find(pins.inputs, l)!.key, v === 1)
|
|
if (!sim.run(SETTLE_BUDGET)) return { pass: false, message: 'The circuit oscillates and never settles', failedStep: i }
|
|
for (const [l, want] of Object.entries(step.expect)) {
|
|
const got = sim.pin(find(pins.outputs, l)!.key, 'a')
|
|
if (got !== want) {
|
|
const inputs = Object.entries(step.set).map(([k, v]) => `${k}=${v}`).join(' ')
|
|
return { pass: false, message: `With ${inputs}: ${l} is ${got}, expected ${want}`, failedStep: i }
|
|
}
|
|
}
|
|
}
|
|
return { pass: true, message: `All ${steps.length} checks pass` }
|
|
}
|