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 0fffb8bfab
11 files changed
+5702 -3670

No files matched your search

+10
View File
@@ -20,6 +20,9 @@ RISC-V processor written from scratch in Verilog:
`LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a `LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a
machine-code monitor with a RISC-V disassembler and assembler, and five machine-code monitor with a RISC-V disassembler and assembler, and five
original games. original games.
- **A BASIC compiler** for the PC (`tools/basc.py`): the same program, the
same results and error messages, 7 to 26 times as fast in loops and
arithmetic.
The [BASIC manual](docs/basic-manual.md) ([PDF](docs/basic-manual.pdf)) The [BASIC manual](docs/basic-manual.md) ([PDF](docs/basic-manual.pdf))
describes the computer from the user's side: BASIC, graphics, sprites, sound, describes the computer from the user's side: BASIC, graphics, sprites, sound,
@@ -167,6 +170,12 @@ All in C (plus a little assembly), compiled with GCC:
assembler that both use GNU as syntax (`.org`, `.word`, `.string`, assembler that both use GNU as syntax (`.org`, `.word`, `.string`,
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel `%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
HEX in and out. HEX in and out.
- `tools/basc.py` — the BASIC compiler. It reads a program with BASIC's own
tokens and turns it into C for GCC: arithmetic, variables, arrays, control
statements and graphics become machine code on the FPU; everything else is
handed, as tokens, to the interpreter in ROM through a jump table at 9F00h
(`rt_table` in `basic.c`), so it behaves the same. It loads at A200h like the
games.
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal - `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
Cavern; they load at A200h (`CALL 41472`). Cavern; they load at A200h (`CALL 41472`).
@@ -202,6 +211,7 @@ the configuration flash.
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. | | `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. | | `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings | | `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings |
| `basic/test-compile.py` | every program in `basic/examples` and in the other BASIC tests, plus programs for each statement and error, run interpreted and compiled in the emulator: the screen and the graphics must come out the same. It also times them. |
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. | | `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
| `bench/` | the processor alone with 64 KB of RAM, for timing | | `bench/` | the processor alone with 64 KB of RAM, for timing |
BIN
View File
Binary file not shown.
+164 -23
View File
@@ -239,10 +239,10 @@ static char svars[26][STRMAX];
struct array { u8 *p; u16 d1, d2; }; struct array { u8 *p; u16 d1, d2; };
static struct array arrays[52]; /* A()-Z(), then A$()-Z$() */ 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]; 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 struct forent fors[FORMAX];
static u8 nfor; static u8 nfor;
@@ -254,6 +254,8 @@ struct doent { u8 *tp, *ln; }; /* tp is the DO itself */
static struct doent dos[DOMAX]; static struct doent dos[DOMAX];
static u8 ndo; 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 *tp; /* text pointer */
static u8 *curln; /* line being run, 0 in direct mode */ static u8 *curln; /* line being run, 0 in direct mode */
static u8 *datap; /* next DATA item, 0 = search from the start */ 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_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_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_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[] = { static const char *const errmsg[] = {
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB", "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 NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
"FILE TOO BIG", "FILE ALREADY OPEN", "FILE NOT OPEN", "INPUT PAST END", "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", "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" "BREAK", "STOP"
}; };
@@ -597,6 +599,7 @@ static void clear_vars(void)
nfor = nsub = ndo = 0; nfor = nsub = ndo = 0;
datap = 0; datap = 0;
deg = 0; deg = 0;
data_base = rt_floor = 0;
} }
static void new_prog(void) static void new_prog(void)
@@ -663,16 +666,18 @@ static u16 get_lineno(void)
return n; return n;
} }
/* Numeric variable name: letter with an optional digit. Returns its index, or /* Numeric variable name: letter with an optional digit. Returns its index,
255 if the text is not a numeric variable (does not move tp then). */ 0 to 285 (so not a byte: X1 to Z9 once wrapped onto A to B9), or NOVAR if
static u8 var_name(void) the text is not a numeric variable (does not move tp then). */
#define NOVAR 0xFFFF
static u16 var_name(void)
{ {
u8 c = peekc(), d; u8 c = peekc(), d;
if (!is_alpha(c)) return 255; if (!is_alpha(c)) return NOVAR;
d = tp[1]; d = tp[1];
if (d == '$') return 255; if (d == '$') return NOVAR;
if (is_digit(d)) { if (is_digit(d)) {
if (tp[2] == '$') return 255; if (tp[2] == '$') return NOVAR;
tp += 2; tp += 2;
return (c - 'A') * 11 + 1 + d - '0'; 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); if ((i16)d1 < 0 || (i16)d2 < 0 || n > (a < 26 ? 6000 : 255)) error(E_SUBSCRIPT);
sz = n * (a < 26 ? sizeof(float) : STRMAX); sz = n * (a < 26 ? sizeof(float) : STRMAX);
np = arr_low - sz; 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; arr_low = np;
memset(np, 0, sz); memset(np, 0, sz);
ar->p = np; ar->p = np;
@@ -716,9 +721,10 @@ static void arr_alloc(u8 a, u16 d1, u16 d2)
ar->d2 = d2; ar->d2 = d2;
} }
static u8 *elem_at(u8 a, i16 i, i16 j, u8 two);
static u8 *array_elem(u8 a) static u8 *array_elem(u8 a)
{ {
struct array *ar = &arrays[a];
i16 i, j = 0; i16 i, j = 0;
u8 two; u8 two;
expect('('); expect('(');
@@ -726,6 +732,13 @@ static u8 *array_elem(u8 a)
two = accept(','); two = accept(',');
if (two) j = to_int(expr()); if (two) j = to_int(expr());
expect(')'); 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 (!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); 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); 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. */ /* A numeric variable or array element as an lvalue. */
static float *num_ref(void) static float *num_ref(void)
{ {
u8 v; u16 v;
if (is_alpha(peekc()) && tp[1] == '(') { if (is_alpha(peekc()) && tp[1] == '(') {
v = *tp - 'A'; v = *tp - 'A';
tp++; tp++;
return (float *)array_elem(v); return (float *)array_elem(v);
} }
v = var_name(); v = var_name();
if (v == 255) error(E_SYNTAX); if (v == NOVAR) error(E_SYNTAX);
return &vars[v]; 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; return (n < 0 ? s * p : s / p) + 0.0f;
} }
static float func2v(u8 t, float v);
static float func2(u8 t, float v) static float func2(u8 t, float v)
{ {
float w; float w;
i16 n = 0; i16 n = 0;
u8 i;
switch (t) { switch (t) {
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */ case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
expect(','); expect(',');
@@ -846,6 +860,14 @@ static float func2(u8 t, float v)
return v; return v;
} }
expect(')'); 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) { switch (t) {
case T_DEG: return v * 180.0f / PI_F; case T_DEG: return v * 180.0f / PI_F;
case T_RAD: return v * PI_F / 180.0f; case T_RAD: return v * PI_F / 180.0f;
@@ -878,6 +900,8 @@ static float func2(u8 t, float v)
return 0; return 0;
} }
static float func1(u8 t, float v);
static float func(u8 t) static float func(u8 t)
{ {
char s[STRMAX]; char s[STRMAX];
@@ -917,6 +941,12 @@ static float func(u8 t)
v = expr(); v = expr();
if (t >= T_ANGLE) return func2(t, v); if (t >= T_ANGLE) return func2(t, v);
expect(')'); expect(')');
return func1(t, v);
}
/* the one-argument functions SIN to INP, of v */
static float func1(u8 t, float v)
{
switch (t) { switch (t) {
case T_SIN: return sin_cos(v, 0); case T_SIN: return sin_cos(v, 0);
case T_COS: return sin_cos(v, 1); case T_COS: return sin_cos(v, 1);
@@ -1543,7 +1573,7 @@ static void next_data(void)
while (*datap == ' ') datap++; while (*datap == ' ') datap++;
if (*datap == ',') { datap++; return; } if (*datap == ',') { datap++; return; }
dataln += *dataln; dataln += *dataln;
} else dataln = arena; } else dataln = data_base ? data_base : arena;
for (; *dataln; dataln += *dataln) { for (; *dataln; dataln += *dataln) {
u8 *p = dataln + 3, q = 0; u8 *p = dataln + 3, q = 0;
for (; *p; p++) { for (; *p; p++) {
@@ -1741,8 +1771,9 @@ static void st_select(void)
static void st_for(void) static void st_for(void)
{ {
struct forent *f; struct forent *f;
u8 v = var_name(), i; u16 v = var_name();
if (v == 255) error(E_SYNTAX); u8 i;
if (v == NOVAR) error(E_SYNTAX);
expect('='); expect('=');
vars[v] = expr(); vars[v] = expr();
for (i = 0; i < nfor; i++) /* reusing a loop variable restarts it */ 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) static void st_next(void)
{ {
struct forent *f; struct forent *f;
u8 v; u16 v;
do { do {
v = var_name(); v = var_name();
if (!nfor) error(E_NEXT); if (!nfor) error(E_NEXT);
if (v != 255) { if (v != NOVAR) {
while (nfor && fors[nfor - 1].var != v) nfor--; while (nfor && fors[nfor - 1].var != v) nfor--;
if (!nfor) error(E_NEXT); if (!nfor) error(E_NEXT);
} }
@@ -1784,7 +1815,7 @@ static void st_next(void)
return; return;
} }
nfor--; nfor--;
} while (v != 255 && accept(',')); } while (v != NOVAR && accept(','));
} }
static void st_dim(void) static void st_dim(void)
@@ -1804,14 +1835,15 @@ static void st_dim(void)
static void st_def(void) static void st_def(void)
{ {
u8 f, v; u8 f;
u16 v;
expect(T_FN); expect(T_FN);
f = peekc(); f = peekc();
if (!is_alpha(f)) error(E_SYNTAX); if (!is_alpha(f)) error(E_SYNTAX);
tp++; tp++;
expect('('); expect('(');
v = var_name(); v = var_name();
if (v == 255) error(E_SYNTAX); if (v == NOVAR) error(E_SYNTAX);
expect(')'); expect(')');
expect('='); expect('=');
fns[f - 'A'].var = v; fns[f - 'A'].var = v;
@@ -1853,9 +1885,16 @@ static void run_prog(void)
static u8 gcolor = 15; static u8 gcolor = 15;
/* Up to n comma-separated integer arguments; returns how many were given. */ /* 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) static u8 int_args(i16 *a, u8 min, u8 n)
{ {
u8 i = 0; u8 i = 0;
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(',')); do a[i++] = to_int(expr()); while (i < n && accept(','));
if (i < min) error(E_SYNTAX); if (i < min) error(E_SYNTAX);
return i; return i;
@@ -2687,6 +2726,108 @@ static void execute(void)
running = 0; 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) int main(void)
{ {
u16 n; u16 n;
+2
View File
@@ -17,6 +17,8 @@ SECTIONS
*(.rodata .rodata.* .srodata .srodata.*) *(.rodata .rodata.* .srodata .srodata.*)
. = ALIGN(4); . = ALIGN(4);
} > ROM } > ROM
/* the jump table for compiled programs (rt_table in basic.c): fixed */
.rtab 0x9F00 : { KEEP(*(.rtab)) } > ROM
.arena (NOLOAD) : { KEEP(*(.arena)) } > RAM .arena (NOLOAD) : { KEEP(*(.arena)) } > RAM
.data : ALIGN(4) { .data : ALIGN(4) {
__data_start = .; __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 $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 \ ${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 -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 ${RV_PREFIX}nm -n out/basic.elf > out/basic.sym
python3 ../tools/bin2mem.py basic.bin out/basic-all.mem 20480 python3 ../tools/bin2mem.py basic.bin out/basic-all.mem 20480
head -n 16384 out/basic-all.mem > basic.mem 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) 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"CLS" + CR)
b.type(b'I=0: DO: I=I+1: LOOP UNTIL I=7: PRINT "DIRECT"; I' + 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()) 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()
+72
View File
@@ -1392,6 +1392,77 @@ file `PROG`, and goes back to BASIC. `BLOAD "PROG"` then loads it where it was
compiled for. It must be at 0A000h or above. That's how The Iron Keep compiled for. It must be at 0A000h or above. That's how The Iron Keep
(section 14) gets onto the board. (section 14) gets onto the board.
### Compiling a program
`tools/basc.py` compiles a BASIC program on the PC into machine code. The
compiled program does exactly what the program does when BASIC runs it, the
same results to the last digit and the same error messages with the same line
numbers, only faster:
| Each time round a loop | Interpreted | Compiled | |
|---|---|---|---|
| `FOR I = 1 TO N: NEXT I` | 6.4 µs | 0.98 µs | 7 times |
| `X = I * 1.5` | 31 µs | 1.2 µs | 26 times |
| `Y = SIN(I)` | 41 µs | 5.8 µs | 7 times |
| `J = I AND 7: A(J) = A(J) + I` | 91 µs | 6.1 µs | 15 times |
| `IF I > 0 THEN GOSUB 30` … `RETURN` | 39 µs | 2.1 µs | 18 times |
| `PLOT I / 5, 100, 7` | 57 µs | 5.8 µs | 10 times |
| `PRINT I;` | 36 µs | 29 µs | about the same |
Arithmetic, numeric variables and arrays, and every control statement (`GOTO`,
`GOSUB`, `ON`, `FOR`, `IF`, `DO`, `SELECT CASE`, `EXIT`, `END`) become machine
code, using the FPU directly, and the graphics statements work out their
numbers there too. Everything else (`PRINT`, `INPUT`, strings, files, sound,
`DATA` and `READ`, `DEF FN`, and functions such as `LEN` and `MOD`) is handed
to BASIC in the ROM as it stands, so it behaves exactly as it does
interpreted, at about the same speed. A program that spends its time
calculating, looping and drawing gains most; one that mostly prints gains
little. The graphics demo (`basic/examples/graphics-demo.bas`) runs 4.7 times
as fast.
```
tools/basc.py spiral.bas
```
writes `SPIRAL.ihx`, the program, and `SPIRAL.bas`, a two-line loader, next
to `spiral.bas` (`-o` puts them elsewhere, `--name` names them). It tells you
how much room the program takes. Then send both, and save the loader:
```
tools/send-hex.py SPIRAL.ihx --save SPIRALC --baud 3000000
```
```
tools/send-bas.py SPIRAL.bas --baud 3000000
```
and `SAVE "SPIRAL"`. From then on `RUN "SPIRAL"` loads the machine code
(the memory file `SPIRALC`) and runs it. It works like the games: it loads at
0xA200, in the program area, after the loader.
- **Variables** are BASIC's own: the program starts with them cleared, as
`RUN` does, and they are still there when it ends, for `PRINT`.
- **Errors** stop the program with BASIC's message and line number, as they
would interpreted. **Ctrl-C** is looked for at every 64th jump (`NEXT`,
`LOOP`, `GOTO`, `GOSUB`, `RETURN` or `ON`), so it stops any loop.
- **Room:** the program and its variables must fit between 0xA200 and
0xF0B7, about 20 KB, less what its arrays need. The graphics demo
compiles to 12 KB.
- **Not allowed:** `RUN`, `LIST`, `NEW`, `LOAD`, `SAVE` and `RENUM` make no
sense inside a compiled program, and `basc` says so.
- **Loops:** each `LOOP` goes back to the `DO` before it that it belongs to,
by position, where the interpreter keeps a list of `DO`s it has run; in a
program that jumps out of a `DO` loop with `GOTO` and back into another the
two can differ.
- **Which BASIC:** a compiled program calls BASIC through a table at 0x9F00
that later versions keep. If BASIC is too old or too new for it, the
program stops with `PROGRAM NEEDS ANOTHER BASIC`; compile it again.
`basc` needs Python 3 and a RISC-V GCC (the one that comes with Vivado will
do; the README says where).
`--fast` compiles for speed rather than size, though it makes little
difference. `--keep-c` keeps the C it makes on the way, for the curious.
When you're done, flip SW14 back down, and bring the getty back with When you're done, flip SW14 back down, and bring the getty back with
`sudo systemctl unmask --runtime serial-getty@ttyUSB1` (a reboot does it too). `sudo systemctl unmask --runtime serial-getty@ttyUSB1` (a reboot does it too).
Don't do that with SW14 up. Don't do that with SW14 up.
@@ -1422,6 +1493,7 @@ An error stops the program and reports the line, for example
| `LOOP WITHOUT DO` | `LOOP` or `EXIT DO` with no `DO` loop open | | `LOOP WITHOUT DO` | `LOOP` or `EXIT DO` with no `DO` loop open |
| `IF WITHOUT END IF` | A block `IF` (or its `ELSE`) with no `END IF` after it | | `IF WITHOUT END IF` | A block `IF` (or its `ELSE`) with no `END IF` after it |
| `SELECT WITHOUT END SELECT` | A `SELECT CASE` (or its `CASE`) with no `END SELECT` after it | | `SELECT WITHOUT END SELECT` | A `SELECT CASE` (or its `CASE`) with no `END SELECT` after it |
| `PROGRAM NEEDS ANOTHER BASIC` | A compiled program (section 12) made for a different version of BASIC |
| `GOSUB NESTED TOO DEEPLY` | More than 32 subroutines in progress | | `GOSUB NESTED TOO DEEPLY` | More than 32 subroutines in progress |
| `FILE NOT FOUND` | `LOAD`, `RUN` or `DEL` of a name not in `DIR` | | `FILE NOT FOUND` | `LOAD`, `RUN` or `DEL` of a name not in `DIR` |
| `BAD FILE NAME` | A name that is empty, longer than 8 or not just letters and digits | | `BAD FILE NAME` | A name that is empty, longer than 8 or not just letters and digits |
Binary file not shown.
Executable
+1510
View File
File diff suppressed because it is too large. Load diff