BASIC compiler (tools/basc.py) and a runtime jump table in BASIC's ROM

tools/basc.py compiles a BASIC program to C and through GCC to an Intel HEX
file loaded at A200h like the games, with a two-line BLOAD/CALL loader.
Arithmetic, variables, arrays, all control flow and graphics arguments are
compiled; PRINT, INPUT, strings, files, sound, DATA and the remaining
functions go through BASIC's ROM via a fixed jump table at 9F00h (RT_ABI 1),
so they behave identically. basic/test-compile.py runs 31 programs both
ways and checks identical screens and graphics; typical loops run 7-26x
faster. New error PROGRAM NEEDS ANOTHER BASIC.

Fixes a bug present since the first version: variable numbers past 255
wrapped, so X1-Z9 shared storage with A-B9 (A7 and Y were the same
variable). test-blocks.py checks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-12-01 19:29:59 -08:00
1 parent fa4752fd7a
commit 2e668c708f
11 files changed
+5703 -3671

No files matched your search

BIN
View File
Binary file not shown.
+165 -24
View File
@@ -239,10 +239,10 @@ static char svars[26][STRMAX];
struct array { u8 *p; u16 d1, d2; };
static struct array arrays[52]; /* A()-Z(), then A$()-Z$() */
struct fn { u8 *body; u8 var; };
struct fn { u8 *body; u16 var; };
static struct fn fns[26];
struct forent { u8 var; float limit, step; u8 *tp, *ln; };
struct forent { u16 var; float limit, step; u8 *tp, *ln; };
static struct forent fors[FORMAX];
static u8 nfor;
@@ -254,6 +254,8 @@ struct doent { u8 *tp, *ln; }; /* tp is the DO itself */
static struct doent dos[DOMAX];
static u8 ndo;
static u8 *data_base; /* where READ looks for DATA: 0 = the program */
static u8 *rt_floor; /* arrays stay above this (a compiled program) */
static u8 *tp; /* text pointer */
static u8 *curln; /* line being run, 0 in direct mode */
static u8 *datap; /* next DATA item, 0 = search from the start */
@@ -301,7 +303,7 @@ enum {
E_SYNTAX, E_LINE, E_RETURN, E_NEXT, E_DATA, E_SUBSCRIPT, E_DIV0, E_MEMORY,
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_NOFILE, E_DISKFULL,
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_NOLOOP,
E_NODO, E_DODEEP, E_NONEXT, E_ENDIF, E_ENDSEL, E_BREAK, E_STOP
E_NODO, E_DODEEP, E_NONEXT, E_ENDIF, E_ENDSEL, E_VERSION, E_BREAK, E_STOP
};
static const char *const errmsg[] = {
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
@@ -311,7 +313,7 @@ static const char *const errmsg[] = {
"FILE NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
"FILE TOO BIG", "FILE ALREADY OPEN", "FILE NOT OPEN", "INPUT PAST END",
"DO WITHOUT LOOP", "LOOP WITHOUT DO", "DO NESTED TOO DEEPLY", "FOR WITHOUT NEXT",
"IF WITHOUT END IF", "SELECT WITHOUT END SELECT",
"IF WITHOUT END IF", "SELECT WITHOUT END SELECT", "PROGRAM NEEDS ANOTHER BASIC",
"BREAK", "STOP"
};
@@ -597,6 +599,7 @@ static void clear_vars(void)
nfor = nsub = ndo = 0;
datap = 0;
deg = 0;
data_base = rt_floor = 0;
}
static void new_prog(void)
@@ -663,16 +666,18 @@ static u16 get_lineno(void)
return n;
}
/* Numeric variable name: letter with an optional digit. Returns its index, or
255 if the text is not a numeric variable (does not move tp then). */
static u8 var_name(void)
/* Numeric variable name: letter with an optional digit. Returns its index,
0 to 285 (so not a byte: X1 to Z9 once wrapped onto A to B9), or NOVAR if
the text is not a numeric variable (does not move tp then). */
#define NOVAR 0xFFFF
static u16 var_name(void)
{
u8 c = peekc(), d;
if (!is_alpha(c)) return 255;
if (!is_alpha(c)) return NOVAR;
d = tp[1];
if (d == '$') return 255;
if (d == '$') return NOVAR;
if (is_digit(d)) {
if (tp[2] == '$') return 255;
if (tp[2] == '$') return NOVAR;
tp += 2;
return (c - 'A') * 11 + 1 + d - '0';
}
@@ -708,7 +713,7 @@ static void arr_alloc(u8 a, u16 d1, u16 d2)
if ((i16)d1 < 0 || (i16)d2 < 0 || n > (a < 26 ? 6000 : 255)) error(E_SUBSCRIPT);
sz = n * (a < 26 ? sizeof(float) : STRMAX);
np = arr_low - sz;
if (np <= prog_end + 1) error(E_MEMORY);
if (np <= prog_end + 1 || np < rt_floor) error(E_MEMORY);
arr_low = np;
memset(np, 0, sz);
ar->p = np;
@@ -716,9 +721,10 @@ static void arr_alloc(u8 a, u16 d1, u16 d2)
ar->d2 = d2;
}
static u8 *elem_at(u8 a, i16 i, i16 j, u8 two);
static u8 *array_elem(u8 a)
{
struct array *ar = &arrays[a];
i16 i, j = 0;
u8 two;
expect('(');
@@ -726,6 +732,13 @@ static u8 *array_elem(u8 a)
two = accept(',');
if (two) j = to_int(expr());
expect(')');
return elem_at(a, i, j, two);
}
/* element i (, j) of array a */
static u8 *elem_at(u8 a, i16 i, i16 j, u8 two)
{
struct array *ar = &arrays[a];
if (!ar->p) arr_alloc(a, 10, two ? 10 : 0); /* undeclared: 0..10 */
if (i < 0 || i > (i16)ar->d1 || j < 0 || j > (i16)ar->d2) error(E_SUBSCRIPT);
return ar->p + ((u16)i * (ar->d2 + 1) + j) * (a < 26 ? sizeof(float) : STRMAX);
@@ -743,14 +756,14 @@ static char *str_ref(void)
/* A numeric variable or array element as an lvalue. */
static float *num_ref(void)
{
u8 v;
u16 v;
if (is_alpha(peekc()) && tp[1] == '(') {
v = *tp - 'A';
tp++;
return (float *)array_elem(v);
}
v = var_name();
if (v == 255) error(E_SYNTAX);
if (v == NOVAR) error(E_SYNTAX);
return &vars[v];
}
@@ -813,11 +826,12 @@ static float round_to(float x, i16 n, u8 rnd)
return (n < 0 ? s * p : s / p) + 0.0f;
}
static float func2v(u8 t, float v);
static float func2(u8 t, float v)
{
float w;
i16 n = 0;
u8 i;
switch (t) {
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
expect(',');
@@ -846,6 +860,14 @@ static float func2(u8 t, float v)
return v;
}
expect(')');
return func2v(t, v);
}
/* the one-argument functions from DEG on, of v */
static float func2v(u8 t, float v)
{
float w;
u8 i;
switch (t) {
case T_DEG: return v * 180.0f / PI_F;
case T_RAD: return v * PI_F / 180.0f;
@@ -878,6 +900,8 @@ static float func2(u8 t, float v)
return 0;
}
static float func1(u8 t, float v);
static float func(u8 t)
{
char s[STRMAX];
@@ -917,6 +941,12 @@ static float func(u8 t)
v = expr();
if (t >= T_ANGLE) return func2(t, v);
expect(')');
return func1(t, v);
}
/* the one-argument functions SIN to INP, of v */
static float func1(u8 t, float v)
{
switch (t) {
case T_SIN: return sin_cos(v, 0);
case T_COS: return sin_cos(v, 1);
@@ -1543,7 +1573,7 @@ static void next_data(void)
while (*datap == ' ') datap++;
if (*datap == ',') { datap++; return; }
dataln += *dataln;
} else dataln = arena;
} else dataln = data_base ? data_base : arena;
for (; *dataln; dataln += *dataln) {
u8 *p = dataln + 3, q = 0;
for (; *p; p++) {
@@ -1741,8 +1771,9 @@ static void st_select(void)
static void st_for(void)
{
struct forent *f;
u8 v = var_name(), i;
if (v == 255) error(E_SYNTAX);
u16 v = var_name();
u8 i;
if (v == NOVAR) error(E_SYNTAX);
expect('=');
vars[v] = expr();
for (i = 0; i < nfor; i++) /* reusing a loop variable restarts it */
@@ -1766,11 +1797,11 @@ static void st_for(void)
static void st_next(void)
{
struct forent *f;
u8 v;
u16 v;
do {
v = var_name();
if (!nfor) error(E_NEXT);
if (v != 255) {
if (v != NOVAR) {
while (nfor && fors[nfor - 1].var != v) nfor--;
if (!nfor) error(E_NEXT);
}
@@ -1784,7 +1815,7 @@ static void st_next(void)
return;
}
nfor--;
} while (v != 255 && accept(','));
} while (v != NOVAR && accept(','));
}
static void st_dim(void)
@@ -1804,14 +1835,15 @@ static void st_dim(void)
static void st_def(void)
{
u8 f, v;
u8 f;
u16 v;
expect(T_FN);
f = peekc();
if (!is_alpha(f)) error(E_SYNTAX);
tp++;
expect('(');
v = var_name();
if (v == 255) error(E_SYNTAX);
if (v == NOVAR) error(E_SYNTAX);
expect(')');
expect('=');
fns[f - 'A'].var = v;
@@ -1853,10 +1885,17 @@ static void run_prog(void)
static u8 gcolor = 15;
/* Up to n comma-separated integer arguments; returns how many were given. */
static const i16 *pre_a; /* rt_gfx: the numbers, worked out */
static u8 pre_n;
static u8 int_args(i16 *a, u8 min, u8 n)
{
u8 i = 0;
do a[i++] = to_int(expr()); while (i < n && accept(','));
if (pre_a) {
for (; i < pre_n; i++) a[i] = pre_a[i];
pre_a = 0;
} else
do a[i++] = to_int(expr()); while (i < n && accept(','));
if (i < min) error(E_SYNTAX);
return i;
}
@@ -2687,6 +2726,108 @@ static void execute(void)
running = 0;
}
/* ------------------------------------------------ for compiled programs
tools/basc.py compiles BASIC to machine code, which calls these through
the jump table at 9F00h (rt_table): statements and expressions it leaves
to the interpreter go to rt_exec and rt_eval as tokens, so they behave
exactly as they would interpreted. line is a 3-byte line record (its
number in bytes 1 and 2) for error messages. The table's order and the
tokens' and errors' values only ever grow: RT_ABI counts the changes. */
#define RT_ABI 1
static u8 *rt_tp, *rt_ln; /* the CALL that started the program */
float *rt_init(u32 abi, u8 *data, u8 *end)
{
if (abi != RT_ABI) error(E_VERSION);
rt_tp = tp;
rt_ln = curln;
clear_vars(); /* as RUN does */
data_base = data;
rt_floor = end;
return vars;
}
void rt_end(void) /* END, or the last line */
{
close_all();
tp = rt_tp;
curln = rt_ln;
}
void rt_exec(u8 *s, u8 *line) /* one statement */
{
curln = line;
tp = s;
statement();
if (peekc()) error(E_SYNTAX);
}
float rt_eval(u8 *s, u8 *line) /* a numeric expression */
{
curln = line;
tp = s;
return expr();
}
void rt_seval(u8 *s, char *out, u8 *line) /* a string expression */
{
curln = line;
tp = s;
sexpr(out);
}
float rt_fn(u8 t, float v, u8 *line) /* a one-argument function; RND, TIM */
{
curln = line;
if (t == T_RND) return rnd();
if (t == T_TIM) return (float)millis() / 1000.0f;
return t >= T_ANGLE ? func2v(t, v) : func1(t, v);
}
float *rt_aref(u8 a, float i, float j, u8 two, u8 *line) /* A(I) or A(I, J) */
{
i16 k;
curln = line;
k = to_int(i);
return (float *)elem_at(a, k, two ? to_int(j) : 0, two);
}
float rt_pow(float x, float y, u8 *line)
{
curln = line;
return ipow(x, y);
}
/* a graphics statement (CLS COLOR PLOT LINE RECT FILL CIRCLE LOCATE INK
SCREEN) with its n numbers, between its fewest and most */
void rt_gfx(u8 t, const i16 *a, u8 n, u8 *line)
{
curln = line;
pre_a = t == T_CLS ? 0 : a;
pre_n = n;
graphics(t);
}
void rt_error(u8 e, u8 *line)
{
curln = line;
error(e);
}
void rt_break(u8 *line) /* Ctrl-C? */
{
curln = line;
check_break();
}
/* at 9F00h (basic.ld), fixed for good */
__asm__(".section .rtab, \"ax\"\n"
".globl rt_table\n"
"rt_table:\n"
" j rt_init\n j rt_end\n j rt_exec\n j rt_eval\n j rt_seval\n"
" j rt_fn\n j rt_aref\n j rt_pow\n j rt_error\n j rt_break\n j rt_gfx\n"
".previous");
int main(void)
{
u16 n;
+2
View File
@@ -17,6 +17,8 @@ SECTIONS
*(.rodata .rodata.* .srodata .srodata.*)
. = ALIGN(4);
} > ROM
/* the jump table for compiled programs (rt_table in basic.c): fixed */
.rtab 0x9F00 : { KEEP(*(.rtab)) } > ROM
.arena (NOLOAD) : { KEEP(*(.arena)) } > RAM
.data : ALIGN(4) {
__data_start = .;
+3646 -3646
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -13,7 +13,7 @@ ${RV_PREFIX}gcc $CFLAGS -c -o out/mathf.o ../lib/mathf.c
${RV_PREFIX}gcc $CFLAGS -c -o out/setjmp.o ../lib/setjmp.S
${RV_PREFIX}gcc $RV_ARCH_F -nostdlib -nostartfiles -T basic.ld -Wl,--gc-sections -Wl,-Map,out/basic.map \
-Wl,--build-id=none -o out/basic.elf out/crt0.o out/basic.o out/string.o out/mathf.o out/setjmp.o -lgcc
${RV_PREFIX}objcopy -O binary -j .text -j .data out/basic.elf basic.bin
${RV_PREFIX}objcopy -O binary -j .text -j .rtab -j .data out/basic.elf basic.bin
${RV_PREFIX}nm -n out/basic.elf > out/basic.sym
python3 ../tools/bin2mem.py basic.bin out/basic-all.mem 20480
head -n 16384 out/basic-all.mem > basic.mem
+8
View File
@@ -150,6 +150,14 @@ def main():
''')
check("GOTO back to a DO does not fill its stack", " 40 41 END" in out, out)
out = run('''
10 A7 = 5: Y = 9: X2 = 3: A = 1: B8 = 2
20 FOR Z9 = 1 TO 2: NEXT Z9
30 DEF FNQ(Y7) = Y7 * 10
40 PRINT A7; Y; X2; A; B8; Z9; FNQ(4); Y7
''')
check("X1 to Z9 are variables of their own (not A to B9)", " 5 9 3 1 2 3 40 0" in out, out)
b.type(b"CLS" + CR)
b.type(b'I=0: DO: I=I+1: LOOP UNTIL I=7: PRINT "DIRECT"; I' + CR)
check("DO ... LOOP in a direct statement", "DIRECT 7" in screen(), screen())
+289
View File
@@ -0,0 +1,289 @@
#!/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()