logigate/app/lib/logic/compile.ts

266 lines
8.0 KiB
TypeScript

// 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<string, number>
/** Same, for nodes at any depth, keyed "chipNode/…/nodeId:pin". Only with `trace`. */
tracePinNet?: Map<string, number>
/** Inputs of lamps and displays inside the root's chips, keyed "chipNode/nodeId:pin", for drawing them on the chip. */
facePinNet: Map<string, number>
/** User-driven sources in the root circuit (switches, buttons): nodeId → net. */
sources: Map<string, number>
clocks: Int32Array
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) : []
default:
return []
}
}
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: number[] = []
const sources = new Map<string, number>()
const rawPinNet = new Map<string, number>()
const rawTrace = opts.trace ? new Map<string, number>() : undefined
const rawFace = new Map<string, number>()
const errors: string[] = []
const pinCache = new Map<string, ChipPins>()
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<string, number> | null, path: string, stack: string[]): Map<string, number> => {
const result = new Map<string, number>()
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<string, Wire>()
for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w)
const outNet = new Map<string, number>()
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(q)
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<string, number>()
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<string, number>) => {
const out = new Map<string, number>()
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 clockNets = Int32Array.from(new Set(clocks.map(canon)))
// 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,
errors: [...new Set(errors)],
}
}