#!/usr/bin/env python3 """MOL/8080 compiler: CPT's Machine Oriented Language for the 8080, to 8080 machine code. MOL/8080 was written by Clarence L. Lehman at CPT Corporation in 1975 to program the CPT word processors; it is described in chapter 2 of the CPT-8000 software specification (1979). A statement moves a value from left to right: `10:L` is MVI L,10, `(BC):A:(DE)` is LDAX B then STAX D, `L-1:L L/=0? /LOOP` is DCR L then JNZ LOOP. This compiler follows the hardware instruction table in that chapter and the macros and conventions seen in the CPT-8000 listings, whose object code it reproduces. python tools/mol8080.py program.mol listing: each MOL line with its 8080 code python tools/mol8080.py program.mol -o program.bin also write the machine code (from --org, default 0) python tools/mol8080.py program.mol --object CPT-style relocatable object (as in the listings) python tools/mol8080.py program.mol --compare file.bin compare the machine code with a binary python tools/mol8080.py program.mol --compare-object file.obj compare with a CPT OBJECT listing (code, labels, entries) The language, as implemented ---------------------------- Lines: a label starts in column 1, statements are indented. Statements are separated by blanks and ended by `;`; text after the last `;` on a line is a comment (so a comment has no `;` in it), and lines with no `;` are comments. Operands: registers A B C D E H L, pairs BC DE HL SP, memory (HL) (BC) (DE), flags FC FI, PORT(n), the stack STK, numbers (decimal; `1010.B` binary; `FF.H` hex; a leading `-`), equates `"NAME"` (from `NAME==value;`), storage labels (`MCURR:HL` loads HL from MCURR), and addresses `P(LABEL)`, `P(LABEL(n))`. Transfers `x:y:z` are evaluated left to right; an expression is computed into its destination with the operators + - * (by 2, 4, ...), ** (and), +* (or), -* (xor), +FC+ (add with carry), -FC- (subtract with borrow), <* and >* (rotate). `A,FC<*1:FC,A` and `FC,A>*1:A,FC` rotate through carry. `A,BC:STK` pushes, `STK:BC,A` pops. Work registers that may be destroyed follow a destination in angle brackets: `HL:DE` is an exchange. `DE:HL/HL:DE` and `STK:HL/HL:STK` are the exchanges. Control: `/LABEL` jumps, `/HL` jumps to HL, `CALL(LABEL)`, `CALL('ENTRY NAME')`, `CALL(n)` (RST n), `RTN`. Conditions end in `?` and govern the next statement or a parenthesised group: flags (`FZ?`, `FZ=0?`, `FC=1?`, `FS?`, `FP=0?`), and comparisons of A with a number, register or (HL) (`A=2?`, `A/=0?`, `A<10?`, `A>99?`), or of a register with zero (`B=0?`). Declarations: `NAME==value;`, `ENTRY('NAME');`, `ENTRY(n);` (interrupt n), `ENTRY;`, `TITLE('...')`, `FILE('...')`, `LOCATION('NAME');` (a separate storage area), `END;`; storage `B;` `W;` `B.5;` and initialised `B(1,FF.H,'TEXT')` `W(1500,P(LABEL))`. """ from __future__ import annotations import argparse import re import sys from dataclasses import dataclass, field REG8 = {"B": 0, "C": 1, "D": 2, "E": 3, "H": 4, "L": 5, "(HL)": 6, "A": 7} REG8_NAMES = "BCDEHLMA" PAIRS = {"BC": 0, "DE": 1, "HL": 2, "SP": 3} PAIR_ASM = {"BC": "B", "DE": "D", "HL": "H", "SP": "SP"} PUSH_CODE = {"BC": 0xC5, "DE": 0xD5, "HL": 0xE5, "A": 0xF5} POP_CODE = {"BC": 0xC1, "DE": 0xD1, "HL": 0xE1, "A": 0xF1} FLAG_CC = {("FZ", 0): (0, "NZ"), ("FZ", 1): (1, "Z"), ("FC", 0): (2, "NC"), ("FC", 1): (3, "C"), ("FP", 0): (4, "PO"), ("FP", 1): (5, "PE"), ("FS", 0): (6, "P"), ("FS", 1): (7, "M")} CC_NAMES = ["NZ", "Z", "NC", "C", "PO", "PE", "P", "M"] ALU = {"+": (0, "ADD", "ADI"), "+FC+": (1, "ADC", "ACI"), "-": (2, "SUB", "SUI"), "-FC-": (3, "SBB", "SBI"), "**": (4, "ANA", "ANI"), "-*": (5, "XRA", "XRI"), "+*": (6, "ORA", "ORI"), "=": (7, "CMP", "CPI")} OPS = ["+FC+", "-FC-", "**", "+*", "-*", "<*", ">*", "*", "+", "-"] class MolError(Exception): pass # ---------------------------------------------------------------- values @dataclass class Value: """A number, or a symbol plus an offset, resolved when everything is known.""" number: int = 0 symbol: str | None = None def __add__(self, n: int) -> "Value": return Value(self.number + n, self.symbol) @property def known(self) -> bool: return self.symbol is None def __str__(self) -> str: if self.symbol is None: return str(self.number) return self.symbol + (f"+{self.number}" if self.number > 0 else f"{self.number}" if self.number else "") def number(text: str) -> int | None: m = re.fullmatch(r"([0-9A-F]+)\.H", text) if m: return int(m.group(1), 16) m = re.fullmatch(r"([01]+)\.B", text) if m: return int(m.group(1), 2) if re.fullmatch(r"[0-9]+", text): return int(text) return None # ---------------------------------------------------------------- code @dataclass class Fixup: offset: int # within the location value: Value size: int # 1 or 2 @dataclass class Location: name: str code: bytearray = field(default_factory=bytearray) fixups: list[Fixup] = field(default_factory=list) base: int = 0 @dataclass class ListingLine: number: int location: str start: int end: int asm: list[str] source: str class Compiler: def __init__(self): self.equates: dict[str, int] = {} self.labels: dict[str, tuple[str, int]] = {} # name -> (location, offset) self.entries: dict[str, tuple[str, int]] = {} self.locations: dict[str, Location] = {"MAIN": Location("MAIN")} self.loc = self.locations["MAIN"] self.listing: list[ListingLine] = [] self.asm: list[str] = [] self.flags_from: str | None = None # the register whose value last set FZ/FS (for R=0? tests) self.skip_count = 0 self.title = "" self.used_as_label: set[str] = set() # -------------------------------------------------------- emission def emit(self, data: list[int], asm: str, value: Value | None = None, size: int = 0): """Emits an opcode; if value is given it is appended as an operand of size bytes.""" self.loc.code.extend(b & 0xFF for b in data) if value is not None: if value.known and size == 1: self.loc.code.append(value.number & 0xFF) else: self.loc.fixups.append(Fixup(len(self.loc.code), value, size)) self.loc.code.extend([0] * size) self.asm.append(asm) def here(self) -> int: return len(self.loc.code) def define_label(self, name: str): if name in self.labels: raise MolError(f"label {name} is defined twice") self.labels[name] = (self.loc.name, self.here()) # -------------------------------------------------------- operands def value_of(self, text: str) -> Value | None: """A constant or address operand: number, "EQUATE", P(LABEL), P(LABEL(n)), 'ENTRY', -x.""" text = text.strip() if text.startswith("-") and len(text) > 1: v = self.value_of(text[1:]) if v is None: return None if not v.known: raise MolError(f"can't negate an address: {text}") return Value(-v.number) n = number(text) if n is not None: return Value(n) m = re.fullmatch(r'"([^"]+)"', text) if m: name = m.group(1).replace(" ", "") if name not in self.equates: raise MolError(f'unknown equate "{m.group(1)}"') return Value(self.equates[name]) m = re.fullmatch(r"P\((.+)\)", text) if m: inner = m.group(1).strip() m2 = re.fullmatch(r"([A-Z][A-Z0-9]*)\((-?\d+)\)", inner) if m2: return Value(int(m2.group(2)), m2.group(1)) if re.fullmatch(r"'[^']+'", inner): return Value(0, inner.strip("'").replace(" ", "")) if re.fullmatch(r"[A-Z][A-Z0-9]*", inner): return Value(0, inner) raise MolError(f"bad address {text}") return None @staticmethod def is_storage(text: str) -> bool: """A storage label used as a memory operand (MCURR:HL, A:MPRIOC), or LABEL(n).""" return (re.fullmatch(r"[A-Z][A-Z0-9]*(\(-?\d+\))?", text) is not None and text not in REG8 and text not in PAIRS and text not in ("STK", "FC", "FI", "RTN")) @staticmethod def storage_value(text: str) -> Value: m = re.fullmatch(r"([A-Z][A-Z0-9]*)(?:\((-?\d+)\))?", text) return Value(int(m.group(2) or 0), m.group(1)) # -------------------------------------------------------- expressions def split_expression(self, text: str) -> tuple[str, list[tuple[str, str]]]: """Splits `A>*2**1` into ('A', [('>*', '2'), ('**', '1')]). A leading '-' belongs to the first term.""" i, depth, quote = 0, 0, None start = 1 if text.startswith("-") else 0 first_end = None parts: list[tuple[str, str]] = [] current_op = None term_start = 0 i = start while i < len(text): c = text[i] if quote: if c == quote: quote = None i += 1 continue if c in "'\"": quote = c i += 1 continue if c == "(": depth += 1 elif c == ")": depth -= 1 elif depth == 0 and i > term_start: op = next((o for o in OPS if text.startswith(o, i)), None) # A trailing .B/.H belongs to the number; FC inside +FC+ is part of the operator. if op and not (op in ("+", "-") and text[i - 1] in ".") and not (op == "*" and text.startswith("**", i - 1)): if first_end is None: first_end = i else: parts.append((current_op, text[term_start:i])) current_op = op i += len(op) term_start = i continue i += 1 if first_end is None: return text, [] parts.append((current_op, text[term_start:])) return text[:first_end], parts # -------------------------------------------------------- statements def statement(self, text: str): text = text.strip() if not text: return # A parenthesised group of statements. if text.startswith("(") and matching(text, 0) == len(text) - 1 and has_top_level_space(text[1:-1]): for s in split_statements(text[1:-1]): self.statement(s) return up = text if up == "RTN": return self.emit([0xC9], "RET") if up == "PAUSE": return self.emit([0x00], "NOP") if up == "WAIT": return self.emit([0x76], "HLT") if up in ("STK:HL/HL:STK", "HL:STK/STK:HL"): return self.emit([0xE3], "XTHL") if up in ("DE:HL/HL:DE", "HL:DE/DE:HL"): self.flags_from = self.flags_from return self.emit([0xEB], "XCHG") if up == "A,FC<*1:FC,A": return self.emit([0x17], "RAL") if up == "FC,A>*1:A,FC": return self.emit([0x1F], "RAR") if up.startswith("/"): return self.jump(None, up[1:]) m = re.fullmatch(r"CALL\((.+)\)", up) if m: return self.call(None, m.group(1)) m = re.fullmatch(r"([A-Z][A-Z0-9 ]*)==(.+)", up) if m: v = self.value_of(m.group(2)) if v is None or not v.known: raise MolError(f"bad equate value {m.group(2)}") self.equates[m.group(1).replace(" ", "")] = v.number return m = re.fullmatch(r"ENTRY(?:\((.*)\))?", up) if m: arg = (m.group(1) or "").strip() if arg: name = arg.strip("'").replace(" ", "") if arg.startswith("'") else f"INTERRUPT{int(arg)}" self.entries[name] = (self.loc.name, self.here()) return m = re.fullmatch(r"(TITLE|FILE)\((.*)\)", up) if m: if m.group(1) == "TITLE": self.title = m.group(2).strip("' ") return m = re.fullmatch(r"LOCATION\('(.+)'\)", up) if m: name = m.group(1).strip() self.loc = self.locations.setdefault(name, Location(name)) return if up == "END": return if self.data(up): return if "?" in up: raise MolError(f"a condition needs a statement after it: {text}") self.chain(up) def data(self, text: str) -> bool: m = re.fullmatch(r"([BW])(?:\.(\d+))?", text) if m: size = (1 if m.group(1) == "B" else 2) * int(m.group(2) or 1) self.loc.code.extend([0] * size) self.asm.append(f"DS {size}") return True m = re.fullmatch(r"([BW])\((.*)\)", text) if not m: return False width = 1 if m.group(1) == "B" else 2 items = split_commas(m.group(2)) shown = [] for item in items: item = item.strip() if item.startswith("'"): for ch in item.strip("'"): self.loc.code.append(ord(ch)) shown.append(item) continue v = self.value_of(item) if v is None and self.is_storage(item): v = self.storage_value(item) if v is None: raise MolError(f"bad data item {item}") if v.known: self.loc.code.extend((v.number & 0xFFFF).to_bytes(2, "little")[:width]) else: self.loc.fixups.append(Fixup(self.here(), v, width)) self.loc.code.extend([0] * width) shown.append(str(v) if not v.known else f"{v.number & 0xFF:02X}H" if width == 1 else f"{v.number & 0xFFFF:04X}H") self.asm.append(("DB " if width == 1 else "DW ") + ",".join(shown)) return True # -------------------------------------------------------- control def jump(self, cc: int | None, target: str): if target == "HL": if cc is not None: raise MolError("/HL can't be conditional") return self.emit([0xE9], "PCHL") if target == "(STK)": return self.emit([0xC9 if cc is None else 0xC0 | cc << 3], "RET" if cc is None else "R" + CC_NAMES[cc]) v = self.target(target) self.flags_from = None if cc is None: self.emit([0xC3], f"JMP {v}", v, 2) else: self.emit([0xC2 | cc << 3], f"J{CC_NAMES[cc]} {v}", v, 2) def call(self, cc: int | None, target: str): target = target.strip() if re.fullmatch(r"[0-7]", target): if cc is not None: raise MolError("CALL(n) can't be conditional") return self.emit([0xC7 | int(target) << 3], f"RST {target}") v = self.target(target) self.flags_from = None if cc is None: self.emit([0xCD], f"CALL {v}", v, 2) else: self.emit([0xC4 | cc << 3], f"C{CC_NAMES[cc]} {v}", v, 2) def target(self, text: str) -> Value: text = text.strip() if text.startswith("'"): return Value(0, text.strip("'").replace(" ", "")) if text.startswith("@"): # the compiler's own labels round conditional code return Value(0, text) v = self.value_of(text) if v is not None: return v if self.is_storage(text): v = self.storage_value(text) self.used_as_label.add(v.symbol) return v raise MolError(f"bad jump or call target {text}") def conditional(self, condition: str, consequent: str): cc = self.condition(condition) c = consequent.strip() if c.startswith("/") and c != "/HL": return self.jump(cc, c[1:]) m = re.fullmatch(r"CALL\((.+)\)", c) if m and not re.fullmatch(r"[0-7]", m.group(1).strip()): return self.call(cc, m.group(1)) if c == "RTN": return self.emit([0xC0 | cc << 3], "R" + CC_NAMES[cc]) # Anything else: jump round it on the opposite condition. self.skip_count += 1 skip = f"@{self.skip_count}" self.jump(cc ^ 1, skip) if "?" in c and not c.startswith("("): cond, _, rest = c.partition("?") self.conditional(cond + "?", rest) else: self.statement(c) self.define_label(skip) def condition(self, text: str) -> int: """Emits any test the condition needs and returns the 8080 condition code that means 'true'.""" text = text.rstrip("?").strip() m = re.fullmatch(r"(FZ|FC|FS|FP)(?:=([01]))?", text) if m: return FLAG_CC[(m.group(1), int(m.group(2) or 1))][0] m = re.fullmatch(r"(.+?)(/=|<=|>=|=|<|>)(.+)", text) if not m: raise MolError(f"bad condition {text}?") left, op, right = m.group(1), m.group(2), m.group(3) zero = number(right) == 0 if left != "A": reg = left if reg not in REG8 or not zero or op not in ("=", "/="): raise MolError(f"only A can be compared with anything but zero: {text}?") if self.flags_from != reg: code = REG8[reg] self.emit([0x04 | code << 3], f"INR {REG8_NAMES[code]}") self.emit([0x05 | code << 3], f"DCR {REG8_NAMES[code]}") self.flags_from = reg return 1 if op == "=" else 0 if zero and op in ("=", "/=", "<", ">="): if self.flags_from != "A": self.emit([0xB7], "ORA A") return {"=": 1, "/=": 0, "<": 7, ">=": 6}[op] v = self.value_of(right) if op in (">", "<="): if v is None or not v.known: raise MolError(f"> and <= need a number: {text}?") v = v + 1 op = ">=" if op == ">" else "<" if v is not None: self.emit([0xFE], f"CPI {v.number & 0xFF:02X}H", Value(v.number & 0xFF) if v.known else v, 1) elif right in REG8: self.emit([0xB8 | REG8[right]], f"CMP {REG8_NAMES[REG8[right]]}") else: raise MolError(f"bad comparison {text}?") self.flags_from = None return {"=": 1, "/=": 0, "<": 3, ">=": 2}[op] # -------------------------------------------------------- transfers def chain(self, text: str): elements = split_colons(text) if len(elements) < 2: raise MolError(f"not a statement: {text}") previous_plain = None for i in range(len(elements) - 1): src, dst = elements[i], elements[i + 1] if i > 0: src = strip_work(src) dst_name, work = split_work(dst) try: self.transfer(src, dst_name, work) except MolError: # x:y:z where y can't go to z directly but x can (A:B:PORT(n) outputs A). if previous_plain is None: raise self.transfer(previous_plain, dst_name, work) simple = self.split_expression(src)[1] == [] and (src in REG8 or src in PAIRS) previous_plain = src if simple else (previous_plain if src == "A" else None) if i == 0 and not simple: previous_plain = dst_name if dst_name in REG8 else None def transfer(self, src: str, dst: str, work: set[str]): # Stack. if dst == "STK": for r in src.split(","): r = r.strip() if r not in PUSH_CODE: raise MolError(f"can't push {r}") self.emit([PUSH_CODE[r]], f"PUSH {'PSW' if r == 'A' else PAIR_ASM[r]}") return if src == "STK": for r in dst.split(","): r = r.strip() if r not in POP_CODE: raise MolError(f"can't pop {r}") self.emit([POP_CODE[r]], f"POP {'PSW' if r == 'A' else PAIR_ASM[r]}") self.flags_from = None return if dst == "FC": if src == "1": return self.emit([0x37], "STC") if src == "NOT(FC)": return self.emit([0x3F], "CMC") raise MolError(f"can't set FC from {src}") if dst == "FI": if src in ("0", "1"): return self.emit([0xFB if src == "1" else 0xF3], "EI" if src == "1" else "DI") raise MolError(f"can't set FI from {src}") m = re.fullmatch(r"PORT\((.+)\)", dst) if m: if src != "A": raise MolError("only A can be output to a port") v = self.value_of(m.group(1)) return self.emit([0xD3], f"OUT {v.number:02X}H", v, 1) if dst in ("(BC)", "(DE)"): if src != "A": raise MolError(f"only A can be stored at {dst}") return self.emit([0x02 if dst == "(BC)" else 0x12], f"STAX {dst[1]}") if dst in PAIRS: return self.transfer16(src, dst, work) if dst in REG8: return self.transfer8(src, dst, work) if self.is_storage(dst): v = self.storage_value(dst) if src == "A": return self.emit([0x32], f"STA {v}", v, 2) if src == "HL": return self.emit([0x22], f"SHLD {v}", v, 2) raise MolError(f"only A or HL can be stored at {dst}") raise MolError(f"can't transfer {src} to {dst}") def transfer8(self, src: str, dst: str, work: set[str]): first, ops = self.split_expression(src) code = REG8[dst] name = REG8_NAMES[code] # The first term into the destination. if first != dst: v = self.value_of(first) if first == "NOT(A)" and dst == "A": self.emit([0x2F], "CMA") elif first == "DEC(A)" and dst == "A": self.emit([0x27], "DAA") self.flags_from = "A" elif v is not None: if dst == "A" and first == "0": self.emit([0xAF], "XRA A") self.flags_from = "A" else: self.emit([0x06 | code << 3], f"MVI {name},{v.number & 0xFF:02X}H" if v.known else f"MVI {name},{v}", Value(v.number & 0xFF) if v.known else v, 1) elif first in REG8: self.emit([0x40 | code << 3 | REG8[first]], f"MOV {name},{REG8_NAMES[REG8[first]]}") elif first in ("(BC)", "(DE)") and dst == "A": self.emit([0x0A if first == "(BC)" else 0x1A], f"LDAX {first[1]}") elif re.fullmatch(r"PORT\((.+)\)", first) and dst == "A": v = self.value_of(first[5:-1]) self.emit([0xDB], f"IN {v.number:02X}H", v, 1) elif self.is_storage(first) and dst == "A": v = self.storage_value(first) self.emit([0x3A], f"LDA {v}", v, 2) else: raise MolError(f"can't transfer {first} to {dst}") elif not ops and dst == "A" and first == "A": self.emit([0x7F], "MOV A,A") # Then each operation on the destination. for op, term in ops: n = number(term) if op in ("+", "-") and n is not None and (n == 1 or dst != "A"): for _ in range(n): if op == "+": self.emit([0x04 | code << 3], f"INR {name}") else: self.emit([0x05 | code << 3], f"DCR {name}") self.flags_from = dst continue if dst != "A": raise MolError(f"{op}{term} needs the result in A, not {dst}") if op == "*": if n is None or n & (n - 1): raise MolError(f"A can only be multiplied by a power of two: {term}") for _ in range(n.bit_length() - 1): self.emit([0x87], "ADD A") self.flags_from = "A" continue if op in ("<*", ">*"): if n is None: raise MolError(f"rotate count must be a number: {term}") for _ in range(n): self.emit([0x07 if op == "<*" else 0x0F], "RLC" if op == "<*" else "RRC") continue alu, reg_mn, imm_mn = ALU[op] v = self.value_of(term) if term in REG8: self.emit([0x80 | alu << 3 | REG8[term]], f"{reg_mn} {REG8_NAMES[REG8[term]]}") elif v is not None: self.emit([0xC6 | alu << 3], f"{imm_mn} {v.number & 0xFF:02X}H" if v.known else f"{imm_mn} {v}", Value(v.number & 0xFF) if v.known else v, 1) else: raise MolError(f"bad operand {term}") self.flags_from = "A" if dst == "(HL)": self.flags_from = None if not ops else self.flags_from def transfer16(self, src: str, dst: str, work: set[str]): first, ops = self.split_expression(src) p = PAIRS[dst] if first != dst: v = self.value_of(first) if v is not None: self.emit([0x01 | p << 4], f"LXI {PAIR_ASM[dst]},{v}", v, 2) elif first == "SP" and dst == "HL": self.emit([0x21], "LXI H,0", Value(0), 2) self.emit([0x39], "DAD SP") elif first == "HL" and dst == "SP": self.emit([0xF9], "SPHL") elif first in ("BC", "DE", "HL") and dst in ("BC", "DE", "HL"): if {first, dst} == {"DE", "HL"} and first in work: self.emit([0xEB], "XCHG") else: hi, lo = first[0], first[1] self.emit([0x40 | REG8[dst[0]] << 3 | REG8[hi]], f"MOV {dst[0]},{hi}") self.emit([0x40 | REG8[dst[1]] << 3 | REG8[lo]], f"MOV {dst[1]},{lo}") elif self.is_storage(first) and dst == "HL": v = self.storage_value(first) self.emit([0x2A], f"LHLD {v}", v, 2) else: raise MolError(f"can't transfer {first} to {dst}") for op, term in ops: n = number(term) if op in ("+", "-") and n is not None: for _ in range(n): self.emit([(0x03 if op == "+" else 0x0B) | p << 4], f"{'INX' if op == '+' else 'DCX'} {PAIR_ASM[dst]}") continue if dst != "HL": raise MolError(f"{op}{term} needs the result in HL, not {dst}") if op == "+" and term in PAIRS: self.emit([0x09 | PAIRS[term] << 4], f"DAD {PAIR_ASM[term]}") continue if op == "*" and n is not None and n and not n & (n - 1): for _ in range(n.bit_length() - 1): self.emit([0x29], "DAD H") continue raise MolError(f"can't apply {op}{term} to {dst}") # ---------------------------------------------------------------- source text def matching(text: str, i: int) -> int: depth, quote = 0, None for j in range(i, len(text)): c = text[j] if quote: if c == quote: quote = None elif c in "'\"": quote = c elif c == "(": depth += 1 elif c == ")": depth -= 1 if depth == 0: return j return -1 def has_top_level_space(text: str) -> bool: return len(split_statements(text)) > 1 or "?" in text def split_top(text: str, separators: str) -> list[str]: parts, depth, quote, start = [], 0, None, 0 for i, c in enumerate(text): if quote: if c == quote: quote = None elif c in "'\"": quote = c elif c == "(": depth += 1 elif c == ")" and depth: depth -= 1 elif depth == 0 and c in separators: parts.append(text[start:i]) start = i + 1 parts.append(text[start:]) return parts def split_statements(text: str) -> list[str]: """Statements separated by blanks and semicolons; a condition (ending '?') takes the next statement.""" tokens = [t for t in split_top(text, " \t;") if t.strip()] out = [] i = 0 while i < len(tokens): t = tokens[i] while t.endswith("?") and i + 1 < len(tokens): i += 1 t = t + " " + tokens[i] out.append(t) i += 1 return out def split_colons(text: str) -> list[str]: return [p for p in split_top(text, ":")] def split_commas(text: str) -> list[str]: return split_top(text, ",") def split_work(text: str) -> tuple[str, set[str]]: m = re.fullmatch(r"(.+?)<([A-Z,]+)>", text) if m and not m.group(1).endswith(("<", ">")): return m.group(1), set(m.group(2).split(",")) return text, set() def strip_work(text: str) -> str: return split_work(text)[0] def compile_source(source: str) -> Compiler: c = Compiler() for number_, raw in enumerate(source.splitlines(), 1): line = raw.rstrip() if ";" not in line or line.lstrip().startswith("*"): continue code = line[: line.rfind(";") + 1] location, start = c.loc.name, c.here() c.asm = [] try: m = re.match(r"([A-Z][A-Z0-9]*)(\s+|$)", code) if m and not code[0].isspace(): c.define_label(m.group(1)) code = code[m.end():] c.flags_from = None for st in split_statements(code): if "?" in st and not st.startswith(("(", "'")) and "('" not in st.split("?")[0]: cond, _, rest = st.partition("?") c.conditional(cond + "?", rest) else: c.statement(st) except MolError as e: raise MolError(f"line {number_}: {e}\n {raw.strip()}") from None if c.loc.name != location: start = c.here() - (c.here() - 0) if False else start c.listing.append(ListingLine(number_, c.loc.name, start if c.loc.name == location else 0, c.here(), list(c.asm), raw.rstrip())) return c # ---------------------------------------------------------------- linking and output def link(c: Compiler, origin: int) -> tuple[bytearray, dict[str, int], set[str]]: """Places MAIN at origin and each LOCATION after it, and resolves every reference. References to entries in other modules (externals) are left as zero and returned.""" address = origin for loc in c.locations.values(): loc.base = address address += len(loc.code) symbols = {name: c.locations[l].base + off for name, (l, off) in {**c.labels, **c.entries}.items()} image = bytearray() externals = set() for loc in c.locations.values(): code = bytearray(loc.code) for f in loc.fixups: v = f.value if v.symbol is None: n = v.number elif v.symbol in symbols: n = symbols[v.symbol] + v.number elif v.symbol.startswith("@") or v.symbol in c.used_as_label: raise MolError(f"undefined label: {v.symbol}") else: externals.add(v.symbol) n = 0 code[f.offset:f.offset + f.size] = (n & 0xFFFF).to_bytes(2, "little")[:f.size] image += code return image, symbols, externals def object_text(c: Compiler) -> str: """The code as CPT's object format shows it: decimal bytes, with *references for addresses and words.""" out = [] for loc in c.locations.values(): items, at = [], 0 fix = {f.offset: f for f in loc.fixups} while at < len(loc.code): if at in fix: f = fix[at] items.append(f"*{f.value}" if f.size == 2 else f"*{f.value}") at += f.size else: items.append(str(loc.code[at])) at += 1 out.append(f"OBJECT {loc.name}.") line = [] for item in items: line.append(item) if len(" ".join(line)) > 60: out.append(" " + " ".join(line)) line = [] if line: out.append(" " + " ".join(line)) return "\n".join(out) def listing_text(c: Compiler, image: bytearray, origin: int) -> str: out = [] bases = {loc.name: loc.base for loc in c.locations.values()} for ln in c.listing: base = bases[ln.location] data = image[base - origin + ln.start: base - origin + ln.end] if ln.end > ln.start else b"" hexes = " ".join(f"{b:02X}" for b in data) asm = "; ".join(ln.asm) addr = f"{base + ln.start:04X}" if ln.end > ln.start else " " first = True while True: chunk, hexes = hexes[:24], hexes[24:].lstrip() if first: out.append(f"{addr} {chunk:24} {asm:38} {ln.source.strip()}") first = False else: out.append(f" {chunk:24}") if not hexes: break return "\n".join(out) def parse_object_listing(text: str) -> list[str]: """Items from a CPT OBJECT listing (R (bytes ...) lines): numbers and *references.""" items = [] for m in re.finditer(r"R\d+\s*\(([^)]*(?:\([^)]*\)[^)]*)*)\)", text): items += m.group(1).split() return items def compare_object(c: Compiler, symbols_by_location: dict, text: str) -> list[str]: """Compares the MAIN code with a CPT OBJECT listing: every byte, and every reference. CPT's internal labels (A3, A12...) must map one to one onto labels here, at the same places; quoted names are entries.""" theirs = parse_object_listing(text) main = c.locations["MAIN"] fix = {f.offset: f for f in main.fixups} problems, mapping, back = [], {}, {} at = 0 for item in theirs: if at >= len(main.code): problems.append(f"the object code goes on past the end of ours at {at}: {item}") break f = fix.get(at) if not item.startswith("*"): if f is not None: problems.append(f"offset {at}: theirs is the byte {item}, ours a reference to {f.value}") at += f.size else: if int(item) != main.code[at]: problems.append(f"offset {at}: theirs {item}, ours {main.code[at]}") at += 1 continue ref = item[1:] if f is None or f.size != 2: problems.append(f"offset {at}: theirs is a reference ({item}), ours the byte {main.code[at]}") at += 1 continue v = f.value m = re.fullmatch(r"\(?(A\d+)(?:\+(\d+))?\)?", ref) if re.fullmatch(r"-?\d+", ref): if v.symbol is not None or (v.number - int(ref)) % 65536: problems.append(f"offset {at}: theirs {ref}, ours {v}") elif ref.startswith("'"): if v.symbol != ref.strip("'") or v.number: problems.append(f"offset {at}: theirs {ref}, ours {v}") elif m: name, offset = m.group(1), int(m.group(2) or 0) if v.symbol is None or v.number != offset: problems.append(f"offset {at}: theirs {ref}, ours {v}") elif mapping.setdefault(name, v.symbol) != v.symbol or back.setdefault(v.symbol, name) != name: problems.append(f"offset {at}: their {name} is ours {mapping[name]} elsewhere, here {v.symbol}") else: problems.append(f"offset {at}: can't read their reference {item}") at += 2 if at != len(main.code): problems.append(f"lengths differ: theirs {at} bytes, ours {len(main.code)}") # Their internal and external address tables: where each label and entry is. loc_index = {name: i for i, name in enumerate(c.locations)} places = {**{n: (loc_index[l], o) for n, (l, o) in c.labels.items()}, **{n: (loc_index[l], o) for n, (l, o) in c.entries.items()}} for name, loc, off in re.findall(r"(A\d+) \((\d+) (\d+)\)", text): ours = mapping.get(name) if ours is None: problems.append(f"their {name} at ({loc} {off}) isn't referred to in our code") elif places.get(ours) != (int(loc), int(off)): problems.append(f"their {name} is at ({loc} {off}); our {ours} is at {places.get(ours)}") externals = text.split("EXTERNAL ADDRESSES.", 1)[1] if "EXTERNAL ADDRESSES." in text else "" for name, loc, off in re.findall(r"([A-Z0-9]+) \((\d+) (\d+)\)", externals): key = f"INTERRUPT{name}" if name.isdigit() else name if places.get(key) != (int(loc), int(off)): problems.append(f"entry {name} is at ({loc} {off}) in theirs, {places.get(key)} in ours") sizes = re.findall(r"([A-Z][A-Z ]*?) \((\d+) (\d+)\)", text.split("LOCATIONS.", 1)[1].split(".", 1)[0]) if "LOCATIONS." in text else [] for name, index, size in sizes: loc = c.locations.get(name.strip()) if loc is None or len(loc.code) != int(size): problems.append(f"location {name.strip()}: {size} bytes in theirs, {len(loc.code) if loc else 'none'} in ours") return problems def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("source") ap.add_argument("-o", "--output", help="write the machine code to this file") ap.add_argument("--org", type=lambda s: int(s, 0), default=0, help="address of the first byte (default 0)") ap.add_argument("--object", action="store_true", help="print CPT-style object code") ap.add_argument("--compare", help="a binary to compare the machine code with") ap.add_argument("--compare-object", help="a CPT OBJECT listing to compare the code, labels and entries with") args = ap.parse_args() try: c = compile_source(open(args.source, encoding="utf-8").read()) image, symbols, externals = link(c, args.org) except MolError as e: sys.exit(f"{args.source}: {e}") print(listing_text(c, image, args.org)) print(f"\n{len(image)} bytes, {args.org:04X}-{args.org + len(image) - 1:04X}" + (f" ({c.title})" if c.title else "")) if externals: print("entries in other modules (left as 0): " + ", ".join(sorted(externals))) if args.object: print() print(object_text(c)) if args.output: open(args.output, "wb").write(image) print(f"wrote {args.output}") if args.compare: other = open(args.compare, "rb").read() diffs = [i for i in range(max(len(image), len(other))) if i >= len(image) or i >= len(other) or image[i] != other[i]] if not diffs: print(f"identical to {args.compare} ({len(other)} bytes)") else: print(f"{len(diffs)} bytes differ from {args.compare}; first at {args.org + diffs[0]:04X}") sys.exit(1) if args.compare_object: problems = compare_object(c, symbols, open(args.compare_object, encoding="utf-8").read()) if problems: print(f"{len(problems)} differences from {args.compare_object}:") for p in problems[:40]: print(" " + p) sys.exit(1) n = len(c.locations["MAIN"].code) print(f"matches {args.compare_object}: all {n} bytes, every reference, label and entry") if __name__ == "__main__": main()