logigate/app/lib/logic/compile.ts

459 lines
17 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 { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry'
import { DATA_KEYS } from './devices'
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>
/** What each of the root circuit's output pins puts out (keyed like ChipPins outputs), after any bubble on it. */
outputs: Map<string, number>
/** User-driven sources in the root circuit (switches, buttons): nodeId → net. */
sources: Map<string, number>
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, get?: DefLookup): string[] {
switch (node.kind) {
case 'portin':
return get ? portLines(node, get).filter(l => !l.enters).map(l => l.key) : []
case 'portout':
return ['bus', ...(get ? portLines(node, get).filter(l => !l.enters).map(l => l.key) : [])]
case 'nand':
return ['a', 'b']
case 'pixel':
return node.rgb ? ['r', 'g', 'b'] : ['a']
case 'output':
case 'lamp':
case 'split':
case 'tag':
return ['a']
case 'hex':
return ['b0', 'b1', 'b2', 'b3']
case 'terminal':
return [...DATA_KEYS, 'wr', 'clr']
case 'keyboard':
return ['next']
case 'outpanel':
return (node.rows ?? []).map(r => r.id)
case 'bundle':
return cableKeys(node)
case 'chip':
return pins ? [...pins.inputs.map(p => p.key), ...portKeys(pins, 'in'), ...lineKeys(node, pins, get, true)] : []
default:
return []
}
}
/** Keys of a component's connector ports on one side. */
const portKeys = (pins: ChipPins, side: 'in' | 'out') => (pins.ports ?? []).filter(p => p.side === side).map(p => p.key)
/** Keys of the lines of ports split on a placed component's box that go in (or come out). */
const lineKeys = (node: CircuitNode, pins: ChipPins, get: DefLookup | undefined, enters: boolean) => splitLines(node, pins, get).filter(l => l.enters === enters).map(l => l.key)
export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): string[] {
switch (node.kind) {
case 'portin':
return ['bus', ...(get ? portLines(node, get).filter(l => l.enters).map(l => l.key) : [])]
case 'portout':
return get ? portLines(node, get).filter(l => l.enters).map(l => l.key) : []
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), ...portKeys(pins, 'out'), ...lineKeys(node, pins, get, false)] : []
case 'hex':
return ['q0', 'q1', 'q2', 'q3']
case 'keyboard':
return [...DATA_KEYS, 'rdy']
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
export 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<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
}
// `portNets`: for each port part of this component, the nets of its lines, from the parent that placed it.
const expand = (
def: ComponentDef,
inNets: Map<string, number> | null,
path: string,
stack: string[],
portNets?: Map<string, number[]>,
): 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 nodeById = new Map(def.nodes.map(n => [n.id, n]))
// Ends of typed cables ("node:pin"): the nets of their lines, joined line by line below.
const ends = new Map<string, number[]>()
// Line pins of ports split on boxes ("node:pin"): the line's net, wired by hand or fed through the cable.
const lineNets = new Map<string, number>()
const outNet = new Map<string, number>()
for (const n of def.nodes) {
for (const k of outputKeys(n, pinsOf(n), getDef)) 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<string, number>()
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<string, CircuitNode[]>()
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 'keyboard':
// The keys typed, 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}`)!)
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 'portin':
case 'portout': {
// A connector port: its lines are the nets the parent handed in (fresh ones at the top).
const lines = portLines(n, getDef)
const nets = portNets?.get(n.id) ?? lines.map(() => make())
ends.set(`${n.id}:bus`, nets)
lines.forEach((l, i) => {
const net = nets[i]
if (net === undefined) return
if (l.enters) union(outNet.get(`${n.id}:${l.key}`)!, net)
else if (wiresTo.has(`${n.id}:${l.key}`)) union(inNet(n.id, l.key), 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<string, number>()
for (const p of pins.inputs) childIn.set(p.key, pinIn(n, p.key))
const childPorts = new Map<string, number[]>()
for (const p of pins.ports ?? []) {
const nets = (getDef.conn?.(p.conn)?.lines ?? []).map(() => make())
childPorts.set(p.key, nets)
ends.set(`${n.id}:${p.key}`, nets)
}
// A port split on the box: each line is a pin of its own as well. A
// wire into a line drives it like the cable would (both at once is a short).
for (const l of splitLines(n, pins, getDef)) {
const net = childPorts.get(l.port)?.[l.index]
if (net === undefined) continue
lineNets.set(`${n.id}:${l.key}`, net)
if (!l.enters) union(outNet.get(`${n.id}:${l.key}`)!, net)
else if (wiresTo.has(`${n.id}:${l.key}`)) union(inNet(n.id, l.key), net)
}
const childOut = expand(child, childIn, `${path}${n.id}/`, inner, childPorts)
for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW)
break
}
}
}
// Typed cables: line i of one end is line i of the other.
for (const w of def.wires) {
const a = ends.get(`${w.from.node}:${w.from.pin}`)
const b = ends.get(`${w.to.node}:${w.to.pin}`)
if (a && b) for (let i = 0; i < Math.min(a.length, b.length); i++) union(a[i]!, b[i]!)
}
// Lamps, displays and pixels inside placed components, at every depth: a box may show those of parts inside it.
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, getDef)) record(n, k, lineNets.get(`${n.id}:${k}`) ?? inNet(n.id, k))
for (const k of outputKeys(n, pins, getDef)) record(n, k, outNet.get(`${n.id}:${k}`)!)
}
}
return result
}
const root = getDef(rootId)
const rootOut = root ? expand(root, null, '', []) : new Map<string, number>()
if (!root) 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 seenClock = new Set<number>()
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,
outputs: mapNets(rootOut),
sources: srcs,
clocks: clockNets,
clockHz: Float64Array.from(clockList.map(c => c.hz)),
clockKeys: clockList.map(c => c.key),
errors: [...new Set(errors)],
}
}