// The assembler tool: your own instruction set, written as a table, turns a // program into words for the memory you built. One instruction per table // line: its name, its opcode bits, then its operands as name:bits. Opcode and // operands fill a word from its top bit down; bits left over are 0, and an // instruction longer than a word takes as many words as it needs. import type { AsmDoc, CircuitNode, ComponentDef } from './logic/types' export type { AsmDoc } export interface AsmError { where: 'table' | 'source' /** 1-based. */ line: number text: string } export interface OpDef { name: string /** Opcode as bits, highest first. */ bits: string fields: { name: string; bits: number }[] } export interface AsmLine { line: number addr: number words: number[] text: string } export interface AsmResult { lines: AsmLine[] /** Memory from address 0 to the last word written; words not written are 0. */ image: number[] labels: Map errors: AsmError[] } export const MAX_WIDTH = 32 export const MAX_WORDS = 65_536 export const EXAMPLE: AsmDoc = { width: 8, table: `; One instruction per line: its name, its opcode bits, then its operands as name:bits. ; Opcode and operands fill the word from its top bit; bits left over are 0. NOP 0000 LDA 0001 addr:4 ADD 0010 addr:4 SUB 0011 addr:4 STA 0100 addr:4 LDI 0101 value:4 JMP 0110 addr:4 JC 0111 addr:4 JZ 1000 addr:4 OUT 1110 HLT 1111`, source: `; Adds 3 again and again and shows it, until it carries past 255. start: LDI 0 loop: ADD three OUT JC done JMP loop done: HLT three: .word 3`, } /** Removes a comment (; or //), leaving quoted text alone. */ function stripComment(line: string): string { let q = '' for (let i = 0; i < line.length; i++) { const c = line[i]! if (q) { if (c === '\\') i++ else if (c === q) q = '' } else if (c === '"' || c === "'") q = c else if (c === ';' || (c === '/' && line[i + 1] === '/')) return line.slice(0, i) } return line } export function parseTable(text: string): { ops: Map; errors: AsmError[] } { const ops = new Map() const errors: AsmError[] = [] text.split('\n').forEach((raw, i) => { const err = (t: string) => errors.push({ where: 'table', line: i + 1, text: t }) const parts = stripComment(raw).trim().split(/[\s,]+/).filter(Boolean) if (!parts.length) return const [name, code, ...rest] = parts if (!/^[A-Za-z_.][\w.]*$/.test(name!)) return err(`"${name}" is not a name for an instruction`) let bits = '' if (code === undefined) return err(`${name}: its opcode bits are missing`) if (/^[01]+$/.test(code)) bits = code else if (/^0x[0-9a-f]+$/i.test(code)) bits = [...code.slice(2)].map(d => parseInt(d, 16).toString(2).padStart(4, '0')).join('') else return err(`${name}: opcode "${code}" is not bits (like 0101, or 0x5 for 4 bits)`) const fields: OpDef['fields'] = [] for (const f of rest) { const m = /^([A-Za-z_]\w*):(\d+)$/.exec(f) if (!m || +m[2]! < 1 || +m[2]! > MAX_WIDTH) return err(`${name}: operand "${f}" should be name:bits, like addr:4`) fields.push({ name: m[1]!, bits: +m[2]! }) } const key = name!.toUpperCase() if (ops.has(key)) return err(`${name} is in the table twice`) ops.set(key, { name: name!, bits, fields }) }) return { ops, errors } } const DIRECTIVES = { word: ['.word', '.db', '.dw', '.byte', '.data', 'db', 'dw'], org: ['.org', 'org'], fill: ['.fill', '.space'], equ: ['.equ', '.set', 'equ'], } const isDir = (w: string, kind: keyof typeof DIRECTIVES) => DIRECTIVES[kind].includes(w.toLowerCase()) /** Splits operands at commas outside quotes. */ function splitArgs(s: string): string[] { const out: string[] = [] let cur = '' let q = '' for (let i = 0; i < s.length; i++) { const c = s[i]! if (q) { cur += c if (c === '\\') cur += s[++i] ?? '' else if (c === q) q = '' } else if (c === '"' || c === "'") { q = c cur += c } else if (c === ',') { out.push(cur.trim()) cur = '' } else cur += c } if (cur.trim()) out.push(cur.trim()) return out } const ESC: Record = { n: '\n', t: '\t', r: '\r', '0': '\0', '\\': '\\', '"': '"', "'": "'" } const unescape = (s: string) => s.replace(/\\(.)/g, (_, c: string) => ESC[c] ?? c) /** A number, a character, a name, or several joined by + and -. `$` alone is the address of this line. */ function evaluate(expr: string, names: Map, here: number): number | string { const tokens = expr.replace(/\s+/g, '').match(/[+-]|'(?:\\.|[^'])'|[^+-]+/g) if (!tokens) return 'nothing to work out' let total = 0 let sign = 1 let expectTerm = true for (const t of tokens) { if (t === '+' || t === '-') { if (expectTerm) sign *= t === '-' ? -1 : 1 else { sign = t === '-' ? -1 : 1 expectTerm = true } continue } let v: number if (/^\d+$/.test(t)) v = parseInt(t, 10) else if (/^0x[0-9a-f]+$/i.test(t)) v = parseInt(t.slice(2), 16) else if (/^\$[0-9a-f]+$/i.test(t)) v = parseInt(t.slice(1), 16) else if (/^[0-9][0-9a-f]*h$/i.test(t)) v = parseInt(t.slice(0, -1), 16) else if (/^0b[01]+$/i.test(t)) v = parseInt(t.slice(2), 2) else if (/^0o[0-7]+$/i.test(t)) v = parseInt(t.slice(2), 8) else if (/^'(\\.|[^'])'$/.test(t)) v = unescape(t.slice(1, -1)).codePointAt(0)! else if (t === '$') v = here else if (/^[A-Za-z_.][\w.]*$/.test(t)) { const n = names.get(t.toLowerCase()) if (n === undefined) return `"${t}" is not a label or name` v = n } else return `"${t}" is not a number or name` if (!expectTerm) return `"${t}" needs a + or - before it` total += sign * v sign = 1 expectTerm = false } if (expectTerm) return 'ends with + or -' return total } /** A value as bits of a field; fits when it is 0 to 2^bits - 1, or negative down to -2^(bits-1) (two's complement). */ function fieldBits(v: number, bits: number): string | null { if (!Number.isInteger(v) || v >= 2 ** bits || v < -(2 ** (bits - 1))) return null return (v < 0 ? v + 2 ** bits : v).toString(2).padStart(bits, '0') } interface Stmt { line: number text: string addr: number kind: 'op' | 'word' | 'fill' op?: OpDef args: string[] size: number } export function assemble(source: string, table: string, width: number): AsmResult { const errors: AsmError[] = [] const t = parseTable(table) errors.push(...t.errors) const w = Math.round(width) if (!(w >= 1 && w <= MAX_WIDTH)) { errors.push({ where: 'source', line: 0, text: `A word is 1 to ${MAX_WIDTH} bits` }) return { lines: [], image: [], labels: new Map(), errors } } const names = new Map() const labels = new Map() const stmts: Stmt[] = [] let addr = 0 // Pass 1: where everything goes. source.split('\n').forEach((raw, i) => { const line = i + 1 const err = (text: string) => errors.push({ where: 'source', line, text }) let s = stripComment(raw).trim() const text = s // Labels at the start. for (let m = /^([A-Za-z_.][\w.]*):/.exec(s); m; m = /^([A-Za-z_.][\w.]*):/.exec(s)) { const key = m[1]!.toLowerCase() if (names.has(key)) err(`${m[1]} is defined twice`) names.set(key, addr) labels.set(m[1]!, addr) s = s.slice(m[0].length).trim() } if (!s) return // NAME = value, NAME equ value, .equ NAME, value const eq = /^([A-Za-z_][\w]*)\s*(?:=|\s+equ\s+)(.+)$/i.exec(s) ?? (/^\.(?:equ|set)\s+([A-Za-z_]\w*)\s*[,\s]\s*(.+)$/i.exec(s) as RegExpExecArray | null) if (eq) { const v = evaluate(eq[2]!, names, addr) if (typeof v === 'string') return err(v) if (names.has(eq[1]!.toLowerCase())) return err(`${eq[1]} is defined twice`) names.set(eq[1]!.toLowerCase(), v) return } const [word] = s.split(/\s+/) const rest = s.slice(word!.length).trim() const args = splitArgs(rest) if (isDir(word!, 'org')) { const v = evaluate(rest, names, addr) if (typeof v === 'string') return err(`.org: ${v}`) if (v < 0 || v >= MAX_WORDS) return err(`.org: address ${v} is outside 0 to ${MAX_WORDS - 1}`) addr = v return } if (isDir(word!, 'word')) { let size = 0 for (const a of args) size += /^"(.*)"$/.test(a) ? [...unescape(a.slice(1, -1))].length : 1 if (!args.length) return err(`${word}: no values`) stmts.push({ line, text, addr, kind: 'word', args, size }) addr += size return } if (isDir(word!, 'fill')) { const n = evaluate(args[0] ?? '', names, addr) if (typeof n === 'string') return err(`${word}: ${n} (the count must be known by here)`) if (n < 0 || n > MAX_WORDS) return err(`${word}: ${n} words is too many`) stmts.push({ line, text, addr, kind: 'fill', args: args.slice(1), size: n }) addr += n return } const op = t.ops.get(word!.toUpperCase()) if (!op) return err(`"${word}" is not in the instruction set`) const total = op.bits.length + op.fields.reduce((n, f) => n + f.bits, 0) const size = Math.max(1, Math.ceil(total / w)) stmts.push({ line, text, addr, kind: 'op', op, args, size }) addr += size }) // Pass 2: the words. const lines: AsmLine[] = [] const used = new Map() let top = 0 for (const st of stmts) { const err = (text: string) => errors.push({ where: 'source', line: st.line, text }) // Its addresses, taken even when it has an error, so a clash still shows. for (let k = 0; k < st.size; k++) { const a = st.addr + k if (a >= MAX_WORDS) { err(`goes past address ${MAX_WORDS - 1}`) break } const before = used.get(a) if (before !== undefined) { err(`address ${a} is also written by line ${before}`) break } used.set(a, st.line) } const words: number[] = [] if (st.kind === 'op') { const op = st.op! if (st.args.length !== op.fields.length) { err(`${op.name} takes ${op.fields.length ? op.fields.map(f => f.name).join(', ') : 'no operands'}${st.args.length ? `, not ${st.args.length}` : ''}`) continue } let bits = op.bits let ok = true op.fields.forEach((f, k) => { const v = evaluate(st.args[k]!, names, st.addr) if (typeof v === 'string') { ok = false return err(`${op.name} ${f.name}: ${v}`) } const b = fieldBits(v, f.bits) if (b === null) { ok = false return err(`${op.name} ${f.name}: ${v} does not fit in ${f.bits} bits`) } bits += b }) if (!ok) continue bits = bits.padEnd(st.size * w, '0') for (let k = 0; k < st.size; k++) words.push(parseInt(bits.slice(k * w, (k + 1) * w), 2)) } else if (st.kind === 'word') { for (const a of st.args) { if (/^"(.*)"$/.test(a)) { for (const c of unescape(a.slice(1, -1))) { const v = c.codePointAt(0)! if (fieldBits(v, w) === null) err(`"${c}" (${v}) does not fit in ${w} bits`) words.push(v) } continue } const v = evaluate(a, names, st.addr + words.length) if (typeof v === 'string') { err(v) words.push(0) continue } const b = fieldBits(v, w) if (b === null) err(`${v} does not fit in ${w} bits`) words.push(b === null ? 0 : parseInt(b, 2)) } } else { const v = st.args[0] ? evaluate(st.args[0], names, st.addr) : 0 const b = typeof v === 'string' ? null : fieldBits(v, w) if (typeof v === 'string') err(v) else if (b === null) err(`${v} does not fit in ${w} bits`) for (let k = 0; k < st.size; k++) words.push(b === null ? 0 : parseInt(b, 2)) } top = Math.max(top, st.addr + words.length) lines.push({ line: st.line, addr: st.addr, words, text: st.text }) } const image = new Array(Math.min(top, MAX_WORDS)).fill(0) for (const l of lines) l.words.forEach((v, k) => l.addr + k < image.length && (image[l.addr + k] = v)) errors.sort((a, b) => (a.where === b.where ? a.line - b.line : a.where === 'table' ? -1 : 1)) return { lines, image, labels, errors } } /** A word as hex or binary digits of the word width. */ export const hexWord = (v: number, width: number) => v.toString(16).toUpperCase().padStart(Math.ceil(width / 4), '0') export const binWord = (v: number, width: number) => v.toString(2).padStart(width, '0') // ── Into memory you built ──────────────────────────────────────────── /** * The input panels of a circuit that can hold words: all their rows are * switches. In reading order: rows of panels top to bottom (panels whose * tops are within half a panel of each other are one row), each left to right. */ export function memoryPanels(def: ComponentDef): CircuitNode[] { const list = def.nodes.filter(n => n.kind === 'panel' && n.rows?.length && n.rows.every(r => r.type === 'switch')).sort((a, b) => a.y - b.y || a.x - b.x) const rows: CircuitNode[][] = [] for (const n of list) { const row = rows[rows.length - 1] const top = row?.[0] if (top && n.y - top.y < Math.max(1, (top.rows!.length) / 2)) row.push(n) else rows.push([n]) } return rows.flatMap(r => r.sort((a, b) => a.x - b.x)) } /** * Puts words into a circuit's memory panels, one word a panel; panels left * over go to 0. Row i of a panel is bit i (or, with `msbTop`, the top row is * the highest bit). A panel with fewer rows than a word has bits refuses. */ export function loadIntoPanels(def: ComponentDef, words: number[], width: number, msbTop = false): { ok: true; panels: number; cleared: number } | { ok: false; error: string } { const panels = memoryPanels(def) if (!panels.length) return { ok: false, error: `"${def.name}" has no input panel of switches to hold the words` } if (words.length > panels.length) return { ok: false, error: `${words.length} words, but "${def.name}" has ${panels.length} panel${panels.length === 1 ? '' : 's'} of switches` } const short = panels.find(p => p.rows!.length < width) if (short) return { ok: false, error: `A panel in "${def.name}" has ${short.rows!.length} switches, a word ${width} bits` } panels.forEach((p, i) => { const v = words[i] ?? 0 p.rows!.forEach((r, k) => { const bit = msbTop ? width - 1 - k : k r.on = bit >= 0 && bit < width && Math.floor(v / 2 ** bit) % 2 === 1 }) }) return { ok: true, panels: words.length, cleared: panels.length - words.length } }