#!/usr/bin/env python3 """Check tools/basc.py: run BASIC programs both interpreted and compiled in tools/rv32emu.py (the board model of tools/boardemu.py) and check the screen and the graphics come out the same; and time them. python3 test-compile.py [--only NAME] [--keep DIR] The programs are the ones in basic/examples (with their waits for the clock and the sound chip taken out, which an emulator can't time) and the programs of the other basic/test-*.py suites, plus programs here that go through each statement and the errors. """ import argparse import importlib.util import os import re import subprocess import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) spec = importlib.util.spec_from_file_location("te", os.path.join(HERE, "test-edit.py")) te = importlib.util.module_from_spec(spec) spec.loader.exec_module(te) CR = te.CR sys.path.insert(0, os.path.join(ROOT, "tools")) from boardemu import load_ihx # noqa: E402 CALL = b"CALL 41472" # BASIC waits for the next line here once a run is over (READY) READ_LINE = next(int(l.split()[0], 16) for l in open(os.path.join(HERE, "out", "basic.sym")) if l.split()[2:] == ["read_line"]) def screen(b): return "\n".join(l.rstrip() for l in b.screen_text().display) def after(text, cmd): """the screen from the line where cmd was typed""" i = text.rfind(cmd) return text[i + len(cmd):] if i >= 0 else text class Runner: def __init__(self, keep=None): self.dir = keep or tempfile.mkdtemp(prefix="basc-test-") os.makedirs(self.dir, exist_ok=True) def go(self, cmd, steps): """type cmd and Enter, and run until BASIC asks for the next line; the clocks it took""" b = self.b b.type(cmd) c0 = b.cycles b.keys_in += CR n = 0 while n < steps: b.step() n += 1 if b.pc == READ_LINE: return b.cycles - c0 raise RuntimeError("still running after %d instructions" % steps) def fresh(self): """a computer just switched on, so RND starts in the same place""" self.b = te.Basic() self.b.type(b"") return self.b def interpreted(self, prog, steps=200_000_000): b = self.fresh() b.type(b"NEW" + CR) for line in prog.strip().splitlines(): b.type(line.encode("latin-1") + CR) b.type(b"CLS" + CR) b.gfx[:] = bytes(len(b.gfx)) c = self.go(b"RUN", steps) return after(screen(b), "RUN"), bytes(b.gfx), c def compiled(self, prog, name, steps=200_000_000, fast=False): src = os.path.join(self.dir, name.lower() + ".bas") open(src, "wb").write(prog.strip().encode("latin-1") + b"\n") cmd = [sys.executable, os.path.join(ROOT, "tools", "basc.py"), src, "-o", self.dir, "--name", name, "--keep-c"] + (["--fast"] if fast else []) r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode: return None, r.stderr.strip(), 0 size = int(re.search(r": (\d+) bytes of code", r.stdout).group(1)) mem, hi = load_ihx(os.path.join(self.dir, name + ".ihx")) b = self.fresh() for a in range(0xA200, hi): b.wr8(a, mem[a]) b.type(b"CLS" + CR) b.gfx[:] = bytes(len(b.gfx)) c = self.go(CALL, steps) return after(screen(b), "CALL 41472"), bytes(b.gfx), (c, size) # ------------------------------------------------------------- the programs def examples(): """basic/examples, with the waits an emulator can't time taken out""" out = {} for f in sorted(os.listdir(os.path.join(HERE, "examples"))): if not f.endswith(".bas"): continue text = open(os.path.join(HERE, "examples", f), "rb").read().decode("latin-1") lines = {int(l.split()[0]): l for l in text.splitlines() if l.strip()} name = f[:-4] if name == "graphics-demo": lines[9010] = "9010 RETURN" # three seconds' pause lines[700] = "700 REM" # a frame's wait lines[630] = "630 FOR I=1 TO 60" # fewer frames lines[810] = "810 FOR J=0 TO 14: FOR I=0 TO 19" # a corner of the set lines[900] = '900 INK 7: LOCATE 30,1: PRINT "MANDELBROT DONE";' lines[910] = '910 PRINT " WHOLE DEMO DONE"' if name == "sound": for n in (90, 170, 230): # waits for the envelopes lines[n] = "%d REM" % n if name == "sprites": # 30 frames, the same each time lines[50] = "50 REM" # (RANDOMIZE takes the clock) lines[390] = "390 REM" # the wait for the next frame lines[400] = "400 Z9 = Z9 + 1: IF Z9 < 30 THEN 300" lines[410] = "410 FOR I = 1 TO N: PRINT X(I); Y(I);: NEXT I: END" out[name] = "\n".join(lines[n] for n in sorted(lines)) return out def suite_programs(): """the programs of the other test-*.py suites""" progs = {} for f in sorted(os.listdir(HERE)): if not (f.startswith("test-") and f.endswith(".py")) or f == "test-compile.py": continue src = open(os.path.join(HERE, f)).read() for k, m in enumerate(re.finditer(r"run\('''\n(.*?)'''\)", src, re.S)): body = m.group(1) if "INPUT" in body: continue progs["%s-%d" % (f[5:-3], k)] = body return progs PROGRAMS = { "control": r''' 10 FOR I = 1 TO 3: FOR J = I TO 3: PRINT I * 10 + J;: NEXT J, I: PRINT 20 FOR X = 10 TO 1 STEP -3.5: PRINT X;: NEXT: PRINT 30 FOR Z = 5 TO 1: PRINT "NEVER": NEXT Z: PRINT "SKIPPED" 40 N = 2: ON N GOTO 50, 60, 70 50 PRINT "WRONG" 60 PRINT "ON GOTO": ON 3 GOSUB 900, 900, 910: ON 7 GOTO 50: PRINT "OUT OF RANGE" 70 IF 0 THEN 50 ELSE IF 1 THEN PRINT "NESTED ELSE" ELSE PRINT "NO" 80 IF 1 THEN IF 0 THEN PRINT "X" ELSE PRINT "Y" ELSE PRINT "Z" 90 A = 5: IF A > 3 AND A < 10 OR NOT A THEN PRINT "LOGIC"; 6 AND 3; 6 OR 3; NOT 0 100 PRINT 2 ^ 3 ^ 2; -2 ^ 2; 2 ^ -1; 2 ^ .5; (1 < 2) + (2 < 1); 7 / 2; 1E3 + .25 110 K = 0: DO: K = K + 1: IF K = 4 THEN EXIT DO 120 LOOP: PRINT "K"; K 130 DO UNTIL K = 0: K = K - 1: LOOP: PRINT "K"; K 140 FOR Q = 1 TO 100: IF Q = 7 THEN EXIT FOR 150 NEXT Q: PRINT "Q"; Q 160 GOSUB 920: PRINT "BACK" 170 FOR I = 0 TO 7 180 SELECT CASE I * 2 190 CASE 0: PRINT "ZERO"; 200 CASE 2, 4: PRINT "SMALL"; 210 CASE 6 TO 9: PRINT "MID"; 220 CASE IS >= 12: PRINT "BIG"; 230 CASE ELSE: PRINT "OTHER"; 240 END SELECT 250 NEXT I: PRINT 260 B$ = "PEAR" 270 SELECT CASE B$ 280 CASE "APPLE": PRINT "A" 290 CASE "B" TO "Q": PRINT "IN RANGE" 300 END SELECT 310 FOR I = 1 TO 4 320 IF I = 1 THEN 330 PRINT "ONE"; 340 ELSEIF I = 2 THEN 350 PRINT "TWO"; 360 ELSE IF I = 3 THEN 370 PRINT "THREE"; 380 ELSE 390 PRINT "MANY"; 400 END IF 410 NEXT I: PRINT 420 DIM M(3, 3): FOR I = 0 TO 3: FOR J = 0 TO 3: M(I, J) = I * J: NEXT J, I 430 PRINT M(2, 3); M(3, 3); C(10) 440 DEF FNS(X) = X * X + 1: PRINT FNS(3); FNS(M(1, 2)) 450 PRINT SIN(1); COS(1); ATN(1) * 4; EXP(1); LOG(10); SQR(2); ABS(-3); SGN(-2); INT(-2.5) 460 OPTION ANGLE DEGREES: PRINT SIN(30); ASIN(1); ANGLE(-1, 0): OPTION ANGLE RADIANS 470 PRINT LOG10(1000); FACT(10); ROUND(2.567, 2); MOD(-7, 3); MIN(3, 1, 2); PI 480 RESTORE: READ R, R$: PRINT R; R$: DATA 17, "SEVEN" 490 S$ = "HELLO": PRINT LEN(S$); LEFT$(S$, 2); UCASE$("x"); (S$ = "HELLO"); ASC(S$) 500 RANDOMIZE: R = RND: PRINT R >= 0 AND R < 1 510 PRINT "THE END": END 900 PRINT "SUB A": RETURN 910 PRINT "SUB B": RETURN 920 GOSUB 900: RETURN ''', "errors-div": "10 X = 0\n20 PRINT 1 / X", "errors-next": "10 NEXT I", "errors-return": "10 PRINT 1: RETURN", "errors-goto": "10 GOTO 99", "errors-sub": "10 DIM A(3)\n20 A(4) = 1", "errors-func": "10 PRINT SQR(-1)", "errors-int": "10 PRINT 40000 AND 1", "errors-syntax": "10 PRINT 1\n20 X = 3 +", "errors-type": '10 X = "A"', "errors-stop": "10 PRINT 1: STOP: PRINT 2", "errors-loop": "10 LOOP", "errors-endif": "10 IF 0 THEN\n20 PRINT 1", "errors-deep": "10 GOSUB 10", "graphics": r''' 10 CLS: FOR I = 0 TO 15: FILL I * 20, 0, I * 20 + 19, 30, I: NEXT 20 FOR X = 0 TO 319 STEP 4: PLOT X, 120 - 50 * SIN(X / 30), 14: NEXT 30 LINE 0, 239, 319, 100, 12: CIRCLE 160, 150, 40, 10: RECT 10, 50, 60, 90, 9 40 PRINT POINT(5, 5); POINT(25, 5); POINT(160, 110) ''', } # each time round the loop, from the difference between 500 and 1500 times BENCH = { "an empty FOR ... NEXT": "10 FOR I = 1 TO {n}: NEXT I", "X = I * 1.5": "10 FOR I = 1 TO {n}: X = I * 1.5: NEXT I", "Y = SIN(I)": "10 FOR I = 1 TO {n}: Y = SIN(I): NEXT I", "A(J) = A(J) + I": "10 DIM A(10): FOR I = 1 TO {n}: J = I AND 7: A(J) = A(J) + I: NEXT I", "IF ... THEN, GOSUB": "10 FOR I = 1 TO {n}: IF I > 0 THEN GOSUB 30\n20 NEXT I: END\n30 RETURN", "PLOT I / 5, 100, 7": "10 FOR I = 1 TO {n}: PLOT I / 5, 100, 7: NEXT I", "PRINT I;": "10 FOR I = 1 TO {n}: PRINT I;: NEXT I", } def bench(run): print("speed: each time round the loop, at 100 MHz (emulated clocks)") for name, prog in BENCH.items(): r = {} for n in (500, 1500): p = prog.replace("{n}", str(n)) r["i", n] = run.interpreted(p)[2] r["c", n] = run.compiled(p, "B")[2][0] r["f", n] = run.compiled(p, "BF", fast=True)[2][0] i, c, f = ((r[k, 1500] - r[k, 500]) / 1000 / 100 for k in "icf") print(" %-22s interpreted %7.2f us, compiled %6.3f us (%3.0f times), --fast %6.3f us (%3.0f times)" % (name, i, c, i / c, f, i / f)) def main(): ap = argparse.ArgumentParser() ap.add_argument("--only") ap.add_argument("--keep") ap.add_argument("--no-bench", action="store_true") a = ap.parse_args() run = Runner(a.keep) progs = dict(examples()) progs.update(suite_programs()) progs.update(PROGRAMS) errors = 0 for k, (name, prog) in enumerate(sorted(progs.items())): if a.only and a.only not in name: continue it, ig, ic = run.interpreted(prog) ct, cg, cc = run.compiled(prog, "P%d" % k) if ct is None: print("FAIL %s: basc says %s" % (name, cg)) errors += 1 continue same = it == ct and ig == cg print("%s %s: %s, %d bytes of code, %.1f times faster" % ("PASS" if same else "FAIL", name, "same screen and graphics" if same else "different", cc[1], ic / max(cc[0], 1))) if not same: errors += 1 il, cl = it.splitlines(), ct.splitlines() for i in range(max(len(il), len(cl))): x = il[i] if i < len(il) else "" y = cl[i] if i < len(cl) else "" if x != y: print(" row %d interpreted: %r\n row %d compiled: %r" % (i, x, i, y)) if ig != cg: print(" the graphics differ in %d pixels" % sum(p != q for p, q in zip(ig, cg))) if not a.no_bench and not a.only: bench(run) sys.exit(1 if errors else 0) if __name__ == "__main__": main()