A assembler tool: your own instruction set as a table, labels, constants, .org/.word/.fill; copy as hex or binary, or load into the switch panels of memory you built
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
6f60462d44
commit
52aea3fe96
|
|
@ -5911,3 +5911,118 @@ button.tile:hover {
|
|||
.convert-table td {
|
||||
padding: 2px 10px 2px 0;
|
||||
}
|
||||
|
||||
/* Assembler */
|
||||
.modal.asm {
|
||||
width: min(1100px, 100%);
|
||||
}
|
||||
|
||||
.modal.asm code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.asm-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.asm-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.asm-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.asm-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.asm-bar .hint {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.asm-width {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.asm-width input {
|
||||
width: 56px;
|
||||
padding: 3px 6px;
|
||||
}
|
||||
|
||||
.asm-text {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
resize: vertical;
|
||||
tab-size: 8;
|
||||
}
|
||||
|
||||
.asm-errors {
|
||||
font-size: 12px;
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.asm-errors span {
|
||||
display: inline-block;
|
||||
min-width: 56px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.asm-fold {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 4px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.asm-fold .hint {
|
||||
margin: 0;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.asm-listing {
|
||||
max-height: 330px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.asm-src {
|
||||
color: var(--muted);
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.asm-load {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.asm-load .hint {
|
||||
margin: 0;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,5 +85,6 @@ watch(
|
|||
<EditorLibraryDialog v-if="ed.dialog.value === 'library'" />
|
||||
<EditorLibraryPublishDialog v-if="ed.dialog.value === 'library-publish'" />
|
||||
<EditorConvertDialog v-if="ed.dialog.value === 'convert'" />
|
||||
<EditorAsmDialog v-if="ed.dialog.value === 'asm'" />
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,128 @@
|
|||
<script setup lang="ts">
|
||||
// The assembler: a program in your own instruction set becomes words, which
|
||||
// copy out as hex or binary or go straight into the switch panels of the
|
||||
// memory you built.
|
||||
import { assemble, binWord, hexWord, MAX_WIDTH, memoryPanels } from '~/lib/asm'
|
||||
|
||||
const ed = useEditor()
|
||||
const close = () => (ed.dialog.value = null)
|
||||
const doc = ed.asmDoc
|
||||
|
||||
const result = computed(() => assemble(doc.value.source, doc.value.table, doc.value.width))
|
||||
const sourceErrors = computed(() => result.value.errors.filter(e => e.where === 'source'))
|
||||
const tableErrors = computed(() => result.value.errors.filter(e => e.where === 'table'))
|
||||
const showTable = ref(!ed.project.value.asm)
|
||||
|
||||
/** Circuits with panels of switches to hold words. */
|
||||
const targets = computed(() =>
|
||||
ed.project.value.components
|
||||
.map(d => {
|
||||
const panels = memoryPanels(d)
|
||||
const rows = Math.min(...panels.map(p => p.rows!.length))
|
||||
return { d, panels, rows, outside: d.id === ed.def.value.id ? 0 : panels.filter(p => !p.inner).length }
|
||||
})
|
||||
.filter(t => t.panels.length),
|
||||
)
|
||||
const target = computed(() => targets.value.find(t => t.d.id === doc.value.target) ?? targets.value.find(t => t.d.id === ed.def.value.id) ?? targets.value[0])
|
||||
|
||||
function setWidth(e: Event) {
|
||||
const v = Math.round(Number((e.target as HTMLInputElement).value))
|
||||
if (v >= 1 && v <= MAX_WIDTH) ed.saveAsm({ width: v })
|
||||
}
|
||||
const copyAll = (fmt: 'hex' | 'bin') => ed.copyText(result.value.image.map(v => (fmt === 'hex' ? hexWord(v, doc.value.width) : binWord(v, doc.value.width))).join(' '), `${result.value.image.length} words copied`)
|
||||
function load() {
|
||||
const t = target.value
|
||||
if (t) ed.loadProgram(t.d.id, result.value.image, doc.value.width, !!doc.value.msbTop)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal-backdrop" @click.self="close">
|
||||
<div class="modal asm" role="dialog" aria-labelledby="asm-title">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<h2 id="asm-title">Assembler</h2>
|
||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||
</div>
|
||||
<p class="hint">
|
||||
Your own instruction set turns a program into words for the memory you built. Labels end with <code>:</code>, comments start with <code>;</code>.
|
||||
<code>.org 16</code> moves on to an address, <code>.word 1, 'A', "Hi"</code> puts words as they are, <code>.fill 4, 0</code> repeats one, <code>N = 5</code> names a value.
|
||||
</p>
|
||||
|
||||
<div class="asm-grid">
|
||||
<div class="asm-col">
|
||||
<div class="asm-bar">
|
||||
<span class="font-semibold">Program</span>
|
||||
<span class="grow" />
|
||||
<label class="asm-width" title="Bits per memory word">
|
||||
Word
|
||||
<input type="number" min="1" :max="MAX_WIDTH" :value="doc.width" class="field-input" @change="setWidth" />
|
||||
bits
|
||||
</label>
|
||||
</div>
|
||||
<textarea class="field-input asm-text" spellcheck="false" rows="14" :value="doc.source" @input="ed.saveAsm({ source: ($event.target as HTMLTextAreaElement).value })" />
|
||||
<ul v-if="sourceErrors.length" class="asm-errors">
|
||||
<li v-for="(e, i) in sourceErrors.slice(0, 20)" :key="i"><span class="tabular-nums">Line {{ e.line }}</span> {{ e.text }}</li>
|
||||
</ul>
|
||||
<button class="asm-fold" @click="showTable = !showTable">
|
||||
<Icon :name="showTable ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-3.5" />
|
||||
Instruction set
|
||||
<span class="hint">{{ tableErrors.length ? `${tableErrors.length} to fix` : 'name, opcode bits, operands as name:bits' }}</span>
|
||||
</button>
|
||||
<template v-if="showTable">
|
||||
<textarea class="field-input asm-text" spellcheck="false" rows="10" :value="doc.table" @input="ed.saveAsm({ table: ($event.target as HTMLTextAreaElement).value })" />
|
||||
<ul v-if="tableErrors.length" class="asm-errors">
|
||||
<li v-for="(e, i) in tableErrors.slice(0, 20)" :key="i"><span class="tabular-nums">Line {{ e.line }}</span> {{ e.text }}</li>
|
||||
</ul>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="asm-col">
|
||||
<div class="asm-bar">
|
||||
<span class="font-semibold">Words</span>
|
||||
<span class="hint">{{ result.image.length }} words</span>
|
||||
<span class="grow" />
|
||||
<button class="btn-sm" :disabled="!result.image.length" @click="copyAll('hex')"><Icon name="lucide:copy" class="size-3.5" /> Hex</button>
|
||||
<button class="btn-sm" :disabled="!result.image.length" @click="copyAll('bin')"><Icon name="lucide:copy" class="size-3.5" /> Binary</button>
|
||||
</div>
|
||||
<div class="asm-listing">
|
||||
<table class="convert-table tabular-nums">
|
||||
<thead>
|
||||
<tr><th>Address</th><th>Hex</th><th>Binary</th><th>Line</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-for="l in result.lines.slice(0, 512)" :key="l.line">
|
||||
<tr v-for="(w, k) in l.words.slice(0, 64)" :key="k">
|
||||
<td>{{ hexWord(l.addr + k, 8) }}</td>
|
||||
<td>{{ hexWord(w, doc.width) }}</td>
|
||||
<td>{{ binWord(w, doc.width) }}</td>
|
||||
<td class="asm-src">{{ k ? '' : l.text }}</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="asm-load">
|
||||
<span class="font-semibold">Into memory</span>
|
||||
<p v-if="!targets.length" class="hint">
|
||||
Build memory from input panels of switches, one panel per word (in a component, set them to stay inside). Words then go in here, in reading order.
|
||||
</p>
|
||||
<template v-else>
|
||||
<select class="tb-select" :value="target?.d.id" @change="ed.saveAsm({ target: ($event.target as HTMLSelectElement).value })">
|
||||
<option v-for="t in targets" :key="t.d.id" :value="t.d.id">{{ t.d.name }} · {{ t.panels.length }} panels of {{ t.rows }}</option>
|
||||
</select>
|
||||
<div class="seg" title="Which switch of a panel is bit 0">
|
||||
<button :class="{ active: !doc.msbTop }" @click="ed.saveAsm({ msbTop: false })">Top row is bit 0</button>
|
||||
<button :class="{ active: doc.msbTop }" @click="ed.saveAsm({ msbTop: true })">Top row is the highest bit</button>
|
||||
</div>
|
||||
<p v-if="target?.outside" class="hint">{{ target.outside }} of its panels are inputs when it is placed: set them to stay inside to make them its memory.</p>
|
||||
<button class="btn btn-primary" :disabled="!result.image.length || result.errors.length > 0" @click="load">
|
||||
<Icon name="lucide:download" class="size-3.5" /> Load {{ result.image.length }} words into {{ target?.d.name }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -43,6 +43,7 @@ const ACTIONS: Action[] = [
|
|||
{ id: 'find', label: 'Find anything in the project', icon: 'lucide:search', keys: 'Ctrl+F', aka: 'search where used', run: () => (ed.dialog.value = 'search') },
|
||||
{ id: 'analyzer', label: 'Logic analyzer', icon: 'lucide:activity', aka: 'waveform signals scope trace timing', run: () => (ed.analyzerOpen.value = true) },
|
||||
{ id: 'convert', label: 'Converter: text, hex, binary, decimal', icon: 'lucide:arrow-left-right', aka: 'ascii utf8 unicode base64 octal encode decode', run: () => (ed.dialog.value = 'convert') },
|
||||
{ id: 'asm', label: 'Assembler: program to memory words', icon: 'lucide:file-code-2', aka: 'assembly opcode instruction rom program cpu machine code', run: () => (ed.dialog.value = 'asm') },
|
||||
{ id: 'table', label: 'Truth table', icon: 'lucide:table', aka: 'test outputs', run: () => (ed.dialog.value = 'table') },
|
||||
{ id: 'fit', label: 'Fit the circuit to the screen', icon: 'lucide:scan', keys: 'F', aka: 'zoom view', run: () => emit('fit') },
|
||||
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
|
||||
|
|
|
|||
|
|
@ -144,6 +144,7 @@ const toolsMenu = ref<{ x: number; y: number } | null>(null)
|
|||
const toolEntries = computed<MenuEntry[]>(() => [
|
||||
{ label: 'Logic analyzer', icon: 'lucide:activity', checked: ed.analyzerOpen.value, note: 'signals over time', run: () => (ed.analyzerOpen.value = !ed.analyzerOpen.value) },
|
||||
{ label: 'Converter…', icon: 'lucide:arrow-left-right', note: 'text, hex, binary', run: () => (ed.dialog.value = 'convert') },
|
||||
{ label: 'Assembler…', icon: 'lucide:file-code-2', note: 'program to memory', run: () => (ed.dialog.value = 'asm') },
|
||||
])
|
||||
|
||||
// The names folded into "…": each leads back to it.
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic
|
|||
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
|
||||
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
|
||||
import { probeValue } from '~/lib/logic/probes'
|
||||
import { EXAMPLE as ASM_EXAMPLE, loadIntoPanels } from '~/lib/asm'
|
||||
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
|
||||
import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library'
|
||||
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
|
||||
|
|
@ -81,7 +82,7 @@ import {
|
|||
type AccountUser,
|
||||
type ProjectMeta,
|
||||
} from '~/lib/logic/storage'
|
||||
import type { CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, Probe, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
|
||||
import type { AsmDoc, CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, Probe, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
|
||||
|
||||
/** A challenge check plus how many transistors the solution uses. */
|
||||
/** How everyone did on a puzzle, from the server. */
|
||||
|
|
@ -1327,6 +1328,30 @@ function create() {
|
|||
commit()
|
||||
}
|
||||
|
||||
// ── Assembler ─────────────────────────────────────────────────────
|
||||
/** The assembler's texts, kept in the project (not undo steps). */
|
||||
const asmDoc = computed<AsmDoc>(() => project.value.asm ?? { ...ASM_EXAMPLE })
|
||||
function saveAsm(patch: Partial<AsmDoc>) {
|
||||
project.value.asm = { ...asmDoc.value, ...patch }
|
||||
persist()
|
||||
}
|
||||
|
||||
/** Puts assembled words into the switch panels of a circuit (one word a panel). An undo step. */
|
||||
function loadProgram(targetId: string, words: number[], width: number, msbTop: boolean): boolean {
|
||||
const target = getDef.value(targetId)
|
||||
if (!target) return false
|
||||
const res = loadIntoPanels(target, words, width, msbTop)
|
||||
if (!res.ok) {
|
||||
notify(res.error, 'error')
|
||||
play('error')
|
||||
return false
|
||||
}
|
||||
commit()
|
||||
notify(`Loaded ${res.panels} word${res.panels === 1 ? '' : 's'} into "${target.name}"${res.cleared ? `, ${res.cleared} more panel${res.cleared === 1 ? '' : 's'} set to 0` : ''}`)
|
||||
play('place')
|
||||
return true
|
||||
}
|
||||
|
||||
/** Every row of an input panel the same kind: all switches, all buttons or all clocks. */
|
||||
function setRowsType(panel: CircuitNode, type: PanelControl) {
|
||||
for (const r of panel.rows ?? []) {
|
||||
|
|
@ -2876,6 +2901,9 @@ function create() {
|
|||
setRowsType,
|
||||
setScreen,
|
||||
setRgb,
|
||||
asmDoc,
|
||||
saveAsm,
|
||||
loadProgram,
|
||||
screen,
|
||||
menuPage,
|
||||
challengesOpen,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,394 @@
|
|||
// 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<string, number>
|
||||
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<string, OpDef>; errors: AsmError[] } {
|
||||
const ops = new Map<string, OpDef>()
|
||||
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<string, string> = { 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<string, number>, 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<string, number>()
|
||||
const labels = new Map<string, number>()
|
||||
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<number, number>()
|
||||
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<number>(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 }
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ import {
|
|||
LAMP_COLORS,
|
||||
PANEL_CONTROLS,
|
||||
WIRE_COLORS,
|
||||
type AsmDoc,
|
||||
type CircuitNode,
|
||||
type ComponentDef,
|
||||
type ConnectorType,
|
||||
|
|
@ -171,6 +172,21 @@ export function toProject(data: unknown): Project {
|
|||
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
|
||||
...(connectorsOf(p.connectors) ? { connectors: connectorsOf(p.connectors)! } : {}),
|
||||
...(stateOf(p.state, p.components) ? { state: stateOf(p.state, p.components)! } : {}),
|
||||
...(asmOf(p.asm) ? { asm: asmOf(p.asm)! } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** The assembler's texts, if they are texts (long ones cut). */
|
||||
function asmOf(a: unknown): AsmDoc | null {
|
||||
const d = a as Partial<AsmDoc> | null
|
||||
if (!d || typeof d !== 'object' || typeof d.table !== 'string' || typeof d.source !== 'string') return null
|
||||
const width = Number.isInteger(d.width) && d.width! >= 1 && d.width! <= 32 ? d.width! : 8
|
||||
return {
|
||||
table: d.table.slice(0, 50_000),
|
||||
source: d.source.slice(0, 200_000),
|
||||
width,
|
||||
...(typeof d.target === 'string' ? { target: d.target } : {}),
|
||||
...(d.msbTop === true ? { msbTop: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -261,8 +261,25 @@ export interface Project {
|
|||
connectors?: ConnectorType[]
|
||||
/** What each circuit held when it was last open (latches, flip-flops, memory), by circuit id. Empty: it starts from all zeros. */
|
||||
state?: Record<string, HeldState>
|
||||
/** The assembler tool: instruction set, program and where it goes. */
|
||||
asm?: AsmDoc
|
||||
}
|
||||
|
||||
/** The assembler's instruction set and program (see lib/asm). */
|
||||
export interface AsmDoc {
|
||||
/** The instruction set, one instruction per line. */
|
||||
table: string
|
||||
/** The program. */
|
||||
source: string
|
||||
/** Bits per memory word. */
|
||||
width: number
|
||||
/** Circuit whose input panels the words go into. */
|
||||
target?: string
|
||||
/** Each panel's top row is the highest bit (else bit 0). */
|
||||
msbTop?: boolean
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The bits a circuit holds, like the contents of a memory chip: the NANDs on
|
||||
* feedback loops that are 1, and the clocks that are high. Everything else
|
||||
|
|
|
|||
|
|
@ -0,0 +1,103 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { assemble, EXAMPLE, loadIntoPanels, memoryPanels, parseTable } from '../app/lib/asm'
|
||||
|
||||
const TABLE = `
|
||||
LDA 0001 addr:4
|
||||
ADD 0010 addr:4
|
||||
LDI 0101 value:4
|
||||
JMP 0110 addr:4
|
||||
OUT 1110
|
||||
HLT 1111
|
||||
LONG 00000001 value:8 ; two words at 8 bits
|
||||
`
|
||||
const asm = (src: string, width = 8, table = TABLE) => assemble(src, table, width)
|
||||
|
||||
describe('assembler', () => {
|
||||
it('the example assembles without errors', () => {
|
||||
const r = assemble(EXAMPLE.source, EXAMPLE.table, EXAMPLE.width)
|
||||
expect(r.errors).toEqual([])
|
||||
// LDI 0, ADD three(6), OUT, JC done(5), JMP loop(1), HLT, 3
|
||||
expect(r.image).toEqual([0x50, 0x26, 0xe0, 0x75, 0x61, 0xf0, 3])
|
||||
})
|
||||
|
||||
it('opcode then operands from the top bit; bits left over are 0', () => {
|
||||
const r = asm('LDA 3\nOUT\nHLT')
|
||||
expect(r.errors).toEqual([])
|
||||
expect(r.image).toEqual([0x13, 0xe0, 0xf0])
|
||||
})
|
||||
|
||||
it('labels before they are defined, constants, .org, .word with strings and characters, .fill', () => {
|
||||
const r = asm(`
|
||||
N = 2
|
||||
.org 1
|
||||
start: LDA data+N ; forward label plus a constant
|
||||
JMP start
|
||||
.org 0x8
|
||||
data: .word 1, 'A', "Hi", -1
|
||||
.fill 2, $FF`)
|
||||
expect(r.errors).toEqual([])
|
||||
expect(r.labels.get('start')).toBe(1)
|
||||
expect(r.labels.get('data')).toBe(8)
|
||||
expect(r.image).toEqual([0, 0x1a, 0x61, 0, 0, 0, 0, 0, 1, 65, 72, 105, 0xff, 0xff, 0xff])
|
||||
})
|
||||
|
||||
it('an instruction longer than a word takes several words', () => {
|
||||
const r = asm('LONG 200\nHLT')
|
||||
expect(r.errors).toEqual([])
|
||||
expect(r.image).toEqual([1, 200, 0xf0])
|
||||
})
|
||||
|
||||
it('wider words: 12 bits', () => {
|
||||
const r = asm('LDA 15', 12)
|
||||
expect(r.image).toEqual([0x1f0])
|
||||
})
|
||||
|
||||
it('says what is wrong and on which line', () => {
|
||||
const r = asm('LDA 16\nFOO 1\nADD\nLDA nowhere\nx: OUT\nx: HLT\n.org 0\nOUT')
|
||||
const at = (line: number) => r.errors.filter(e => e.where === 'source' && e.line === line).map(e => e.text)
|
||||
expect(at(1)[0]).toMatch(/does not fit in 4 bits/)
|
||||
expect(at(2)[0]).toMatch(/not in the instruction set/)
|
||||
expect(at(3)[0]).toMatch(/takes addr/)
|
||||
expect(at(4)[0]).toMatch(/not a label/)
|
||||
expect(at(6)[0]).toMatch(/defined twice/)
|
||||
expect(at(8)[0]).toMatch(/also written by line 1/)
|
||||
})
|
||||
|
||||
it('a broken table says so', () => {
|
||||
const t = parseTable('LDA 0102 addr:4\nADD 0010 addr\nADD 0011\nADD 0100')
|
||||
expect(t.errors.map(e => e.line)).toEqual([1, 2, 4])
|
||||
expect(parseTable('X 0xA').ops.get('X')!.bits).toBe('1010')
|
||||
})
|
||||
|
||||
it('comments do not cut quoted text', () => {
|
||||
const r = asm('.word ";", \';\' ; comment')
|
||||
expect(r.errors).toEqual([])
|
||||
expect(r.image).toEqual([59, 59])
|
||||
})
|
||||
})
|
||||
|
||||
describe('loading words into panels of switches', () => {
|
||||
const panel = (id: string, x: number, y: number, rows = 4) => ({ id, kind: 'panel' as const, x, y, rows: Array.from({ length: rows }, (_, i) => ({ id: `r${i}`, type: 'switch' as const })) })
|
||||
const def = (nodes: ReturnType<typeof panel>[]) => ({ id: 'rom', name: 'ROM', symbol: 'box' as const, nodes, wires: [] })
|
||||
const bits = (p: ReturnType<typeof panel>) => p.rows.map(r => ((r as { on?: boolean }).on ? 1 : 0)).join('')
|
||||
|
||||
it('in reading order, row i is bit i; panels left over go to 0', () => {
|
||||
// Two rows of panels, the second slightly out of line.
|
||||
const ps = [panel('c', 10, 0), panel('a', 0, 1), panel('d', 0, 8), panel('e', 5, 9), panel('b', 5, 0)]
|
||||
const d = def(ps)
|
||||
expect(memoryPanels(d).map(n => n.id)).toEqual(['a', 'b', 'c', 'd', 'e'])
|
||||
ps[3]!.rows[0]!.on = true
|
||||
const r = loadIntoPanels(d, [1, 2, 0xc, 5], 4)
|
||||
expect(r).toEqual({ ok: true, panels: 4, cleared: 1 })
|
||||
const by = (id: string) => bits(ps.find(p => p.id === id)!)
|
||||
expect([by('a'), by('b'), by('c'), by('d'), by('e')]).toEqual(['1000', '0100', '0011', '1010', '0000'])
|
||||
loadIntoPanels(d, [1], 4, true)
|
||||
expect(by('a')).toBe('0001')
|
||||
})
|
||||
|
||||
it('refuses what does not fit', () => {
|
||||
expect(loadIntoPanels(def([panel('a', 0, 0)]), [1, 2], 4).ok).toBe(false)
|
||||
expect(loadIntoPanels(def([panel('a', 0, 0, 3)]), [1], 4).ok).toBe(false)
|
||||
expect(loadIntoPanels(def([]), [1], 4).ok).toBe(false)
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue