// Flattens a component tree into a flat list of NAND gates over numbered // nets. Chip boundaries and input/output pins disappear: they are aliases, // merged with union-find. Net 0 is constant LOW, net 1 constant HIGH. import { cableBits, chipPins, isPinRow, rowPin, type ChipPins, type DefLookup } from './geometry' import type { CircuitNode, ComponentDef, Wire } from './types' export const LOW = 0 export const HIGH = 1 export interface Netlist { netCount: number gateA: Int32Array gateB: Int32Array gateOut: Int32Array /** Stable identity per gate ("chipNode/chipNode/nandNode"), to keep state across recompiles. */ gateKeys: string[] /** CSR fanout: gates reading net n are fanList[fanStart[n] .. fanStart[n + 1]). */ fanStart: Int32Array fanList: Int32Array /** Net of every pin of the root circuit's nodes, keyed "nodeId:pin". */ pinNet: Map /** Same, for nodes at any depth, keyed "chipNode/…/nodeId:pin". Only with `trace`. */ tracePinNet?: Map /** Inputs of lamps and displays inside the root's chips, keyed "chipNode/nodeId:pin", for drawing them on the chip. */ facePinNet: Map /** User-driven sources in the root circuit (switches, buttons): nodeId → net. */ sources: Map clocks: Int32Array /** Frequency per clock in Hz; 0 follows the speed in the top bar. */ clockHz: Float64Array /** Stable identity per clock ("chipNode/…/clockNode"), to keep its level across recompiles. */ clockKeys: string[] errors: string[] } export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] { switch (node.kind) { case 'nand': return ['a', 'b'] case 'output': case 'lamp': case 'pixel': case 'split': case 'tag': return ['a'] case 'hex': return ['b0', 'b1', 'b2', 'b3'] case 'outpanel': return (node.rows ?? []).map(r => r.id) case 'bundle': return cableKeys(node) case 'chip': return pins ? pins.inputs.map(p => p.key) : [] default: return [] } } export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] { switch (node.kind) { case 'output': case 'lamp': return ['q'] case 'nand': case 'input': case 'high': case 'low': case 'button': case 'clock': case 'ref': return ['q'] case 'chip': return pins ? pins.outputs.map(p => p.key) : [] case 'hex': return ['q0', 'q1', 'q2', 'q3'] case 'panel': case 'outpanel': return (node.rows ?? []).map(r => r.id) case 'bundle': return ['q'] case 'split': return cableKeys(node) default: return [] } } /** Kinds whose inputs can be inverted with a bubble. */ export const INVERTIBLE = new Set(['nand', 'chip', 'output', 'lamp']) /** The inverted inputs of a part that it really has, each once. */ export function invertedPins(node: CircuitNode, pins?: ChipPins): string[] { if (!node.invert?.length || !INVERTIBLE.has(node.kind)) return [] const keys = new Set(inputKeys(node, pins)) return [...new Set(node.invert)].filter(k => keys.has(k)) } /** Pin keys of the single wires on a bundle or split: b0, b1, … */ export function cableKeys(node: CircuitNode): string[] { return Array.from({ length: cableBits(node) }, (_, i) => `b${i}`) } /** Key of a panel row in the simulator's sources, like a switch's node id. */ export const rowSource = rowPin const MAX_DEPTH = 64 export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist { const parent: number[] = [LOW, HIGH] const make = () => { parent.push(parent.length) return parent.length - 1 } const find = (x: number) => { while (parent[x] !== x) { parent[x] = parent[parent[x]!]! x = parent[x]! } return x } const union = (a: number, b: number) => { a = find(a) b = find(b) if (a === b) return // Constants stay roots so they keep their fixed values. if (a <= HIGH) parent[b] = a else parent[a] = b } const gA: number[] = [] const gB: number[] = [] const gOut: number[] = [] const gateKeys: string[] = [] const clocks: { net: number; hz: number; key: string }[] = [] const sources = new Map() const rawPinNet = new Map() const rawTrace = opts.trace ? new Map() : undefined const rawFace = new Map() const errors: string[] = [] const pinCache = new Map() const pinsOf = (node: CircuitNode): ChipPins | undefined => { if (node.kind !== 'chip' || !node.chip) return undefined let p = pinCache.get(node.chip) if (!p) { const def = getDef(node.chip) if (!def) return undefined p = chipPins(def) pinCache.set(node.chip, p) } return p } const expand = (def: ComponentDef, inNets: Map | null, path: string, stack: string[]): Map => { const result = new Map() if (stack.includes(def.id)) { errors.push(`"${def.name}" contains itself`) return result } if (stack.length >= MAX_DEPTH) { errors.push(`Nesting deeper than ${MAX_DEPTH} levels`) return result } const inner = [...stack, def.id] const wiresTo = new Map() for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w) const nodeById = new Map(def.nodes.map(n => [n.id, n])) const outNet = new Map() for (const n of def.nodes) { for (const k of outputKeys(n, pinsOf(n))) outNet.set(`${n.id}:${k}`, make()) } const inNet = (nodeId: string, pin: string) => { const w = wiresTo.get(`${nodeId}:${pin}`) return w ? (outNet.get(`${w.from.node}:${w.from.pin}`) ?? LOW) : LOW } // An inverted input: the wire's signal through a NAND with both inputs tied, made once per pin. const inverters = new Map() const pinIn = (n: CircuitNode, pin: string) => { const raw = inNet(n.id, pin) if (!n.invert?.length || !invertedPins(n, pinsOf(n)).includes(pin)) return raw const key = `${n.id}:${pin}` let net = inverters.get(key) if (net === undefined) { net = make() gA.push(raw) gB.push(raw) gOut.push(net) gateKeys.push(`${path}${n.id}~${pin}`) inverters.set(key, net) } return net } // Signal tags by name: a reference carries what is wired into the tag of its name. const tags = new Map() for (const n of def.nodes) { const name = n.kind === 'tag' ? n.label?.trim() : '' if (name) tags.set(name, [...(tags.get(name) ?? []), n]) } for (const n of def.nodes) { const q = outNet.get(`${n.id}:q`)! switch (n.kind) { case 'nand': { const a = pinIn(n, 'a') const b = pinIn(n, 'b') gA.push(a) gB.push(b) gOut.push(q) gateKeys.push(path + n.id) break } case 'input': if (inNets) union(q, inNets.get(n.id) ?? LOW) else sources.set(n.id, q) break case 'button': if (!inNets) sources.set(n.id, q) break case 'high': union(q, HIGH) break case 'low': union(q, LOW) break case 'clock': clocks.push({ net: q, hz: n.hz ?? 0, key: path + n.id }) break case 'split': { // Wire i of the cable is whatever drives input i of the bundle at its other end. const w = wiresTo.get(`${n.id}:a`) const src = w && nodeById.get(w.from.node) if (src?.kind !== 'bundle') break const count = Math.min(cableBits(n), cableBits(src)) for (let i = 0; i < count; i++) union(outNet.get(`${n.id}:b${i}`)!, inNet(src.id, `b${i}`)) break } case 'panel': // In the open circuit the rows are switches and buttons you use; // inside a component they are its input pins. A panel kept inside // has fixed switches there (a button is 0). for (const r of n.rows ?? []) { const net = outNet.get(`${n.id}:${r.id}`)! if (r.type === 'clock') clocks.push({ net, hz: r.hz ?? 0, key: `${path}${n.id}:${r.id}` }) else if (!inNets) sources.set(rowSource(n.id, r.id), net) else if (isPinRow(n, r)) union(net, inNets.get(rowPin(n.id, r.id)) ?? LOW) else if (r.type === 'switch' && r.on) union(net, HIGH) } break case 'output': result.set(n.id, pinIn(n, 'a')) union(q, pinIn(n, 'a')) break case 'ref': // Two tags of one name drive one signal: a short, like two wires on one input. for (const t of tags.get(n.label?.trim() ?? '') ?? []) union(q, inNet(t.id, 'a')) break case 'lamp': // A lamp passes its signal on to whatever its right pin feeds. union(q, pinIn(n, 'a')) break case 'hex': for (let i = 0; i < 4; i++) union(outNet.get(`${n.id}:q${i}`)!, inNet(n.id, `b${i}`)) break case 'outpanel': // Each row shows its signal and passes it on; inside a component the rows are its outputs. for (const r of n.rows ?? []) { const net = inNet(n.id, r.id) union(outNet.get(`${n.id}:${r.id}`)!, net) if (!n.inner) result.set(rowPin(n.id, r.id), net) } break case 'chip': { const child = n.chip ? getDef(n.chip) : undefined const pins = pinsOf(n) if (!child || !pins) { errors.push(`Missing component in "${def.name}"`) break } const childIn = new Map() for (const p of pins.inputs) childIn.set(p.key, pinIn(n, p.key)) const childOut = expand(child, childIn, `${path}${n.id}/`, inner) for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW) break } } } if (stack.length === 1) { for (const n of def.nodes) { if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, pinIn(n, k)) } } if (inNets === null || rawTrace) { const record = (n: CircuitNode, k: string, net: number) => { if (inNets === null) rawPinNet.set(`${n.id}:${k}`, net) rawTrace?.set(`${path}${n.id}:${k}`, net) } for (const n of def.nodes) { const pins = pinsOf(n) for (const k of inputKeys(n, pins)) record(n, k, inNet(n.id, k)) for (const k of outputKeys(n, pins)) record(n, k, outNet.get(`${n.id}:${k}`)!) } } return result } const root = getDef(rootId) if (root) expand(root, null, '', []) else errors.push('Circuit not found') // Renumber union-find roots to 0..netCount-1, constants first. const idx = new Int32Array(parent.length).fill(-1) idx[find(LOW)] = LOW idx[find(HIGH)] = HIGH let netCount = 2 const canon = (x: number) => { const r = find(x) if (idx[r]! < 0) idx[r] = netCount++ return idx[r]! } const gateCount = gOut.length const gateA = new Int32Array(gateCount) const gateB = new Int32Array(gateCount) const gateOut = new Int32Array(gateCount) for (let i = 0; i < gateCount; i++) { gateA[i] = canon(gA[i]!) gateB[i] = canon(gB[i]!) gateOut[i] = canon(gOut[i]!) } const mapNets = (m: Map) => { const out = new Map() for (const [k, v] of m) out.set(k, canon(v)) return out } const pinNet = mapNets(rawPinNet) const tracePinNet = rawTrace ? mapNets(rawTrace) : undefined const facePinNet = mapNets(rawFace) const srcs = mapNets(sources) const seenClock = new Set() const clockList = clocks .map(c => ({ ...c, net: canon(c.net) })) .filter(c => !seenClock.has(c.net) && seenClock.add(c.net)) const clockNets = Int32Array.from(clockList.map(c => c.net)) // Fanout in CSR form. const fanStart = new Int32Array(netCount + 1) for (let i = 0; i < gateCount; i++) { fanStart[gateA[i]! + 1]!++ if (gateB[i] !== gateA[i]) fanStart[gateB[i]! + 1]!++ } for (let n = 0; n < netCount; n++) fanStart[n + 1]! += fanStart[n]! const fanList = new Int32Array(fanStart[netCount]!) const fill = fanStart.slice(0, netCount) for (let i = 0; i < gateCount; i++) { fanList[fill[gateA[i]!]!++] = i if (gateB[i] !== gateA[i]) fanList[fill[gateB[i]!]!++] = i } return { netCount, gateA, gateB, gateOut, gateKeys, fanStart, fanList, pinNet, tracePinNet, facePinNet, sources: srcs, clocks: clockNets, clockHz: Float64Array.from(clockList.map(c => c.hz)), clockKeys: clockList.map(c => c.key), errors: [...new Set(errors)], } }