"""The HDCSTORAGE instruction set. An instruction is not a word in a flat array — it *is* a hypervector, built the canonical VSA way: instr = bundle([ bind(role("op"), hvc("op/ADD")), bind(role("ra"), hvc("reg/R2")), bind(role("rb"), hvc("reg/R0")), bind(role("rc"), hvc("reg/R1")), ]) The program counter therefore indexes *cells*, and the decoder never reads a bit field at a fixed offset. It unbinds each role (``instr ^ role``, self- inverse) and runs cleanup: nearest match over the opcode alphabet, the register alphabet, the literal table. Every decode reports its own clearance (best similarity and margin over the runner-up), so the machine can say *how confident* it was that this cell said ADD. Measured on this implementation at d=10 000: members of a 4-5 field bundle recover at similarity ~0.37-0.50 against a random-vector noise floor of 0.010 sd, which makes a 32-opcode x 16-register alphabet decode exactly in practice. Field presence is detected the same way: an absent role unbinds to noise, so "is this field here?" and "what does it say?" are one test. Operand slots by kind: reg -> ra, rb, rc in operand order imm -> role("imm"), value hvc("lit/") label -> role("tgt"), value hvc("pc/") name -> role("imm"), value hvc("name/") (a storage cell name) str -> role("imm"), value hvc("str/") (a string literal) tool -> role("imm"), value hvc("tool/") (an MCP tool) """ from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable, Sequence from .hypervec import DEFAULT_DIM, bind, bundle, hvc, mask, role, sim #: A field counts as present when its best cleanup similarity clears this. #: Noise floor is ~0.010-0.020; a genuine bundle member sits at 0.27-0.50. PRESENCE = 0.12 REG_COUNT = 16 REG_NAMES: tuple[str, ...] = tuple("R%d" % i for i in range(REG_COUNT)) @dataclass(frozen=True) class Opcode: """One entry of the instruction set.""" name: str operands: str effect: str doc: str @property def operand_list(self) -> list[str]: return [o.strip() for o in self.operands.split(",") if o.strip()] _RAW_OPCODES: tuple[tuple[str, str, str, str], ...] = ( # name operands effect documentation ("NOP", "", "ctrl", "Do nothing; the vector still decodes."), ("HALT", "", "ctrl", "Stop the machine."), ("LDI", "reg,imm", "alu", "Load an integer literal, HDC-coded, into a register."), ("MOV", "reg,reg", "alu", "Copy one hypervector register to another."), ("ADD", "reg,reg,reg", "alu", "Integer add of two decoded registers."), ("SUB", "reg,reg,reg", "alu", "Integer subtract."), ("MUL", "reg,reg,reg", "alu", "Integer multiply."), ("DIV", "reg,reg,reg", "alu", "Integer divide (ra = rb // rc; zero yields 0)."), ("AND", "reg,reg,reg", "alu", "Bitwise AND of decoded integers."), ("OR", "reg,reg,reg", "alu", "Bitwise OR of decoded integers."), ("XOR", "reg,reg,reg", "alu", "Bitwise XOR of decoded integers."), ("NOT", "reg,reg", "alu", "Bitwise complement."), ("SHL", "reg,reg,imm", "alu", "Shift left by an immediate."), ("SHR", "reg,reg,imm", "alu", "Shift right by an immediate."), ("POPC", "reg,reg", "alu", "Population count of a raw hypervector."), ("CMP", "reg,reg", "alu", "Compare decoded integers; sets the zero flag."), ("JMP", "label", "ctrl", "Jump to a program cell."), ("JZ", "label", "ctrl", "Jump if the zero flag is set."), ("JNZ", "label", "ctrl", "Jump if the zero flag is clear."), ("CALL", "label", "ctrl", "Push the return cell and jump."), ("RET", "", "ctrl", "Return to the pushed cell."), ("PUSH", "reg", "mem", "Push a register onto the stack."), ("POP", "reg", "mem", "Pop the stack into a register."), ("BIND", "reg,reg,reg", "hd", "XOR-bind two hypervectors into a register."), ("BUNDLE", "reg,reg,reg", "hd", "Majority-bundle two hypervectors into a register."), ("PERMUTE", "reg,reg,imm", "hd", "Rotate a hypervector by an immediate."), ("SIM", "reg,reg,reg", "hd", "Similarity of two registers, scaled to milli-units."), ("CLEAN", "reg,reg", "hd", "Cleanup: index of the symbol nearest to a register."), ("STORE", "name,reg", "mem", "Store a register into a named HDC cell."), ("LOAD", "reg,name", "mem", "Load a named HDC cell into a register."), ("RECALL", "reg,reg,imm", "mem", "Associative search: nearest stored cell to a register."), ("MEMSTAT", "reg", "mem", "Write storage occupancy statistics into a register."), ("OUT", "reg", "io", "Print a register's decoded integer."), ("OUTT", "reg", "io", "Print the symbol name nearest to a register."), ("PRINTS", "str", "io", "Print a string literal."), ("TOOL", "reg,reg,reg,tool", "tool", "Call an MCP tool held in HDC storage."), ("BREAK", "", "debug", "Trap into the debugger."), ) OPCODES: dict[str, Opcode] = { name: Opcode(name, operands, effect, doc) for name, operands, effect, doc in _RAW_OPCODES } OPCODE_NAMES: tuple[str, ...] = tuple(OPCODES) #: Operand slots, in binding order. _REG_SLOTS = ("ra", "rb", "rc") class DecodeError(Exception): """Raised when a hypervector cannot be read as an instruction.""" @dataclass class DecodedInstr: """A decoded instruction plus how much of it the machine actually trusts.""" op: str regs: list[int] = field(default_factory=list) imm: int | None = None tgt: int | None = None name: str | None = None text: str | None = None tool: str | None = None confidence: float = 0.0 margins: dict[str, float] = field(default_factory=dict) raw: int = 0 source_line: str = "" def __str__(self) -> str: # pragma: no cover - formatting only return self.text or self.op @dataclass class DecodeContext: """Alphabets cleanup memory is allowed to use when reading a cell.""" d: int = DEFAULT_DIM imms: Sequence[int] = () tgts: Sequence[int] = () names: Sequence[str] = () strs: Sequence[str] = () tools: Sequence[str] = () @classmethod def of(cls, image: "object", d: int = DEFAULT_DIM) -> "DecodeContext": """Build a context from an assembled image.""" return cls( d=getattr(image, "d", d), imms=tuple(getattr(image, "literals", ())), tgts=tuple(range(len(getattr(image, "instrs", ())))), names=tuple(getattr(image, "cell_names", ())), strs=tuple(getattr(image, "strings", ())), tools=tuple(getattr(image, "tools", ())), ) # -------------------------------------------------------------------------- # encoding # -------------------------------------------------------------------------- def op_hv(name: str, d: int = DEFAULT_DIM) -> int: return hvc("op/" + name, d) def reg_hv(index: int, d: int = DEFAULT_DIM) -> int: return hvc("reg/R%d" % index, d) def imm_hv(value: int, d: int = DEFAULT_DIM) -> int: return hvc("lit/%d" % value, d) def tgt_hv(pc: int, d: int = DEFAULT_DIM) -> int: return hvc("pc/%d" % pc, d) def name_hv(name: str, d: int = DEFAULT_DIM) -> int: return hvc("name/" + name, d) def str_hv(text: str, d: int = DEFAULT_DIM) -> int: return hvc("str/" + text, d) def tool_hv(name: str, d: int = DEFAULT_DIM) -> int: return hvc("tool/" + name, d) def encode_instr( op: str, *, regs: Sequence[int] = (), imm: int | None = None, tgt: int | None = None, name: str | None = None, text: str | None = None, tool: str | None = None, d: int = DEFAULT_DIM, ) -> int: """Compose an instruction hypervector. Every present field contributes one ``bind(role, value)`` term; majority bundling superposes them. With <= 5 terms each component still recovers at ~0.31-0.50 similarity, far above the noise floor, which is precisely why the decoder works at all. """ if op not in OPCODES: raise DecodeError("unknown opcode %r" % (op,)) parts = [bind(role("op", d), op_hv(op, d), d)] regs = tuple(regs) if len(regs) > len(_REG_SLOTS): raise DecodeError("at most %d register operands" % len(_REG_SLOTS)) for slot, idx in zip(_REG_SLOTS, regs): if not 0 <= idx < REG_COUNT: raise DecodeError("register index out of range: %r" % (idx,)) parts.append(bind(role(slot, d), reg_hv(idx, d), d)) if imm is not None: parts.append(bind(role("imm", d), imm_hv(imm, d), d)) if tgt is not None: parts.append(bind(role("tgt", d), tgt_hv(tgt, d), d)) if name is not None: parts.append(bind(role("imm", d), name_hv(name, d), d)) if text is not None: parts.append(bind(role("imm", d), str_hv(text, d), d)) if tool is not None: parts.append(bind(role("imm", d), tool_hv(tool, d), d)) return bundle(parts, d) # -------------------------------------------------------------------------- # decoding (compute-in-memory) # -------------------------------------------------------------------------- def _argmax( probe: int, cands: Iterable[tuple[object, int]], d: int ) -> tuple[object | None, float, float]: """Return (best candidate, best similarity, margin over runner-up).""" first = -2.0 second = -2.0 best: object | None = None for key, hv in cands: s = sim(probe, hv, d) if s > first: second = first first = s best = key elif s > second: second = s return best, first, (first - second if best is not None else 0.0) def _candidates(kinds: Sequence[str], ctx: DecodeContext) -> dict[str, list[tuple[object, int]]]: d = ctx.d table: dict[str, list[tuple[object, int]]] = { "op": [(n, op_hv(n, d)) for n in OPCODE_NAMES], "reg": [(i, reg_hv(i, d)) for i in range(REG_COUNT)], "imm": [], "tgt": [], "name": [], "str": [], "tool": [], } for kind in kinds: if kind == "imm": table["imm"] = [(v, imm_hv(v, d)) for v in ctx.imms] elif kind == "tgt": table["tgt"] = [(v, tgt_hv(v, d)) for v in ctx.tgts] elif kind == "name": table["name"] = [(v, name_hv(v, d)) for v in ctx.names] elif kind == "str": table["str"] = [(v, str_hv(v, d)) for v in ctx.strs] elif kind == "tool": table["tool"] = [(v, tool_hv(v, d)) for v in ctx.tools] return table def decode_instr(hv: int, ctx: DecodeContext | None = None) -> DecodedInstr: """Read a hypervector as an instruction using cleanup memory only. Three stages, all similarity-based: 1. unbind ``role("op")`` and clean up over the opcode alphabet; 2. ask the opcode which operand kinds it expects, and read exactly those slots (so a ``LDI`` never tries to interpret a target field); 3. for each operand, clean up over the matching alphabet and record the margin, which is the decoder's self-reported confidence. """ ctx = ctx or DecodeContext() d = ctx.d table = _candidates(("imm", "tgt", "name", "str", "tool"), ctx) op_name, op_s, op_margin = _argmax(bind(hv, role("op", d), d), table["op"], d) if op_name is None: raise DecodeError("no opcode alphabet") spec = OPCODES[op_name] out = DecodedInstr(op=str(op_name), raw=hv, confidence=op_s, margins={"op": op_margin}) reg_slot = 0 for kind in spec.operand_list: if kind == "reg": slot = _REG_SLOTS[reg_slot] reg_slot += 1 idx, s, m = _argmax(bind(hv, role(slot, d), d), table["reg"], d) out.regs.append(int(idx)) out.confidence = min(out.confidence, s) out.margins["r" + slot[-1]] = m continue # every non-register operand shares role("imm")/role("tgt"), but each # kind is rebuilt from its own namespace, so the alphabet a field is # cleaned up against must follow the declared operand kind. slot = "tgt" if kind == "label" else "imm" probe = bind(hv, role(slot, d), d) cands = table["tgt" if kind == "label" else kind] key, s, m = _argmax(probe, cands, d) if kind == "imm": out.imm = int(key) if key is not None else None elif kind == "label": out.tgt = int(key) if key is not None else None elif kind == "name": out.name = str(key) if key is not None else None elif kind == "str": out.text = str(key) if key is not None else None elif kind == "tool": out.tool = str(key) if key is not None else None out.confidence = min(out.confidence, s) out.margins[kind] = m return out def format_operands(dec: DecodedInstr) -> str: """Render an instruction's operands as assembler source.""" parts: list[str] = [] reg_i = 0 for kind in OPCODES[dec.op].operand_list: if kind == "reg": parts.append(REG_NAMES[dec.regs[reg_i]]) reg_i += 1 elif kind == "imm": parts.append(str(dec.imm)) elif kind == "label": parts.append("@%d" % dec.tgt if dec.tgt is not None else "@?") elif kind == "name": parts.append(str(dec.name)) elif kind == "str": parts.append('"%s"' % dec.text) elif kind == "tool": parts.append(str(dec.tool)) return ", ".join(parts) def disassemble(hv: int, ctx: DecodeContext | None = None, pc: int | None = None) -> str: """One-line disassembly with the decode confidence attached.""" dec = decode_instr(hv, ctx) label = "" if pc is None else "%04d " % pc ops = format_operands(dec) return "%s%-8s %-24s conf=%.2f" % (label, dec.op, ops, dec.confidence) def opcode_table_text() -> str: """The ISA reference as plain text (used by the IDE's ``help``).""" lines = ["%-8s %-22s %-6s %s" % ("OP", "OPERANDS", "CLASS", "DESCRIPTION")] lines.append("-" * 78) for name in OPCODE_NAMES: op = OPCODES[name] lines.append("%-8s %-22s %-6s %s" % (op.name, op.operands, op.effect, op.doc)) return "\n".join(lines)