logigate/app/lib/logic/check.ts

123 lines
6.3 KiB
TypeScript

// Checking a circuit for mistakes that still simulate but rarely mean what
// was intended: inputs left open (they read 0), parts that drive nothing,
// pins that share a name, and signals nothing sends or two parts send.
import { chipPins, shapeOf, type DefLookup } from './geometry'
import { KIND_NAMES } from './progress'
import type { CircuitNode, ComponentDef, Project } from './types'
export type IssueLevel = 'error' | 'warn' | 'info'
export interface Issue {
level: IssueLevel
text: string
/** Parts to show for it; the first one is centred. */
nodes: string[]
}
/** Parts whose open inputs are worth a warning (a cable bundle's spare wires are not). */
export const CHECKED_INPUTS = new Set(['nand', 'chip', 'output', 'lamp', 'hex', 'pixel', 'tag', 'outpanel'])
function partName(n: CircuitNode, get: DefLookup): string {
const own = !n.autoLabel && n.label?.trim()
const kind = n.kind === 'chip' ? ((n.chip && get(n.chip)?.name) ?? 'Missing component') : (KIND_NAMES[n.kind] ?? n.kind)
if (n.kind === 'tag' || n.kind === 'ref') return `${kind} "${n.label?.trim() || '?'}"`
return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind)
}
/** Input pins of a part that have no wire (the lines of a split port may stay open: a cable can feed them). */
export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
if (!CHECKED_INPUTS.has(n.kind)) return []
const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
return shapeOf(n, get).inputs.filter(p => !p.bus && !p.port && !wired.has(p.key)).map(p => p.key)
}
/** Lines of split ports on a component's box that are wired by hand while a cable is plugged into their port. */
export function doublyFedLines(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
if (n.kind !== 'chip' || !n.splitPorts?.length) return []
// Its pins with a wire or cable, coming in or going out.
const linked = new Set(def.wires.flatMap(w => [w.to.node === n.id ? w.to.pin : '', w.from.node === n.id ? w.from.pin : '']))
return shapeOf(n, get).inputs.filter(p => p.port && linked.has(p.key) && linked.has(p.port)).map(p => p.key)
}
export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
const issues: Issue[] = []
const fed = new Set(def.wires.map(w => `${w.from.node}:${w.from.pin}`))
const name = (n: CircuitNode) => partName(n, get)
for (const n of def.nodes) {
if (n.kind === 'chip' && (!n.chip || !get(n.chip))) {
issues.push({ level: 'error', text: 'A placed component no longer exists', nodes: [n.id] })
continue
}
const open = openInputs(def, n, get)
if (open.length) {
const shape = shapeOf(n, get)
const labels = open.map(k => shape.inputs.find(p => p.key === k)?.label || k)
const all = open.length === shape.inputs.length
const text =
n.kind === 'chip' || n.kind === 'nand' || n.kind === 'hex'
? `${name(n)}: ${all ? 'no input connected' : `${labels.join(', ')} not connected`} (reads 0)`
: `${name(n)}: nothing connected`
issues.push({ level: 'warn', text, nodes: [n.id] })
}
if (n.kind === 'split' && !def.wires.some(w => w.to.node === n.id)) issues.push({ level: 'warn', text: 'Cable split without a cable', nodes: [n.id] })
const twice = doublyFedLines(def, n, get)
if (twice.length) {
const shape = shapeOf(n, get)
const labels = twice.map(k => shape.inputs.find(p => p.key === k)?.label || k)
issues.push({ level: 'warn', text: `${name(n)}: ${labels.join(', ')} wired and fed by the cable as well: both drive ${twice.length === 1 ? 'it' : 'them'}`, nodes: [n.id] })
}
// Parts that drive nothing.
if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) {
issues.push({ level: 'info', text: n.kind === 'nand' ? 'NAND gate: its output goes nowhere' : `${name(n)}: goes nowhere`, nodes: [n.id] })
}
if (n.kind === 'chip' && n.chip) {
const outs = chipPins(get(n.chip)!).outputs
if (outs.length && !outs.some(p => fed.has(`${n.id}:${p.key}`))) issues.push({ level: 'info', text: `${name(n)}: none of its outputs is used`, nodes: [n.id] })
}
}
// Pins of the same name can't be told apart from outside.
for (const kind of ['input', 'output'] as const) {
const by = new Map<string, CircuitNode[]>()
for (const n of def.nodes) {
const l = n.kind === kind ? n.label?.trim() : ''
if (l) by.set(l.toLowerCase(), [...(by.get(l.toLowerCase()) ?? []), n])
}
for (const list of by.values()) {
if (list.length > 1) issues.push({ level: 'warn', text: `${list.length} ${kind} pins are called ${list[0]!.label!.trim()}`, nodes: list.map(n => n.id) })
}
}
// Signals: sent once, used somewhere.
const tags = new Map<string, CircuitNode[]>()
const refs = new Map<string, CircuitNode[]>()
for (const n of def.nodes) {
const l = n.label?.trim() ?? ''
if (n.kind === 'tag') tags.set(l, [...(tags.get(l) ?? []), n])
if (n.kind === 'ref') refs.set(l, [...(refs.get(l) ?? []), n])
}
for (const [l, list] of tags) {
if (!l) issues.push({ level: 'warn', text: 'A "Send signal" has no name', nodes: list.map(n => n.id) })
else if (list.length > 1) issues.push({ level: 'error', text: `Signal "${l}" is sent by ${list.length} parts: they drive it against each other`, nodes: list.map(n => n.id) })
else if (!refs.has(l)) issues.push({ level: 'info', text: `Signal "${l}" is sent but not used`, nodes: list.map(n => n.id) })
}
for (const [l, list] of refs) {
if (!tags.has(l)) issues.push({ level: 'error', text: l ? `Nothing sends signal "${l}" (reads 0)` : 'A "Use signal" has no name', nodes: list.map(n => n.id) })
}
const rank: Record<IssueLevel, number> = { error: 0, warn: 1, info: 2 }
return issues.sort((a, b) => rank[a.level] - rank[b.level])
}
/**
* Components made in this project that no other circuit places. Some are
* circuits you work in directly; the rest can go. The examples are left out.
*/
export function unusedComponents(project: Project): ComponentDef[] {
const used = new Set<string>()
for (const d of project.components) for (const n of d.nodes) if (n.kind === 'chip' && n.chip && n.chip !== d.id) used.add(n.chip)
return project.components.filter(d => !used.has(d.id) && !d.id.startsWith('ex-') && !d.challenge)
}