logigate/tests/state.test.ts

298 lines
12 KiB
TypeScript
Raw Normal View History

import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { compile, type Netlist } from '../app/lib/logic/compile'
import { chipPins } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { parseProject, toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
import { flow, packState, stateCarry } from '../app/lib/logic/state'
import type { CircuitNode, ComponentDef, Project } from '../app/lib/logic/types'
/** A D latch from the examples between two switches and an output pin, open as the circuit. */
function memory(): Project {
const p = createProject({ examples: true })
const pins = chipPins(lookup(p)('ex-dlatch')!)
const pin = (label: string) => pins.inputs.find(x => x.label === label)!.key
p.components.push({
id: 'mem',
name: 'Memory',
symbol: 'box',
nodes: [
{ id: 'd', kind: 'input', x: 0, y: 0, label: 'D' },
{ id: 'e', kind: 'input', x: 0, y: 4, label: 'E' },
{ id: 'u', kind: 'chip', chip: 'ex-dlatch', x: 6, y: 0 },
{ id: 'q', kind: 'output', x: 20, y: 0, label: 'Q' },
],
wires: [
{ id: 'w1', from: { node: 'd', pin: 'q' }, to: { node: 'u', pin: pin('D') } },
{ id: 'w2', from: { node: 'e', pin: 'q' }, to: { node: 'u', pin: pin('E') } },
{ id: 'w3', from: { node: 'u', pin: pins.outputs[0]!.key }, to: { node: 'q', pin: 'a' } },
],
})
p.openId = 'mem'
return p
}
/** Opens a circuit the way the editor does: from what it held last, with its switches as they are set. */
function open(p: Project, id: string): Simulator {
const nl = compile(lookup(p), id)
const held = p.state?.[id]
const s = new Simulator(nl, held && stateCarry(held, nl))
for (const n of lookup(p)(id)!.nodes) if (n.kind === 'input') s.setSource(n.id, !!n.on)
s.run()
return s
}
/** Leaves a circuit (or saves): what it holds goes into the project. */
function leave(p: Project, id: string, s: Simulator) {
const held = packState(s)
p.state = { ...p.state }
if (held) p.state[id] = held
else delete p.state[id]
}
/** Flips switches as clicks do, letting the circuit settle after each. */
function flip(p: Project, s: Simulator, steps: [string, boolean][]) {
const nodes = new Map(p.components.flatMap(d => d.nodes).map(n => [n.id, n]))
for (const [id, on] of steps) {
nodes.get(id)!.on = on
s.setSource(id, on)
expect(s.run()).toBe(true)
}
}
const store1 = (p: Project, s: Simulator) => flip(p, s, [['d', true], ['e', true], ['e', false], ['d', false]])
describe('what a circuit holds', () => {
it('is only the gates on loops: the latch, not the gates in front of it', () => {
const p = memory()
const nl = compile(lookup(p), 'mem')
const { loop, order } = flow(nl)
const looped = nl.gateKeys.filter((_, g) => loop[g])
// The SR latch inside the D latch: its two cross-coupled NANDs.
expect(looped).toHaveLength(2)
expect(looped.every(k => k.startsWith('u/'))).toBe(true)
// Every gate once, each after the gates that feed it.
expect([...order].sort((a, b) => a - b)).toEqual(nl.gateKeys.map((_, g) => g))
const at = new Map([...order].map((g, i) => [g, i]))
nl.gateOut.forEach((out, g) => {
for (let j = nl.fanStart[out]!; j < nl.fanStart[out + 1]!; j++) {
const r = nl.fanList[j]!
if (!loop[r] || !loop[g]) expect(at.get(g)!).toBeLessThan(at.get(r)!)
}
})
})
it('packs the gates that are 1 by their path, and unpacks them again', () => {
const p = memory()
const s = open(p, 'mem')
store1(p, s)
expect(s.pin('q', 'a')).toBe(1)
const held = packState(s)!
const key = s.nl.gateKeys.find((k, g) => flow(s.nl).loop[g] && s.values[s.nl.gateOut[g]!])!
expect(key.split('/')).toHaveLength(3)
expect(held).toEqual({ names: key.split('/'), on: '0:0.1.2' })
const back = JSON.parse(JSON.stringify(held))
const carry = stateCarry(back, s.nl)
expect([...carry.gates]).toEqual([[key, 1]])
expect(open(p, 'mem').pin('q', 'a')).toBe(0)
p.state = { mem: back }
expect(open(p, 'mem').pin('q', 'a')).toBe(1)
})
it('writes each gate as the levels it shares with the one before and the rest of its path', () => {
const keys = ['a/b/c/x', 'a/b/c/y', 'a/b/d/x', 'a/e/c/x', 'z', 'a/b/c~in']
// Gates that each read their own output: all on a loop, all set to 1.
const out = Int32Array.from(keys, (_, i) => i + 2)
const nl: Netlist = {
netCount: keys.length + 2,
gateA: out,
gateB: out,
gateOut: out,
gateKeys: keys,
fanStart: Int32Array.from({ length: keys.length + 3 }, (_, n) => Math.max(0, n - 2)),
fanList: Int32Array.from(keys, (_, i) => i),
pinNet: new Map(),
facePinNet: new Map(),
outputs: new Map(),
sources: new Map(),
clocks: new Int32Array(0),
clockHz: new Float64Array(0),
clockKeys: [],
errors: [],
}
const s = new Simulator(nl)
s.values.fill(1)
const held = packState(s)!
expect(held.names).toEqual(['a', 'b', 'c', 'x', 'y', 'd', 'e', 'z', 'c~in'])
expect(held.on).toBe('0:0.1.2.3 3:4 2:5.3 1:6.2.3 0:7 0:0.1.8')
expect([...stateCarry(held, nl).gates.keys()]).toEqual(keys)
})
it('is nothing to keep for a circuit without loops', () => {
const p = createProject({ examples: true })
expect(packState(open(p, 'ex-add4'))).toBeUndefined()
})
it('keeps a latch’s bit when you go into a component and come back', () => {
const p = memory()
let s = open(p, 'mem')
store1(p, s)
expect(s.pin('q', 'a')).toBe(1)
// Into the D latch itself: it runs on its own, with its own switches.
leave(p, 'mem', s)
const inside = open(p, 'ex-dlatch')
leave(p, 'ex-dlatch', inside)
s = open(p, 'mem')
expect(s.pin('q', 'a')).toBe(1)
// And a 0 stays a 0 while D is already 1 again.
flip(p, s, [['e', true], ['e', false], ['d', true]])
expect(s.pin('q', 'a')).toBe(0)
leave(p, 'mem', s)
expect(open(p, 'mem').pin('q', 'a')).toBe(0)
})
it('a memory placed while the circuit runs starts at 0, and the rest keeps its bits', () => {
const p = memory()
const s = open(p, 'mem')
store1(p, s)
lookup(p)('mem')!.nodes.push({ id: 'r', kind: 'chip', chip: 'ex-reg4', x: 30, y: 0 })
// What the editor does after a change: the same circuit goes on from all its gates.
const again = new Simulator(compile(lookup(p), 'mem'), s.carry())
again.run()
expect(again.pin('q', 'a')).toBe(1)
for (const out of chipPins(lookup(p)('ex-reg4')!).outputs) expect(again.pin('r', out.key)).toBe(0)
})
it('starts from all zeros again after power off and on', () => {
const p = memory()
const s = open(p, 'mem')
store1(p, s)
leave(p, 'mem', s)
delete p.state!.mem
expect(open(p, 'mem').pin('q', 'a')).toBe(0)
})
it('is not upset by the gates in front of a latch that were placed after it', () => {
// The latch NANDs come first, their inverting inputs last: run in placing order from saved bits, the latch would flip.
const nand = (id: string, x: number): CircuitNode => ({ id, kind: 'nand', x, y: 0 })
const def: ComponentDef = {
id: 'sr',
name: 'SR',
symbol: 'box',
nodes: [nand('q', 10), nand('nq', 10), nand('is', 5), nand('ir', 5), { id: 's', kind: 'input', x: 0, y: 0 }, { id: 'r', kind: 'input', x: 0, y: 4 }],
wires: [
{ id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'is', pin: 'a' } },
{ id: 'w2', from: { node: 's', pin: 'q' }, to: { node: 'is', pin: 'b' } },
{ id: 'w3', from: { node: 'r', pin: 'q' }, to: { node: 'ir', pin: 'a' } },
{ id: 'w4', from: { node: 'r', pin: 'q' }, to: { node: 'ir', pin: 'b' } },
{ id: 'w5', from: { node: 'is', pin: 'q' }, to: { node: 'q', pin: 'a' } },
{ id: 'w6', from: { node: 'nq', pin: 'q' }, to: { node: 'q', pin: 'b' } },
{ id: 'w7', from: { node: 'q', pin: 'q' }, to: { node: 'nq', pin: 'a' } },
{ id: 'w8', from: { node: 'ir', pin: 'q' }, to: { node: 'nq', pin: 'b' } },
],
}
const p = createProject({ examples: false })
p.components.push(def)
for (const bit of [1, 0]) {
const s = open(p, 'sr')
flip(p, s, bit ? [['s', true], ['s', false]] : [['r', true], ['r', false]])
expect(s.pin('q', 'q')).toBe(bit)
leave(p, 'sr', s)
expect(p.state!.sr).toEqual({ names: [bit ? 'q' : 'nq'], on: '0:0' })
const again = open(p, 'sr')
expect([again.pin('q', 'q'), again.pin('nq', 'q')]).toEqual([bit, 1 - bit])
}
})
it('keeps clock levels: high ones high, the others low', () => {
const p = createProject({ examples: false })
p.components.push({
id: 'clk',
name: 'Clocks',
symbol: 'box',
nodes: [
{ id: 'c1', kind: 'clock', x: 0, y: 0 },
{ id: 'c2', kind: 'clock', x: 0, y: 4, hz: 10 },
{ id: 'l1', kind: 'lamp', x: 6, y: 0 },
{ id: 'l2', kind: 'lamp', x: 6, y: 4 },
],
wires: [
{ id: 'w1', from: { node: 'c1', pin: 'q' }, to: { node: 'l1', pin: 'a' } },
{ id: 'w2', from: { node: 'c2', pin: 'q' }, to: { node: 'l2', pin: 'a' } },
],
})
const s = open(p, 'clk')
s.toggleClock(1)
s.run()
leave(p, 'clk', s)
expect(p.state!.clk).toEqual({ names: [], on: '', clocks: ['c2'] })
const again = open(p, 'clk')
expect([again.pin('l1', 'a'), again.pin('l2', 'a')]).toEqual([0, 1])
expect(again.clock).toBe(1)
})
it('stays small for a lot of memory: 64 flip-flops', () => {
const p = createProject({ examples: true })
const reg = chipPins(lookup(p)('ex-reg4')!)
const nodes: CircuitNode[] = [{ id: 'one', kind: 'high', x: 0, y: 0 }, { id: 'clk', kind: 'input', x: 0, y: 4 }]
const wires: ComponentDef['wires'] = []
for (let i = 0; i < 16; i++) {
nodes.push({ id: `reg${i}`, kind: 'chip', chip: 'ex-reg4', x: 10, y: 20 * i })
reg.inputs.forEach((pin, k) => wires.push({ id: `w${i}-${k}`, from: { node: pin.label === 'CLK' ? 'clk' : 'one', pin: 'q' }, to: { node: `reg${i}`, pin: pin.key } }))
}
p.components.push({ id: 'ram', name: 'RAM', symbol: 'box', nodes, wires })
const s = open(p, 'ram')
flip(p, s, [['clk', true], ['clk', false]])
const nl = s.nl
expect(flow(nl).loop.reduce((n, v) => n + v, 0)).toBe(64 * 4)
leave(p, 'ram', s)
const size = JSON.stringify(p.state!.ram).length
// 128 latches hold a 1 (master and slave of each flip-flop): about ten characters each.
expect(size).toBeLessThan(128 * 12)
const again = open(p, 'ram')
for (let i = 0; i < 16; i++) for (const out of reg.outputs) expect(again.pin(`reg${i}`, out.key)).toBe(1)
})
})
describe('saving what circuits hold', () => {
it('goes with the project through a file or the server and comes back', () => {
const p = memory()
const s = open(p, 'mem')
store1(p, s)
leave(p, 'mem', s)
const loaded = parseProject(JSON.stringify(p))
expect(loaded.state).toEqual(p.state)
expect(toProject(JSON.parse(JSON.stringify(loaded))).state).toEqual(p.state)
expect(open(loaded, 'mem').pin('q', 'a')).toBe(1)
})
it('is absent in projects saved before it, which start from zeros as they always did', () => {
const p = parseProject(readFileSync('tests/fixtures/v1-project.json', 'utf8'))
expect(p.state).toBeUndefined()
for (const d of p.components) open(p, d.id)
})
it('drops entries for circuits that are gone and broken ones; names that no longer exist are ignored', () => {
const p = memory()
const s = open(p, 'mem')
store1(p, s)
leave(p, 'mem', s)
const data = JSON.parse(JSON.stringify(p))
data.state.gone = { names: ['n1'], on: '0:0' }
data.state['ex-sr'] = { names: ['n1'], on: ['0:0'] }
data.state['ex-dlatch'] = { names: [7], on: '0:0' }
data.state['ex-dff'] = 'bits'
data.state['ex-not'] = { names: [], on: '', clocks: [3, 'c'] }
data.state['ex-and'] = { names: [], on: '' }
// Gates of an old version, and garbage: they match no gate.
data.state.mem.names.push('old')
data.state.mem.on += ' 1:3 0:z.q 9 :'
const back = toProject(data)
expect(Object.keys(back.state!).sort()).toEqual(['ex-not', 'mem'])
expect(back.state!['ex-not']).toEqual({ names: [], on: '', clocks: ['c'] })
expect(open(back, 'mem').pin('q', 'a')).toBe(1)
expect(toProject({ ...data, state: [1, 2] }).state).toBeUndefined()
})
})