#!/usr/bin/env python3 """basc: compile a BASIC program for the Basys 3 RISC-V computer to machine code, which runs at A200h like the games and is started by a two-line BASIC loader. tools/basc.py prog.bas [-o DIR] [--name NAME] [--fast] [--keep-c] writes DIR/NAME.ihx (the program, for tools/send-hex.py --save NAMEC), and DIR/NAME.bas (the loader: BLOAD "NAMEC": CALL 41472). DIR is the .bas file's folder unless -o says otherwise, NAME its name in capitals. How it works. The program is read exactly as BASIC reads it (the same tokens, from basic/basic.c), and turned into C, which GCC compiles. Numbers, numeric variables and arrays, arithmetic, and all the control statements (GOTO, GOSUB, ON, FOR ... NEXT, IF ... THEN ... ELSE, block IF, DO ... LOOP, EXIT, SELECT CASE, END, STOP) become machine code, using the FPU directly. Every other statement (PRINT, INPUT, strings, graphics, sound, files, DATA and READ, DEF FN ...) and the functions without a fast path are handed, as tokens, to the interpreter in BASIC's ROM through a fixed jump table at 9F00h (rt_table in basic.c), so they do exactly what they do interpreted. Control goes where the interpreter would send it: the scans BASIC makes at run time (for the NEXT of a FOR that runs no times, the END IF of a block IF, a matching CASE) are made here, the same way, once. The variables are BASIC's own, so a program's PRINT, INPUT and READ see the same ones, and they are still there afterwards. Errors stop the program with the interpreter's message and line number. """ import argparse import os import re import subprocess import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) RT_ABI = 1 RT_TABLE = 0x9F00 LOAD_AT = 0xA200 PROG_END = 0xF0B8 # the end of BASIC's program area class CompileError(Exception): pass # --------------------------------------------------------------- from basic.c def basic_tables(): src = open(os.path.join(ROOT, "basic", "basic.c"), encoding="latin-1").read() kw_body = re.search(r"static const char \*const kw\[\] = \{(.*?)\};", src, re.S).group(1) kws = re.findall(r'"((?:[^"\\]|\\.)*)"', kw_body) enum_body = re.search(r"enum \{\s*T_LET = 0x80,(.*?)\};", src, re.S).group(1) names = ["T_LET"] + [n.strip() for n in enum_body.replace("\n", " ").split(",") if n.strip()] tok = {n: 0x80 + i for i, n in enumerate(names)} assert len(kws) == tok["T_LAST"] - 0x80, "kw[] and the token enum disagree" err_body = re.search(r"enum \{\s*(E_SYNTAX,.*?)\};", src, re.S).group(1) errs = {n.strip(): i for i, n in enumerate(err_body.replace("\n", " ").split(",")) if n.strip()} m = re.search(r"#define RT_ABI (\d+)", src) assert m and int(m.group(1)) == RT_ABI, "basc.py and basic.c have different RT_ABI" return kws, tok, errs KWS, T, E = basic_tables() KW_BYTES = [k.encode("latin-1") for k in KWS] STR_FUNCS = {T[n] for n in ("T_CHRS", "T_STRS", "T_LEFTS", "T_RIGHTS", "T_MIDS", "T_DATES", "T_UCASES", "T_LCASES")} # one-argument numeric functions rt_fn does (func1: SIN..INP, func2v: DEG..FACT) FN1 = {T[n] for n in ("T_SIN", "T_COS", "T_TAN", "T_ATN", "T_EXP", "T_LOG", "T_ABS", "T_SQR", "T_INT", "T_SGN", "T_PEEK", "T_INP")} FN2V = {T[n] for n in ("T_DEG", "T_RAD", "T_ASIN", "T_ACOS", "T_SEC", "T_CSC", "T_COT", "T_SINH", "T_COSH", "T_TANH", "T_ASINH", "T_ACOSH", "T_ATANH", "T_LOG10", "T_LOG2", "T_CEIL", "T_IP", "T_FP", "T_FACT")} # graphics statements: (fewest, most) numbers, which rt_gfx takes worked out GFX = {T["T_CLS"]: (0, 0), T["T_COLOR"]: (1, 1), T["T_PLOT"]: (2, 3), T["T_LINE"]: (4, 5), T["T_RECT"]: (4, 5), T["T_FILL"]: (4, 5), T["T_CIRCLE"]: (3, 4), T["T_LOCATE"]: (2, 2), T["T_INK"]: (1, 2), T["T_SCREEN"]: (1, 3)} # statements that make no sense inside a compiled program NOT_COMPILED = {T[n]: n[2:] for n in ("T_RUN", "T_LIST", "T_NEW", "T_SCRATCH", "T_LOAD", "T_SAVE", "T_RENUM")} # ------------------------------------------------------------------ reading def tokenize(s): """basic.c's tokenize(): keywords to single bytes, capitals outside quotes, REM and DATA text kept as typed.""" out = bytearray() quote = raw = False i = 0 up = lambda b: b - 32 if 97 <= b <= 122 else b while i < len(s): c = s[i] if raw: out.append(c); i += 1; continue if c == 34: quote = not quote if quote: out.append(c); i += 1; continue c = up(c) best = blen = 0 for k, kb in enumerate(KW_BYTES): if kb[0] != c or i + len(kb) > len(s): continue if all(up(s[i + j]) == kb[j] for j in range(1, len(kb))) and len(kb) > blen: blen, best = len(kb), 0x80 + k if blen: out.append(best) i += blen if best in (T["T_REM"], T["T_DATA"]): raw = True else: out.append(c) i += 1 return bytes(out) def read_program(path): """{line number: tokens}, as BASIC would store the file typed in.""" lines = {} for n, raw in enumerate(open(path, "rb").read().split(b"\n"), 1): raw = raw.rstrip(b"\r") p = raw.lstrip(b" ") if not p: continue m = re.match(rb"(\d+) *", p) if not m: raise CompileError("line %d of the file has no line number: %s" % (n, raw.decode("latin-1"))) num = int(m.group(1)) if num > 65535: raise CompileError("line number %d is over 65535" % num) toks = tokenize(p[m.end():]).rstrip(b" ") if not toks: lines.pop(num, None) continue if len(toks) + 4 > 255: raise CompileError("line %d is too long for BASIC" % num) lines[num] = toks return [(n, lines[n]) for n in sorted(lines)] # ------------------------------------------------------------------ scanning class Prog: """The program as BASIC holds it, with the interpreter's ways of moving through it. A position is (line index, byte offset).""" def __init__(self, lines): self.lines = lines self.nums = {n: i for i, (n, _) in enumerate(lines)} def byte(self, p): li, off = p t = self.lines[li][1] return t[off] if off < len(t) else 0 def peek(self, p): """skip spaces: (the byte, its position)""" li, off = p t = self.lines[li][1] while off < len(t) and t[off] == 32: off += 1 return (t[off] if off < len(t) else 0), (li, off) def skip_statement(self, p): li, off = p t = self.lines[li][1] q = False while off < len(t) and (q or t[off] != 58): if t[off] == 34: q = not q off += 1 return (li, off) def next_stmt(self, p): """basic.c's next_stmt(): the next statement's start, or None at the end of the program""" li, off = self.skip_statement(p) if off < len(self.lines[li][1]): return (li, off + 1) if li + 1 >= len(self.lines): return None return (li + 1, 0) def ends_then(self, p): li, off = p t = self.lines[li][1] q, last = False, 0 for b in t[off:]: if b == 34: q = not q elif b != 32: last = 0 if q else b return last == T["T_THEN"] def var_name(self, p): """(variable index, position after) or (None, p)""" c, p = self.peek(p) if not (65 <= c <= 90): return None, p d = self.byte((p[0], p[1] + 1)) if d == 36: return None, p if 48 <= d <= 57: if self.byte((p[0], p[1] + 2)) == 36: return None, p return (c - 65) * 11 + 1 + d - 48, (p[0], p[1] + 2) return (c - 65) * 11, (p[0], p[1] + 1) def at_end(self, p): c, _ = self.peek(p) return c in (0, 58, T["T_ELSE"]) # the scans the interpreter makes at run time def find_next(self, p): depth = 0 while True: p = self.next_stmt(p) if p is None: return None c, p = self.peek(p) if c == T["T_FOR"]: depth += 1 elif c == T["T_NEXT"]: if depth == 0: p = (p[0], p[1] + 1) while not self.at_end(p): _, p = self.var_name(p) c, q = self.peek(p) if c != 44: break p = (q[0], q[1] + 1) return p depth -= 1 def find_loop(self, p): depth = 0 while True: p = self.next_stmt(p) if p is None: return None c, p = self.peek(p) if c == T["T_DO"]: depth += 1 elif c == T["T_LOOP"]: if depth == 0: return self.skip_statement((p[0], p[1] + 1)) depth -= 1 def find_end(self, p, k, els): """the END IF / END SELECT closing the block, or with els the next ELSE or ELSEIF: ("end", position after) / ("else", position after ELSE) / ("elseif", the ELSE's position) / None""" depth = 0 while True: p = self.next_stmt(p) if p is None: return None c, p = self.peek(p) if c == k and (k == T["T_SELECT"] or self.ends_then(p)): depth += 1 elif c == T["T_END"]: c2, q = self.peek((p[0], p[1] + 1)) if c2 == k: if depth == 0: return ("end", (q[0], q[1] + 1)) depth -= 1 elif c == T["T_ELSE"] and els and depth == 0: c2, q = self.peek((p[0], p[1] + 1)) if c2 == T["T_IF"]: return ("elseif", p) return ("else", (p[0], p[1] + 1)) def select_stops(self, p): """what a SELECT's scan from p meets next: ("case", CASE position) / ("end", position after END SELECT) / None""" depth = 0 while True: p = self.next_stmt(p) if p is None: return None c, p = self.peek(p) if c == T["T_SELECT"]: depth += 1 elif c == T["T_END"]: c2, q = self.peek((p[0], p[1] + 1)) if c2 == T["T_SELECT"]: if depth == 0: return ("end", (q[0], q[1] + 1)) depth -= 1 elif c == T["T_CASE"] and depth == 0: return ("case", p) def norm(self, p): """Where execution goes on from p: a statement's start, or ("eol", li)""" c, q = self.peek(p) if c == 58: return self.norm((q[0], q[1] + 1)) if c == 0 or c == T["T_ELSE"]: return ("eol", q[0]) return q def is_str_start(self, p): c, p = self.peek(p) if c == 34 or c in STR_FUNCS: return True return 65 <= c <= 90 and self.byte((p[0], p[1] + 1)) == 36 def skip_parens(self, p): """from just after a '(' to just after its ')'""" li, off = p t = self.lines[li][1] d, q = 1, False while off < len(t): b = t[off] off += 1 if b == 34: q = not q elif not q and b == 40: d += 1 elif not q and b == 41: d -= 1 if d == 0: return (li, off) raise SyntaxError def skip_str_prim(self, p): c, p = self.peek(p) li, off = p t = self.lines[li][1] if c == 34: off += 1 while off < len(t) and t[off] != 34: off += 1 return (li, min(off + 1, len(t))) if 65 <= c <= 90 and self.byte((li, off + 1)) == 36: c2, q = self.peek((li, off + 2)) if c2 == 40: return self.skip_parens((q[0], q[1] + 1)) return (li, off + 2) if c == T["T_DATES"]: return (li, off + 1) if c in STR_FUNCS: c2, q = self.peek((li, off + 1)) if c2 != 40: raise SyntaxError return self.skip_parens((q[0], q[1] + 1)) raise SyntaxError def skip_sexpr(self, p): p = self.skip_str_prim(p) while True: c, q = self.peek(p) if c != 43: return p p = self.skip_str_prim((q[0], q[1] + 1)) def relop(self, p): """(op bits: 1 <, 2 =, 4 >; position after) or (0, p)""" c, q = self.peek(p) nx = (q[0], q[1] + 1) if c == 61: return 2, nx if c == T["T_NE"]: return 5, nx if c == T["T_LE"]: return 3, nx if c == T["T_GE"]: return 6, nx if c == 60: c2, r = self.peek(nx) if c2 == 62: return 5, (r[0], r[1] + 1) if c2 == 61: return 3, (r[0], r[1] + 1) return 1, nx if c == 62: c2, r = self.peek(nx) if c2 == 61: return 6, (r[0], r[1] + 1) return 4, nx return 0, p # ---------------------------------------------------------------- C output def c_bytes(b): return "{" + ",".join(str(x) for x in b) + "}" class Gen: def __init__(self, prog): self.P = prog self.out = [] # main's statements self.snips = {} # bytes -> name self.consts = [] # number text tokens self.ntemp = 0 self.labels_used = set() self.sels = 0 self.need_str = False self.do_of_loop = {} # LOOP position -> DO position self.case_sel = {} # CASE position -> (select id, is string) self.warn = [] # ---- names def temp(self): self.ntemp += 1 return "t%d" % self.ntemp def snip(self, b): b = bytes(b).rstrip(b" ") if b not in self.snips: self.snips[b] = "S%d" % len(self.snips) return self.snips[b] def lab(self, p): """the label of a place execution goes on from""" n = self.P.norm(p) if n[0] == "eol": name = "E%d" % n[1] else: name = "S%d_%d" % n self.labels_used.add(name) return name def line_lab(self, num): if num not in self.P.nums: return None return self.lab((self.P.nums[num], 0)) def lr(self, li): return "LR[%d]" % li def scan_fail(self, e): """a scan that runs off the end of the program: the interpreter is on the last line by then""" return "rt_error(%d, %s);" % (E[e], self.lr(len(self.P.lines) - 1)) def emit(self, s): self.out.append(s) def err(self, e, li): self.emit("rt_error(%d, %s);" % (E[e], self.lr(li))) def goto_line(self, num, li): l = self.line_lab(num) if l: self.emit("goto %s;" % l) else: self.err("E_LINE", li) def span(self, a, b): li = a[0] assert b[0] == li return self.P.lines[li][1][a[1]:b[1]] def rest(self, p): li, off = p return self.P.lines[li][1][off:] # ---- expressions: each returns (C expression, position after); the # code that computes it, in the interpreter's order, goes to self.out def number(self, p): c, p = self.P.peek(p) li, off = p t = self.P.lines[li][1] e = off dot = digits = 0 while e < len(t) and (48 <= t[e] <= 57 or (t[e] == 46 and not dot)): if t[e] == 46: dot = 1 else: digits += 1 e += 1 if not digits: raise SyntaxError ex = False if e < len(t) and t[e] == 69: q = e + 1 if q < len(t) and t[q] in (43, 45): q += 1 if q < len(t) and 48 <= t[q] <= 57: while q < len(t) and 48 <= t[q] <= 57: q += 1 e, ex = q, True text = t[off:e] if not dot and not ex and len(text.lstrip(b"0")) <= 9: return "%d.0f" % int(text), (li, e) # BASIC's own parse_num, once at the start if text not in self.consts: self.consts.append(text) return "K[%d]" % self.consts.index(text), (li, e) def opaque(self, a, b): """a piece of expression the interpreter works out""" t = self.temp() self.emit("%s = rt_eval((u8 *)%s, %s);" % (t, self.snip(self.span(a, b)), self.lr(a[0]))) return t def primary(self, p): P = self.P c, p = P.peek(p) li = p[0] nx = (li, p[1] + 1) if 48 <= c <= 57 or c == 46: return self.number(p) if c == 40: v, q = self.expr(nx) c2, q = P.peek(q) if c2 != 41: raise SyntaxError return v, (q[0], q[1] + 1) if P.is_str_start(p): self.err("E_TYPE", li) raise Stop if c == T["T_PI"]: return "3.14159265358979f", nx if c in (T["T_RND"], T["T_TIM"]): q = nx if c == T["T_RND"]: c2, r = P.peek(nx) if c2 == 40: # RND(x): x is worked out and ignored _, q = self.expr((r[0], r[1] + 1)) c3, q = P.peek(q) if c3 != 41: raise SyntaxError q = (q[0], q[1] + 1) t = self.temp() self.emit("%s = rt_fn(%d, 0, %s);" % (t, c, self.lr(li))) return t, q if c in FN1 or c in FN2V: c2, r = P.peek(nx) if c2 != 40: raise SyntaxError v, q = self.expr((r[0], r[1] + 1)) c3, q = P.peek(q) if c3 != 41: raise SyntaxError q = (q[0], q[1] + 1) t = self.temp() if c == T["T_ABS"]: self.emit("%s = %s < 0 ? -%s : %s;" % (t, v, v, v)) elif c == T["T_SGN"]: self.emit("%s = %s > 0 ? 1 : %s < 0 ? -1 : 0;" % (t, v, v)) else: self.emit("%s = rt_fn(%d, %s, %s);" % (t, c, v, self.lr(li))) return t, q if c >= 0x80: # FN, POINT, LEN, MOD, MIN ...: interpreted c2, r = P.peek(nx) q = nx if c == T["T_FN"]: _, r = P.peek(nx) c2, r = P.peek((r[0], r[1] + 1)) if c2 == 40: q = P.skip_parens((r[0], r[1] + 1)) return self.opaque(p, q), q if 65 <= c <= 90: if P.byte(nx) == 40: # an array element a = self.aref(c - 65, (nx[0], nx[1] + 1)) t = self.temp() self.emit("%s = *%s;" % (t, a)) return t, self.after_aref v, q = P.var_name(p) return "V[%d]" % v, q raise SyntaxError def aref(self, a, p): """A(I [, J]) from just after the '(': a pointer temp""" P = self.P i, q = self.expr(p) it = self.temp() self.emit("%s = %s;" % (it, i)) c, q = P.peek(q) two = c == 44 j = "0" if two: j, q = self.expr((q[0], q[1] + 1)) c, q = P.peek(q) if c != 41: raise SyntaxError self.after_aref = (q[0], q[1] + 1) t = self.temp().replace("t", "a") self.emit("%s = rt_aref(%d, %s, %s, %d, %s);" % (t, a, it, j, two, self.lr(p[0]))) return t def power(self, p): v, p = self.primary(p) while True: c, q = self.P.peek(p) if c != 94: return v, p a = self.temp() self.emit("%s = %s;" % (a, v)) w, p = self.unary((q[0], q[1] + 1)) t = self.temp() self.emit("%s = pw(%s, %s, %s);" % (t, a, w, self.lr(p[0]))) v = t def unary(self, p): c, q = self.P.peek(p) if c == 45: v, q = self.unary((q[0], q[1] + 1)) t = self.temp() self.emit("%s = -%s;" % (t, v)) return t, q if c == 43: return self.unary((q[0], q[1] + 1)) return self.power(p) def term(self, p): v, p = self.unary(p) while True: c, q = self.P.peek(p) if c not in (42, 47): return v, p a = self.temp() self.emit("%s = %s;" % (a, v)) w, p = self.unary((q[0], q[1] + 1)) t = self.temp() if c == 42: self.emit("%s = %s * %s;" % (t, a, w)) else: d = self.temp() self.emit("%s = %s;" % (d, w)) self.emit("if (%s == 0) rt_error(%d, %s);" % (d, E["E_DIV0"], self.lr(p[0]))) self.emit("%s = %s / %s;" % (t, a, d)) v = t def sum(self, p): v, p = self.term(p) while True: c, q = self.P.peek(p) if c not in (43, 45): return v, p a = self.temp() self.emit("%s = %s;" % (a, v)) w, p = self.term((q[0], q[1] + 1)) t = self.temp() self.emit("%s = %s %s %s;" % (t, a, "+" if c == 43 else "-", w)) v = t def relation(self, p): P = self.P if P.is_str_start(p): a, _ = P.peek(p) _, a = P.peek(p) q = P.skip_sexpr(a) op, q = P.relop(q) if not op: self.err("E_TYPE", a[0]) raise Stop q = P.skip_sexpr(q) return self.opaque(a, q), q x, p = self.sum(p) op, q = P.relop(p) if not op: return x, p a = self.temp() self.emit("%s = %s;" % (a, x)) y, q = self.sum(q) t = self.temp() self.emit("%s = rel(%s, %s, %d);" % (t, a, y, op)) return t, q def notx(self, p): c, q = self.P.peek(p) if c == T["T_NOT"]: v, q = self.notx((q[0], q[1] + 1)) t = self.temp() self.emit("%s = (float)~ti(%s, %s);" % (t, v, self.lr(q[0]))) return t, q return self.relation(p) def andx(self, p): v, p = self.notx(p) while True: c, q = self.P.peek(p) if c != T["T_AND"]: return v, p a = self.temp() self.emit("%s = %s;" % (a, v)) w, p = self.notx((q[0], q[1] + 1)) t = self.temp() self.emit("%s = (float)(ti(%s, %s) & ti(%s, %s));" % (t, a, self.lr(p[0]), w, self.lr(p[0]))) v = t def expr(self, p): v, p = self.andx(p) while True: c, q = self.P.peek(p) if c != T["T_OR"]: return v, p a = self.temp() self.emit("%s = %s;" % (a, v)) w, p = self.andx((q[0], q[1] + 1)) t = self.temp() self.emit("%s = (float)(ti(%s, %s) | ti(%s, %s));" % (t, a, self.lr(p[0]), w, self.lr(p[0]))) v = t def expr_or_rt(self, p, li): """an expression, compiled; if it won't parse, the interpreter gets the rest of the statement, which gives its error""" mark = len(self.out) try: return self.expr(p) except SyntaxError: del self.out[mark:] t = self.temp() self.emit("%s = rt_eval((u8 *)%s, %s);" % (t, self.snip(self.rest(p)), self.lr(li))) self.err("E_SYNTAX", li) raise Stop def lineno(self, p): c, p = self.P.peek(p) li, off = p t = self.P.lines[li][1] e = off while e < len(t) and 48 <= t[e] <= 57: e += 1 if e == off: return None, p return int(t[off:e]), (li, e) # ---- statements def statement(self, p): """compile the statement at p (a statement start); returns the position after it, where the execute loop takes over, or with follow=True a position where a statement may start straight away""" P = self.P c, p = P.peek(p) li = p[0] nx = (li, p[1] + 1) if c in (0, 58): return p if c in NOT_COMPILED: raise CompileError("line %d: %s can't be used in a compiled program" % (P.lines[li][0], NOT_COMPILED[c])) if c in (T["T_REM"], T["T_DATA"]): return (li, len(P.lines[li][1])) if c == T["T_LET"]: return self.st_let(nx, p) if c == T["T_GOTO"]: n, q = self.lineno(nx) if n is None: self.err("E_SYNTAX", li) else: self.emit("BRK(%s);" % self.lr(li)) self.goto_line(n, li) return q if c == T["T_GOSUB"]: n, q = self.lineno(nx) if n is None: self.err("E_SYNTAX", li) return q self.gosub(n, q, li) return q if c == T["T_RETURN"]: self.emit("BRK(%s); if (!ng) rt_error(%d, %s); goto *gs[--ng];" % (self.lr(li), E["E_RETURN"], self.lr(li))) return nx if c == T["T_ON"]: return self.st_on(nx, li) if c == T["T_IF"]: return self.st_if(nx, li) if c == T["T_FOR"]: return self.st_for(nx, li, p) if c == T["T_NEXT"]: return self.st_next(nx, li) if c == T["T_END"]: c2, q = P.peek(nx) if c2 in (T["T_IF"], T["T_SELECT"]): return (q[0], q[1] + 1) self.emit("goto FINISH;") return nx if c == T["T_STOP"]: self.err("E_STOP", li) return nx if c == T["T_DO"]: return self.st_do(nx, li, p) if c == T["T_LOOP"]: return self.st_loop(nx, li, p) if c == T["T_EXIT"]: return self.st_exit(nx, li) if c == T["T_SELECT"]: return self.st_select(nx, li, p) if c == T["T_ELSE"]: return self.st_else(nx, li, p) if c == T["T_CASE"]: return self.st_case(nx, li, p) if c in GFX: return self.st_gfx(c, nx, p) if 65 <= c <= 90 and P.byte(nx) != 36: return self.st_let(p, p) return self.interpreted(p) def st_gfx(self, t, p, start): """PLOT, LINE, CIRCLE ...: the numbers here, the drawing by rt_gfx""" P = self.P li = p[0] lo, hi = GFX[t] c, q = P.peek(p) if t == T["T_LINE"] and c == T["T_INPUT"]: return self.interpreted(start) mark = len(self.out) args = [] try: if hi: while True: v, q = self.expr(q) self.emit("ga[%d] = ti(%s, %s);" % (len(args), v, self.lr(li))) args.append(v) c, r = P.peek(q) if c != 44 or len(args) == hi: break q = (r[0], r[1] + 1) if len(args) < lo or not P.at_end(q): raise SyntaxError except SyntaxError: del self.out[mark:] return self.interpreted(start) # the interpreter's error self.emit("rt_gfx(%d, ga, %d, %s);" % (t, len(args), self.lr(li))) return q def interpreted(self, p): """the interpreter runs this statement""" q = self.P.skip_statement(p) li = p[0] t = self.P.lines[li][1] # the statement ends at an ELSE too (at_end), outside quotes qq, end = False, p[1] while end < q[1]: b = t[end] if b == 34: qq = not qq elif b == T["T_ELSE"] and not qq: break end += 1 self.emit("rt_exec((u8 *)%s, %s);" % (self.snip(t[p[1]:end]), self.lr(li))) return (li, end) def st_let(self, p, start): P = self.P li = p[0] c, p = P.peek(p) if not (65 <= c <= 90) or P.byte((li, p[1] + 1)) == 36: return self.interpreted(start) # strings: interpreted mark = len(self.out) try: nx = (li, p[1] + 1) if P.byte(nx) == 40: ref = self.aref(c - 65, (nx[0], nx[1] + 1)) q = self.after_aref target = "*" + ref else: v, q = P.var_name(p) target = "V[%d]" % v c2, q = P.peek(q) if c2 != 61: raise SyntaxError v, q = self.expr((q[0], q[1] + 1)) except SyntaxError: del self.out[mark:] return self.interpreted(start) # gives the error self.emit("%s = %s;" % (target, v)) return q def gosub(self, n, ret, li): r = self.lab(ret) self.emit("BRK(%s); if (ng >= 32) rt_error(%d, %s); gs[ng++] = &&%s;" % (self.lr(li), E["E_GOSUB"], self.lr(li), r)) self.goto_line(n, li) def st_on(self, p, li): P = self.P v, q = self.expr_or_rt(p, li) n = self.temp().replace("t", "i") self.emit("%s = ti(%s, %s);" % (n, v, self.lr(li))) c, q = P.peek(q) if c not in (T["T_GOTO"], T["T_GOSUB"]): self.err("E_SYNTAX", li) raise Stop q = (q[0], q[1] + 1) targets = [] while True: num, q = self.lineno(q) if num is None: self.err("E_SYNTAX", li) raise Stop targets.append(num) c2, r = P.peek(q) if c2 != 44: break q = (r[0], r[1] + 1) end = P.skip_statement(q) self.emit("BRK(%s);" % self.lr(li)) for k, num in enumerate(targets, 1): self.emit("if (%s == %d) {" % (n, k)) if c == T["T_GOSUB"]: self.gosub(num, end, li) else: self.goto_line(num, li) self.emit("}") return end def st_if(self, p, li): P = self.P v, q = self.expr_or_rt(p, li) c, r = P.peek(q) if c == T["T_THEN"]: q = (r[0], r[1] + 1) elif c != T["T_GOTO"]: self.err("E_SYNTAX", li) raise Stop c, r = P.peek(q) if c == 0: # block IF stop = P.find_end(r, T["T_IF"], True) self.emit("if (!%s) %s" % (v, self.block_jump(stop, li, "E_ENDIF"))) return r # on to this IF's ELSE when false t = P.lines[li][1] off, depth, qq, target = q[1], 0, False, None while off < len(t): b = t[off] if b == 34: qq = not qq elif not qq and b == T["T_IF"]: depth += 1 elif not qq and b == T["T_ELSE"]: if depth == 0: target = (li, off + 1) break depth -= 1 off += 1 if target is None: self.emit("if (!%s) goto E%d;" % (v, li)) self.labels_used.add("E%d" % li) else: self.emit("if (!%s) goto %s;" % (v, self.lab_raw(target))) self.follow = "then" return q def lab_raw(self, p): """a label at exactly p (the start of an ELSE part)""" name = "X%d_%d" % p self.labels_used.add(name) return name def block_jump(self, stop, li, e): if stop is None: return self.scan_fail(e) kind, q = stop if kind == "elseif": name = "T%d_%d" % q self.labels_used.add(name) return "goto %s;" % name return "goto %s;" % self.lab(q) def st_else(self, p, li, at): """an ELSE or ELSEIF met in the course of running: on past END IF. Arriving by the scan, it is where the IF's false part starts""" P = self.P self.emit(self.block_jump(P.find_end(p, T["T_IF"], False), li, "E_ENDIF")) c, q = P.peek(p) if c == T["T_IF"]: # ELSEIF: its test, when the scan arrives self.emit("T%d_%d:;" % at) v, r = self.expr_or_rt((q[0], q[1] + 1), li) c2, r = P.peek(r) if c2 != T["T_THEN"]: self.err("E_SYNTAX", li) raise Stop r = (r[0], r[1] + 1) self.emit("if (!%s) %s" % (v, self.block_jump(P.find_end(r, T["T_IF"], True), li, "E_ENDIF"))) self.follow = True return r self.follow = True return p def st_for(self, p, li, at): P = self.P v, q = P.var_name(p) c, r = P.peek(q) if v is None or c != 61: self.err("E_SYNTAX", li) raise Stop a, q = self.expr_or_rt((r[0], r[1] + 1), li) self.emit("V[%d] = %s;" % (v, a)) self.emit("for (fi = 0; fi < nf; fi++) if (fs[fi].v == %d) { nf = fi; break; }" % v) self.emit("if (nf >= 16) rt_error(%d, %s);" % (E["E_FOR"], self.lr(li))) c, r = P.peek(q) if c != T["T_TO"]: self.err("E_SYNTAX", li) raise Stop lim, q = self.expr_or_rt((r[0], r[1] + 1), li) lt = self.temp() self.emit("%s = %s;" % (lt, lim)) c, r = P.peek(q) st = "1.0f" if c == T["T_STEP"]: st, q = self.expr_or_rt((r[0], r[1] + 1), li) body = self.lab(q) self.emit("fs[nf].v = %d; fs[nf].lim = %s; fs[nf].step = %s; fs[nf].tp = &&%s; nf++;" % (v, lt, st, body)) after = P.find_next(q) skip = self.scan_fail("E_NONEXT") if after is None else "goto %s;" % self.lab(after) self.emit("if ((fs[nf-1].step >= 0 && V[%d] > fs[nf-1].lim) || (fs[nf-1].step < 0 && V[%d] < fs[nf-1].lim)) { nf--; %s }" % (v, v, skip)) return q def st_next(self, p, li): P = self.P q = p while True: v, q = P.var_name(q) self.emit("if (!nf) rt_error(%d, %s);" % (E["E_NEXT"], self.lr(li))) if v is not None: self.emit("while (nf && fs[nf-1].v != %d) nf--;" % v) self.emit("if (!nf) rt_error(%d, %s);" % (E["E_NEXT"], self.lr(li))) self.emit("{ struct fe *f = &fs[nf-1]; float x = V[f->v] += f->step;") self.emit(" if ((f->step >= 0 && x <= f->lim) || (f->step < 0 && x >= f->lim)) { BRK(%s); goto *f->tp; }" % self.lr(li)) self.emit(" nf--; }") if v is None: return q c, r = P.peek(q) if c != 44: return q q = (r[0], r[1] + 1) def st_do(self, p, li, at): P = self.P c, q = P.peek(p) cond = None self.emit("DO%d_%d:;" % at) if c in (T["T_WHILE"], T["T_UNTIL"]): v, q = self.expr_or_rt((q[0], q[1] + 1), li) cond = ("!%s" if c == T["T_WHILE"] else "%s") % v if cond: after = P.find_loop(q) self.emit("if (%s) %s" % (cond, self.scan_fail("E_NOLOOP") if after is None else "goto %s;" % self.lab(after))) return q def st_loop(self, p, li, at): P = self.P do = self.do_of_loop.get(at) if do is None: self.err("E_NODO", li) raise Stop c, q = P.peek(p) again = "1" if c in (T["T_WHILE"], T["T_UNTIL"]): v, q = self.expr_or_rt((q[0], q[1] + 1), li) again = ("%s" if c == T["T_WHILE"] else "!%s") % v if True: self.emit("if (%s) { BRK(%s); goto DO%d_%d; }" % (again, self.lr(li), do[0], do[1])) return q def st_exit(self, p, li): P = self.P c, q = P.peek(p) q = (q[0], q[1] + 1) if c == T["T_DO"]: after = P.find_loop(q) self.emit(self.scan_fail("E_NOLOOP") if after is None else "goto %s;" % self.lab(after)) elif c == T["T_FOR"]: after = P.find_next(q) self.emit("if (!nf) rt_error(%d, %s);" % (E["E_NEXT"], self.lr(li))) self.emit("nf--; " + (self.scan_fail("E_NONEXT") if after is None else "goto %s;" % self.lab(after))) else: self.err("E_SYNTAX", li) raise Stop return q def st_select(self, p, li, at): P = self.P c, q = P.peek(p) if c != T["T_CASE"]: self.err("E_SYNTAX", li) raise Stop p = (q[0], q[1] + 1) sid = self.sels self.sels += 1 is_str = P.is_str_start(p) if is_str: _, a = P.peek(p) try: q = P.skip_sexpr(a) except SyntaxError: self.err("E_SYNTAX", li) raise Stop self.emit("rt_seval((u8 *)%s, ss%d, %s);" % (self.snip(self.span(a, q)), sid, self.lr(li))) self.need_str = True else: v, q = self.expr_or_rt(p, li) self.emit("sv%d = %s;" % (sid, v)) self.selects.append((sid, is_str)) # which CASEs this SELECT's scans reach stop = P.select_stops(q) self.emit(self.case_jump(stop, li)) while stop and stop[0] == "case": self.case_sel[stop[1]] = (sid, is_str) stop = P.select_stops(self.case_items_end(stop[1])) return q def case_items_end(self, at): """where a CASE's scan goes on from when nothing matches: past its items (a CASE ELSE always matches)""" P = self.P c, q = P.peek((at[0], at[1] + 1)) return P.skip_statement(q) def case_jump(self, stop, li): if stop is None: return self.scan_fail("E_ENDSEL") kind, q = stop if kind == "case": name = "C%d_%d" % q self.labels_used.add(name) return "goto %s;" % name return "goto %s;" % self.lab(q) def st_case(self, p, li, at): """a CASE met in the course of running: on past END SELECT. Arriving by its SELECT's scan: test it""" P = self.P self.emit(self.block_jump(P.find_end(p, T["T_SELECT"], False), li, "E_ENDSEL")) sel = self.case_sel.get(at) c, q = P.peek(p) self.emit("C%d_%d:;" % at) if c == T["T_ELSE"]: self.follow = True return (q[0], q[1] + 1) if sel is None: # no SELECT reaches it return P.skip_statement(p) sid, is_str = sel m = self.temp().replace("t", "i") self.emit("%s = 0;" % m) q = p while True: self.case_item(q, sid, is_str, m, li) q = self.after_item c2, r = P.peek(q) if c2 != 44: break q = (r[0], r[1] + 1) stop = P.select_stops(q) self.emit("if (!%s) %s" % (m, self.case_jump(stop, li))) self.follow = True return q def case_value(self, p, sid, is_str, li): """compare the selector with the value at p: an int temp -1, 0, 1""" P = self.P k = self.temp().replace("t", "i") if is_str: if not P.is_str_start(p): self.err("E_TYPE", li) raise Stop _, a = P.peek(p) q = P.skip_sexpr(a) self.emit("rt_seval((u8 *)%s, sb, %s); %s = cmp(ss%d, sb);" % (self.snip(self.span(a, q)), self.lr(li), k, sid)) else: v, q = self.expr_or_rt(p, li) self.emit("%s = sv%d < %s ? -1 : sv%d > %s;" % (k, sid, v, sid, v)) return k, q def case_item(self, p, sid, is_str, m, li): P = self.P c, q = P.peek(p) if c == 73 and P.byte((q[0], q[1] + 1)) == 83: # IS q = (q[0], q[1] + 2) op, q = P.relop(q) k, q = self.case_value(q, sid, is_str, li) if op: self.emit("%s |= (%s < 0 && %d) || (%s == 0 && %d) || (%s > 0 && %d);" % (m, k, op & 1, k, op & 2, k, op & 4)) else: c2, r = P.peek(q) if c2 == T["T_TO"]: k2, q = self.case_value((r[0], r[1] + 1), sid, is_str, li) self.emit("%s |= (%s >= 0) & (%s <= 0);" % (m, k, k2)) else: self.emit("%s |= %s == 0;" % (m, k)) self.after_item = q # ---- the whole program def compile(self): P = self.P self.selects = [] # DO ... LOOP pairs, as the scan from each DO finds its LOOP for li in range(len(P.lines)): p = (li, 0) while p is not None and p[0] == li: c, q = P.peek(p) if c == T["T_DO"]: lp = self.loop_pos(q) if lp is not None: self.do_of_loop[lp] = q p = P.next_stmt(p) for li, (num, t) in enumerate(P.lines): self.emit("/* %d */" % num) self.compile_line(li) self.emit("E%d:;" % li) self.emit("goto FINISH;") # a place jumped to that the compiler never reached: the interpreter # would have met an error before getting there out = "\n".join(self.out) defined = set(re.findall(r"^(\w+):;", out, re.M)) wanted = set(re.findall(r"goto (\w+);|&&(\w+)", out)) wanted = {a or b for a, b in wanted} - {"FINISH"} for name in sorted(wanted - defined): self.emit("%s: rt_error(%d, 0);" % (name, E["E_SYNTAX"])) def loop_pos(self, p): """the position of the LOOP that the scan from the DO at p finds""" P = self.P depth = 0 while True: p = P.next_stmt(p) if p is None: return None c, p = P.peek(p) if c == T["T_DO"]: depth += 1 elif c == T["T_LOOP"]: if depth == 0: return p depth -= 1 def extent(self, p): """where the statement at p ends: its ':', the end of the line, or an ELSE outside quotes""" q = self.P.skip_statement(p) t = self.P.lines[p[0]][1] qq, end = False, p[1] while end < q[1]: if t[end] == 34: qq = not qq elif t[end] == T["T_ELSE"] and not qq: break end += 1 return (p[0], end) def compile_line(self, li): """the line as the interpreter's execute loop runs it: statements, ':', and ELSE ending the THEN part of an IF""" P = self.P t = P.lines[li][1] p, mode = (li, 0), "stmt" while True: if mode == "stmt": c, p = P.peek(p) if c == 0: return if c == 58: p = (li, p[1] + 1) continue self.emit("S%d_%d:;" % p) mark = len(self.out) self.follow = False try: q = self.statement(p) except Stop: q, self.follow = self.extent(p), False except SyntaxError: del self.out[mark:] self.follow = False if self.control(p): self.err("E_SYNTAX", li) q = self.extent(p) else: q = self.interpreted(p) c2, r = P.peek(q) if self.follow and c2 not in (0, 58, T["T_ELSE"]): if self.follow == "then" and 48 <= c2 <= 57: n, q = self.lineno(r) # IF ... THEN line self.goto_line(n, li) p, mode = q, "after" continue p = r # a statement straight after continue p, mode = q, "after" continue # after a statement c, r = P.peek(p) if c == 58: p, mode = (li, r[1] + 1), "stmt" continue if c == 0: return if c == T["T_ELSE"]: # the THEN part is over self.emit("goto E%d;" % li) e = (li, r[1] + 1) self.emit("X%d_%d:;" % e) # where a false IF goes on c3, s3 = P.peek(e) if 48 <= c3 <= 57: n, q = self.lineno(s3) self.goto_line(n, li) p = q continue p, mode = e, "stmt" continue self.err("E_SYNTAX", li) # then on to an ELSE, if any off, qq = r[1], False while off < len(t) and not (t[off] == T["T_ELSE"] and not qq): if t[off] == 34: qq = not qq off += 1 if off >= len(t): return p = (li, off) def control(self, p): c, _ = self.P.peek(p) return c in (T["T_GOTO"], T["T_GOSUB"], T["T_RETURN"], T["T_ON"], T["T_IF"], T["T_FOR"], T["T_NEXT"], T["T_END"], T["T_STOP"], T["T_DO"], T["T_LOOP"], T["T_EXIT"], T["T_SELECT"], T["T_CASE"], T["T_ELSE"]) class Stop(Exception): """the rest of this line can't be reached (an error is certain)""" # ---------------------------------------------------------------- the C file RUNTIME = r""" typedef unsigned char u8; typedef unsigned int u32; typedef short i16; #define RT(n) (%(table)d + 4 * (n)) static float *(*const rt_init)(u32, const u8 *, u8 *) = (void *)RT(0); static void (*const rt_end)(void) = (void *)RT(1); static void (*const rt_exec)(u8 *, const u8 *) = (void *)RT(2); static float (*const rt_eval)(u8 *, const u8 *) = (void *)RT(3); static void (*const rt_seval)(u8 *, char *, const u8 *) = (void *)RT(4); static float (*const rt_fn)(u8, float, const u8 *) = (void *)RT(5); static float *(*const rt_aref)(u8, float, float, u8, const u8 *) = (void *)RT(6); static float (*const rt_pow)(float, float, const u8 *) = (void *)RT(7); static void (*const rt_error)(u8, const u8 *) __attribute__((noreturn)) = (void *)RT(8); static void (*const rt_break)(const u8 *) = (void *)RT(9); static void (*const rt_gfx)(u8, const i16 *, u8, const u8 *) = (void *)RT(10); static i16 ga[5]; extern u8 __bss_end[]; static float *V; /* BASIC's variables */ struct fe { unsigned short v; float lim, step; void *tp; }; static struct fe fs[16]; /* the FOR loops, as BASIC keeps them */ static u8 nf; static void *gs[32]; /* GOSUB's return places */ static u8 ng; static u8 bc; /* Ctrl-C, every 64th time round a loop */ #define BRK(l) do { if (!(++bc & 63)) rt_break(l); } while (0) static i16 ti(float v, const u8 *l) /* to_int() */ { if (v > 32767.0f || v < -32768.0f) rt_error(%(e_func)d, l); return (i16)v; } static float rel(float x, float y, int op) { int c = x < y ? -1 : x > y ? 1 : 0; return ((c < 0 && (op & 1)) || (c == 0 && (op & 2)) || (c > 0 && (op & 4))) ? -1 : 0; } static float pw(float x, float y, const u8 *l) /* ipow(): whole powers here */ { i16 n; float r = 1; u8 neg; if (y == (float)(i16)y && y >= -64 && y <= 64) { n = (i16)y; neg = n < 0; if (neg) n = -n; for (; n; n >>= 1, x *= x) if (n & 1) r *= x; return neg ? 1 / r : r; } return rt_pow(x, y, l); } static int cmp(const char *a, const char *b) { while (*a && *a == *b) a++, b++; return (u8)*a < (u8)*b ? -1 : (u8)*a > (u8)*b; } """ def c_source(gen, name): P = gen.P o = ["/* %s, compiled by tools/basc.py: don't edit */" % name, RUNTIME % {"table": RT_TABLE, "e_func": E["E_FUNC"]}] o.append("static const u8 LR[%d][3] = {%s};" % ( len(P.lines), ",".join("{3,%d,%d}" % (n & 255, n >> 8) for n, _ in P.lines))) # the DATA lines, in BASIC's line format, for READ data = bytearray() for n, t in P.lines: q = False has = False for b in t: if b == 34: q = not q elif b == T["T_DATA"] and not q: has = True break if has: data += bytes([len(t) + 4, n & 255, n >> 8]) + t + b"\0" data += b"\0" o.append("static const u8 DATA[] = %s;" % c_bytes(data)) for b, s in gen.snips.items(): o.append("static const u8 %s[] = %s;" % (s, c_bytes(b + b"\0"))) for i, k in enumerate(gen.consts): o.append("static const u8 KS%d[] = %s;" % (i, c_bytes(k + b"\0"))) if gen.consts: o.append("static float K[%d];" % len(gen.consts)) for sid, is_str in gen.selects: o.append("static char ss%d[80];" % sid if is_str else "static float sv%d;" % sid) o.append("static char sb[80];") o.append("int main(void)\n{") temps = ["t%d" % i for i in range(1, gen.ntemp + 1)] o.append(" float %s;" % ", ".join(["x0"] + temps)) o.append(" float %s;" % ", ".join("*a%d" % i for i in range(gen.ntemp + 1))) o.append(" int fi, %s;" % ", ".join(["i0"] + ["i%d" % i for i in range(1, gen.ntemp + 1)])) o.append(" V = rt_init(%d, DATA, __bss_end);" % RT_ABI) o.append(" nf = ng = 0;") for i in range(len(gen.consts)): o.append(" K[%d] = rt_eval((u8 *)KS%d, 0);" % (i, i)) for s in gen.out: o.append(" " + s) o.append("FINISH:\n rt_end();\n return 0;\n}") return "\n".join(o) + "\n" # ---------------------------------------------------------------- building def rv_env(): out = subprocess.run(["bash", "-c", "source %s/scripts/rv_env.sh && echo $RV_PREFIX && echo $RV_ARCH_F" % ROOT], capture_output=True, text=True) if out.returncode: raise CompileError(out.stderr.strip()) prefix, arch = out.stdout.strip().split("\n") return prefix, arch.split() def build(csrc, outdir, name, fast, keep_c): prefix, arch = rv_env() work = tempfile.mkdtemp(prefix="basc-") c = os.path.join(outdir if keep_c else work, name.lower() + ".c") open(c, "w").write(csrc) opt = "-O2" if fast else "-Os" flags = arch + ["-ffp-contract=off", opt, "-mno-relax", "-ffunction-sections", "-fdata-sections", "-fno-common", "-Wall", "-Wno-unused-label", "-Wno-unused-variable", "-Wno-unused-but-set-variable", "-Wno-unused-function", "-Wno-maybe-uninitialized"] elf = os.path.join(work, "prog.elf") cmds = [ [prefix + "gcc"] + flags + ["-c", "-o", os.path.join(work, "crt0.o"), os.path.join(ROOT, "games", "crt0.S")], [prefix + "gcc"] + flags + ["-c", "-o", os.path.join(work, "prog.o"), c], [prefix + "gcc"] + arch + ["-nostdlib", "-nostartfiles", "-T", os.path.join(ROOT, "games", "game.ld"), "-Wl,--no-relax", "-Wl,--gc-sections", "-Wl,--build-id=none", "-Wl,--no-warn-rwx-segments", "-o", elf, os.path.join(work, "crt0.o"), os.path.join(work, "prog.o"), "-lgcc"], ] for cmd in cmds: r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode: raise CompileError("GCC failed (a bug in basc.py):\n" + r.stderr[-3000:]) ihx = os.path.join(outdir, name + ".ihx") subprocess.run([prefix + "objcopy", "-O", "ihex", "-j", ".text", "-j", ".data", elf, ihx], check=True) syms = {} for line in subprocess.run([prefix + "nm", elf], capture_output=True, text=True).stdout.splitlines(): f = line.split() if len(f) == 3: syms[f[2]] = int(f[0], 16) sizes = subprocess.run([prefix + "size", "-A", elf], capture_output=True, text=True).stdout data = [int(l.split()[1]) for l in sizes.splitlines() if l.startswith(".data ")] if data and data[0]: raise CompileError("the program has initialised variables (a bug in basc.py)") end = syms["__bss_end"] if end > PROG_END: raise CompileError("the program needs %d bytes, beyond BASIC's program area by %d" % (end - LOAD_AT, end - PROG_END)) return syms["__bss_start"] - LOAD_AT, end - LOAD_AT, ihx def main(): ap = argparse.ArgumentParser(description="Compile a BASIC program for the Basys 3 RISC-V computer.") ap.add_argument("file") ap.add_argument("-o", "--outdir") ap.add_argument("--name", help="the loader's name; the memory file is this with C on the end") ap.add_argument("--fast", action="store_true", help="optimise for speed (-O2) instead of size") ap.add_argument("--keep-c", action="store_true", help="keep the C in the output folder") a = ap.parse_args() base = os.path.splitext(os.path.basename(a.file))[0] name = (a.name or re.sub(r"[^A-Za-z0-9]", "", base)).upper()[:7] if not name or not name[0].isalpha(): sys.exit("basc: give a --name of letters and digits, starting with a letter") mem = name + "C" outdir = a.outdir or os.path.dirname(os.path.abspath(a.file)) os.makedirs(outdir, exist_ok=True) try: prog = Prog(read_program(a.file)) if not prog.lines: raise CompileError("there is no program") gen = Gen(prog) gen.compile() code, total, ihx = build(c_source(gen, name), outdir, name, a.fast, a.keep_c) except CompileError as e: sys.exit("basc: %s" % e) loader = os.path.join(outdir, name + ".bas") open(loader, "w").write('10 REM %s, COMPILED: LOADS %s AND RUNS IT AT A200H\n20 BLOAD "%s": CALL 41472\n' % (name, mem, mem)) print("%s: %d bytes of code and constants, %d with variables (A200-%04X)" % (ihx, code, total, LOAD_AT + total - 1)) print("send it: tools/send-hex.py %s --save %s" % (ihx, mem)) print("then the loader, %s, and SAVE \"%s\"; RUN \"%s\" runs it" % (loader, name, name)) if __name__ == "__main__": main()