// 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 { chipPins, 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': return ['a'] case 'hex': return ['b0', 'b1', 'b2', 'b3'] case 'chip': return pins ? pins.inputs.map(p => p.key) : [] default: return [] } } export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] { switch (node.kind) { case 'nand': case 'input': case 'high': case 'low': case 'button': case 'clock': return ['q'] case 'chip': return pins ? pins.outputs.map(p => p.key) : [] case 'panel': return (node.rows ?? []).map(r => r.id) default: return [] } } /** Key of a panel row in the simulator's sources, like a switch's node id. */ export const rowSource = (nodeId: string, rowId: string) => `${nodeId}:${rowId}` 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 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 } for (const n of def.nodes) { const q = outNet.get(`${n.id}:q`)! switch (n.kind) { case 'nand': gA.push(inNet(n.id, 'a')) gB.push(inNet(n.id, '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 'panel': // In the open circuit the rows are switches and buttons you use; // inside a component a switch row keeps its position, 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 (r.type === 'switch' && r.on) union(net, HIGH) } break case 'output': result.set(n.id, inNet(n.id, 'a')) 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, inNet(n.id, 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') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, inNet(n.id, 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)], } }