6 Commits
Author SHA1 Message Date
brad ArantandClaude Opus 5.5 addf0157fc Monitor: wide 132x64 screen showing everything at once
On the 132x64 screen the monitor shows PC and all integer registers, all
float registers (hex and decimal) with FCSR decoded, mstatus/mepc/mcause/
mtval/cycle/instret and the breakpoint, 24 rows of disassembly beside the
stack, and 14 rows of memory, with changed registers highlighted; the 80x32
layout is unchanged. R takes float register names. The CPU's trap CSRs
start at 0, so reading them before the first trap no longer hangs the
simulated bus. send-hex accepts the prompt on any row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:00:43 -08:00
brad ArantandClaude Opus 5.5 1e44ce4383 Manual: build the PDF with XeLaTeX in IBM Plex
docs/md2tex.py converts docs/basic-manual.md (still the only source) to
LaTeX via python-markdown's HTML; build-manual.sh typesets it with XeLaTeX
instead of printing HTML from Chrome. A title page, contents with page
numbers, section openers, running heads, Carbon-style tables and code
panels. Code blocks inside numbered lists now render as code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 19:41:27 -08:00
brad ArantandClaude Opus 5.5 2e668c708f 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>
2026-12-01 19:29:59 -08:00
brad ArantandClaude Opus 5.5 fa4752fd7a Assembler in GNU as syntax, objdump-style disassembly, UCASE$ and LCASE$
The monitor's assembler takes GNU as directives (.org, .equ, .byte, .half,
.word, .ascii, .string, .space, .align, .balign ...), # comments, 0x/0b
numbers, '\n' constants, . for the current address, << >> ^ ~, %hi/%lo and
the FP CSR short forms; the old ORG/DB/EQU/0FFH forms remain as aliases. The
disassembler prints lower case and 0x hex as objdump does. The monitor is
built with -msave-restore and puts .rodata first, to fit its ROM.
BASIC gains UCASE$ and LCASE$. Manual, README and tests updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 18:14:19 -08:00
brad ArantandClaude Opus 5.5 25c8286cf2 BASIC: scientific functions and OPTION ANGLE DEGREES
ASIN, ACOS, ANGLE, SEC, CSC, COT; SINH, COSH, TANH and their inverses;
LOG10, LOG2; IP, FP, CEIL, ROUND, TRUNCATE; MOD; MIN and MAX of any number of
values; FACT; PI, DEG, RAD; OPTION ANGLE DEGREES|RADIANS. Out-of-domain values
give ILLEGAL FUNCTION CALL. basic/test-math.py checks each against Python's
math (within 3 ulp); the manual and README cover them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:39:29 -08:00
brad ArantandClaude Opus 5.5 79aef8ed38 BASIC: DO … LOOP, EXIT, ELSE, block IF and SELECT CASE
DO WHILE/UNTIL … LOOP WHILE/UNTIL, EXIT DO and EXIT FOR; IF … THEN … ELSE on
one line; block IF … ELSEIF … ELSE … END IF; SELECT CASE with values, ranges
and IS comparisons, numeric or string. RENUM also fixes line numbers after
ELSE. basic/test-blocks.py checks them; the manual and README cover them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 16:09:41 -08:00
27 changed files with 16465 additions and 12374 deletions

No files matched your search

+33 -7
View File
@@ -14,9 +14,15 @@ RISC-V processor written from scratch in Verilog:
- **USB keyboard** on the board's USB host port, with a keys-held port for - **USB keyboard** on the board's USB host port, with a keys-held port for
games. games.
- **Files** saved in the board's configuration flash. - **Files** saved in the board's configuration flash.
- **Software**: Dartmouth-style BASIC with graphics, sound and files, a - **Software**: Dartmouth-style BASIC with graphics, sound and files,
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
functions (inverse and hyperbolic trigonometry in radians or degrees,
`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,
@@ -152,12 +158,27 @@ uses 49.5 of the XC7A35T's 50.
All in C (plus a little assembly), compiled with GCC: All in C (plus a little assembly), compiled with GCC:
- `basic/` — BASIC, with single-precision arithmetic on the FPU (`rv32imf`, - `basic/` — BASIC, with single-precision arithmetic on the FPU (`rv32imf`,
`ilp32f`), correctly rounded. `lib/` has the few C library functions it `ilp32f`), correctly rounded, and the structured statements of later
needs (small string functions, `setjmp`, and `sinf` … `sqrtf`), since Dartmouth BASIC and True BASIC (`DO … LOOP`, `EXIT`, block `IF`, `SELECT
CASE`). `lib/` has the few C library functions it
needs (small string functions, `setjmp`, and `sinf` … `sqrtf`, `asinf`,
`sinhf`, `atanhf`, `log10f`, an exact `fmodf` and the rest, each within 3
ulp), since
newlib's bring in its stdio and malloc. newlib's bring in its stdio and malloc.
- `monitor/` — the machine-code monitor: memory, registers (integer and - `monitor/` — the machine-code monitor: memory, registers (integer and
floating point), step, breakpoints, a RISC-V disassembler and a two-pass floating point), step, breakpoints; on the 132 × 64 screen it shows
assembler, Intel HEX in and out. everything at once (all the integer and float registers, the float values
in decimal, the CSRs, the disassembly, the stack and the memory, with the
registers a step changed highlighted), a RISC-V disassembler and a two-pass
assembler that both use GNU as syntax (`.org`, `.word`, `.string`,
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
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`).
@@ -192,8 +213,9 @@ the configuration flash.
| `scripts/fputest.sh` | `rtl/rv32_fpu.v` against `tools/f32.py`, an exact model of RISC-V's single precision (itself checked against the PC's FPU), on random vectors: every F instruction, every rounding mode, special values, subnormals and near-cancellations | | `scripts/fputest.sh` | `rtl/rv32_fpu.v` against `tools/f32.py`, an exact model of RISC-V's single precision (itself checked against the PC's FPU), on random vectors: every F instruction, every rounding mode, special values, subnormals and near-cancellations |
| `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 | | `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-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays and graphics modes, 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-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. |
| `bench/` | the processor alone with 64 KB of RAM, for timing | | `bench/` | the processor alone with 64 KB of RAM, for timing |
## Toolchain ## Toolchain
@@ -202,6 +224,10 @@ the configuration flash.
- RISC-V GCC: Vivado ships one for MicroBlaze V (`~/vivado/*/gnu/riscv/lin/bin/riscv64-unknown-elf-gcc`, - RISC-V GCC: Vivado ships one for MicroBlaze V (`~/vivado/*/gnu/riscv/lin/bin/riscv64-unknown-elf-gcc`,
GCC 13 with an `rv32im/ilp32` multilib), which `scripts/rv_env.sh` finds GCC 13 with an `rv32im/ilp32` multilib), which `scripts/rv_env.sh` finds
if there is no `riscv64-unknown-elf-gcc` on the PATH. `RV_PREFIX` overrides. if there is no `riscv64-unknown-elf-gcc` on the PATH. `RV_PREFIX` overrides.
- The manual: `docs/build-manual.sh` turns `docs/basic-manual.md` (the only
source) into the PDF with `docs/md2tex.py` and XeLaTeX, set in IBM Plex. It
needs `python3-markdown`, TeX Live with XeLaTeX and KOMA-Script, and
`fonts-ibm-plex`.
## License ## License
BIN
View File
Binary file not shown.
+520 -55
View File
@@ -180,6 +180,7 @@ static struct chan ch[NCHAN];
static struct chan *chan_arg(u8 mode); static struct chan *chan_arg(u8 mode);
static u8 chan_line(struct chan *c); static u8 chan_line(struct chan *c);
static u8 deg; /* OPTION ANGLE DEGREES */
static u8 ghi; /* 640x480 (SCREEN 1) */ static u8 ghi; /* 640x480 (SCREEN 1) */
static u16 gw = 320, gh = 240; /* the graphics' size */ static u16 gw = 320, gh = 240; /* the graphics' size */
/* follow the hardware's mode: a game run with CALL may have ended SCREEN 1 */ /* follow the hardware's mode: a game run with CALL may have ended SCREEN 1 */
@@ -193,8 +194,13 @@ enum {
T_BYE, T_CLS, T_COLOR, T_PLOT, T_LINE, T_RECT, T_FILL, T_CIRCLE, T_LOCATE, T_INK, T_SCREEN, T_BYE, T_CLS, T_COLOR, T_PLOT, T_LINE, T_RECT, T_FILL, T_CIRCLE, T_LOCATE, T_INK, T_SCREEN,
T_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, T_MONITOR, T_CALL, T_BSAVE, T_BLOAD, T_OUTPUT, T_APPEND, T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS, T_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, T_MONITOR, T_CALL, T_BSAVE, T_BLOAD, T_OUTPUT, T_APPEND, T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
T_SQR, T_INT, T_RND, T_SGN, T_FN, T_TAB, T_PEEK, T_INP, T_LEN, T_VAL, T_ASC, T_EOF, T_SQR, T_INT, T_RND, T_SGN, T_FN, T_TAB, T_PEEK, T_INP, T_LEN, T_VAL, T_ASC, T_EOF,
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM, T_LAST T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM,
T_DO, T_LOOP, T_WHILE, T_UNTIL, T_EXIT, T_ELSE, T_SELECT, T_CASE,
T_OPTION, T_PI, T_ANGLE, 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_ROUND, T_TRUNCATE, T_MOD, T_MIN, T_MAX, T_FACT, T_UCASES, T_LCASES, T_LAST
}; };
_Static_assert(T_LAST <= 0x100, "too many keywords for a byte");
static const char *const kw[] = { static const char *const kw[] = {
"LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR", "LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR",
@@ -203,7 +209,11 @@ static const char *const kw[] = {
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK", "SCREEN", "BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK", "SCREEN",
"SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "MONITOR", "CALL", "BSAVE", "BLOAD", "OUTPUT", "APPEND", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS", "SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "MONITOR", "CALL", "BSAVE", "BLOAD", "OUTPUT", "APPEND", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF", "SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM" "CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM",
"DO", "LOOP", "WHILE", "UNTIL", "EXIT", "ELSE", "SELECT", "CASE",
"OPTION", "PI", "ANGLE", "DEG", "RAD", "ASIN", "ACOS", "SEC", "CSC", "COT",
"SINH", "COSH", "TANH", "ASINH", "ACOSH", "ATANH", "LOG10", "LOG2", "CEIL",
"IP", "FP", "ROUND", "TRUNCATE", "MOD", "MIN", "MAX", "FACT", "UCASE$", "LCASE$"
}; };
/* ----------------------------------------------------------------- memory */ /* ----------------------------------------------------------------- memory */
@@ -212,6 +222,7 @@ static const char *const kw[] = {
#define NVARS (26 * 11) #define NVARS (26 * 11)
#define FORMAX 16 #define FORMAX 16
#define GOSUBMAX 32 #define GOSUBMAX 32
#define DOMAX 16
#ifdef __riscv #ifdef __riscv
/* at 8000h (basic.ld), where machine-code programs know to load into it */ /* at 8000h (basic.ld), where machine-code programs know to load into it */
@@ -228,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;
@@ -239,6 +250,12 @@ struct subent { u8 *tp, *ln; };
static struct subent subs[GOSUBMAX]; static struct subent subs[GOSUBMAX];
static u8 nsub; static u8 nsub;
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 *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 */
@@ -285,7 +302,8 @@ static void put_u16(u16 v)
enum { 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_BREAK, E_STOP 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_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",
@@ -294,6 +312,8 @@ static const char *const errmsg[] = {
"UNDEFINED FUNCTION", "FOR NESTED TOO DEEPLY", "GOSUB NESTED TOO DEEPLY", "UNDEFINED FUNCTION", "FOR NESTED TOO DEEPLY", "GOSUB NESTED TOO DEEPLY",
"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",
"IF WITHOUT END IF", "SELECT WITHOUT END SELECT", "PROGRAM NEEDS ANOTHER BASIC",
"BREAK", "STOP" "BREAK", "STOP"
}; };
@@ -576,8 +596,10 @@ static void clear_vars(void)
memset(arrays, 0, sizeof arrays); memset(arrays, 0, sizeof arrays);
memset(fns, 0, sizeof fns); memset(fns, 0, sizeof fns);
arr_low = arena + ARENA; arr_low = arena + ARENA;
nfor = nsub = 0; nfor = nsub = ndo = 0;
datap = 0; datap = 0;
deg = 0;
data_base = rt_floor = 0;
} }
static void new_prog(void) static void new_prog(void)
@@ -633,7 +655,7 @@ static void expect(u8 c)
static u8 at_end(void) static u8 at_end(void)
{ {
u8 c = peekc(); u8 c = peekc();
return c == 0 || c == ':'; return c == 0 || c == ':' || c == T_ELSE; /* ELSE ends IF ... THEN's statement */
} }
static u16 get_lineno(void) static u16 get_lineno(void)
@@ -644,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';
} }
@@ -665,7 +689,7 @@ static u8 is_str_start(void)
{ {
u8 c = peekc(); u8 c = peekc();
if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS || if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS ||
c == T_DATES) c == T_DATES || c == T_UCASES || c == T_LCASES)
return 1; return 1;
return is_alpha(c) && tp[1] == '$'; return is_alpha(c) && tp[1] == '$';
} }
@@ -689,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;
@@ -697,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('(');
@@ -707,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);
@@ -724,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];
} }
@@ -759,6 +791,117 @@ static float rnd(void)
return (float)((seed >> 8) & 0xFFFFFF) / 16777216.0f; return (float)((seed >> 8) & 0xFFFFFF) / 16777216.0f;
} }
/* ------------------------------------------------- scientific functions */
#define PI_F 3.14159265358979f
/* an angle from an inverse function, in the units OPTION ANGLE chose */
static float ang(float r) { return deg ? r * 180.0f / PI_F : r; }
/* sine (c = 0) or cosine (c = 1). In degrees, the angle is reduced exactly
to within 45 of a multiple of 90 first, so SIN(180) and COS(90) are 0. */
static float sin_cos(float v, u8 c)
{
float r, y;
int k;
if (!deg) return c ? cosf(v) : sinf(v);
r = fmodf(v, 360.0f);
k = (int)floorf(r / 90.0f + 0.5f);
r = (r - 90.0f * (float)k) * (PI_F / 180.0f);
k += c; /* cos x = sin(x + 90) */
y = k & 1 ? cosf(r) : sinf(r);
return (k & 2 ? -y : y) + 0.0f; /* + 0: no -0 */
}
/* x rounded (or truncated) to n decimal places, n < 0 to the left of the
point: INT(x * 10^n + .5) / 10^n, as in True BASIC */
static float round_to(float x, i16 n, u8 rnd)
{
float p = 1, s;
i16 i;
if (n < -38 || n > 38) error(E_FUNC);
for (i = n < 0 ? -n : n; i; i--) p *= 10.0f;
s = n < 0 ? x / p : x * p;
if (s >= 8388608.0f || s <= -8388608.0f) return x; /* nothing to round */
s = rnd ? floorf(s + 0.5f) : s < 0 ? -floorf(-s) : floorf(s);
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;
switch (t) {
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
expect(',');
w = expr();
expect(')');
if (v == 0 && w == 0) error(E_FUNC);
return ang(atan2f(w, v));
case T_ROUND: case T_TRUNCATE:
if (t == T_TRUNCATE || peekc() == ',') { expect(','); n = to_int(expr()); }
expect(')');
return round_to(v, n, t == T_ROUND);
case T_MOD: /* the sign of the divisor, like INT */
expect(',');
w = expr();
expect(')');
if (w == 0) error(E_DIV0);
v = fmodf(v, w);
if (v != 0 && (v < 0) != (w < 0)) v += w;
return v + 0.0f;
case T_MIN: case T_MAX:
while (accept(',')) {
w = expr();
if (t == T_MIN ? w < v : w > v) v = w;
}
expect(')');
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;
case T_ASIN: if (v < -1 || v > 1) error(E_FUNC); return ang(asinf(v));
case T_ACOS: if (v < -1 || v > 1) error(E_FUNC); return ang(acosf(v));
case T_SEC: w = sin_cos(v, 1); if (w == 0) error(E_FUNC); return 1 / w;
case T_CSC: w = sin_cos(v, 0); if (w == 0) error(E_FUNC); return 1 / w;
case T_COT:
if (!deg) { w = tanf(v); if (w == 0) error(E_FUNC); return 1 / w; }
w = sin_cos(v, 0);
if (w == 0) error(E_FUNC);
return sin_cos(v, 1) / w;
case T_SINH: return sinhf(v);
case T_COSH: return coshf(v);
case T_TANH: return tanhf(v);
case T_ASINH: return asinhf(v);
case T_ACOSH: if (v < 1) error(E_FUNC); return acoshf(v);
case T_ATANH: if (v <= -1 || v >= 1) error(E_FUNC); return atanhf(v);
case T_LOG10: if (v <= 0) error(E_FUNC); return log10f(v);
case T_LOG2: if (v <= 0) error(E_FUNC); return log2f(v);
case T_CEIL: return -floorf(-v) + 0.0f;
case T_IP: return (v < 0 ? -floorf(-v) : floorf(v)) + 0.0f;
case T_FP: return v - (v < 0 ? -floorf(-v) : floorf(v));
case T_FACT: /* to 34!: 35! is beyond single precision */
if (v < 0 || v > 34 || v != floorf(v)) error(E_FUNC);
for (w = 1, i = 2; i <= v; i++) w *= i; /* exact to 13! */
return w;
}
error(E_SYNTAX);
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];
@@ -796,12 +939,25 @@ static float func(u8 t)
return *p ? parse_num(&p) : 0; return *p ? parse_num(&p) : 0;
} }
v = expr(); v = expr();
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 sinf(v); case T_SIN: return sin_cos(v, 0);
case T_COS: return cosf(v); case T_COS: return sin_cos(v, 1);
case T_TAN: return tanf(v); case T_TAN:
case T_ATN: return atanf(v); if (deg) {
float c = sin_cos(v, 1);
if (c == 0) error(E_FUNC);
return sin_cos(v, 0) / c;
}
return tanf(v);
case T_ATN: return ang(atanf(v));
case T_EXP: return expf(v); case T_EXP: return expf(v);
case T_LOG: if (v <= 0) error(E_FUNC); return logf(v); case T_LOG: if (v <= 0) error(E_FUNC); return logf(v);
case T_ABS: return v < 0 ? -v : v; case T_ABS: return v < 0 ? -v : v;
@@ -852,6 +1008,8 @@ static float primary(void)
if (is_str_start()) error(E_TYPE); if (is_str_start()) error(E_TYPE);
if (c == T_FN) { tp++; return call_fn(); } if (c == T_FN) { tp++; return call_fn(); }
if (c >= T_SIN && c <= T_POINT && c != T_FN && c != T_TAB) { tp++; return func(c); } if (c >= T_SIN && c <= T_POINT && c != T_FN && c != T_TAB) { tp++; return func(c); }
if (c == T_PI) { tp++; return PI_F; }
if (c >= T_ANGLE && c <= T_FACT) { tp++; return func(c); }
if (is_alpha(c)) return *num_ref(); if (is_alpha(c)) return *num_ref();
error(E_SYNTAX); error(E_SYNTAX);
return 0; return 0;
@@ -979,6 +1137,14 @@ static void str_prim(char *out)
out[0] = to_int(expr()); out[0] = to_int(expr());
out[1] = 0; out[1] = 0;
break; break;
case T_UCASES: /* only A-Z and a-z change */
case T_LCASES: {
char *p;
sexpr(out);
for (p = out; *p; p++)
if (c == T_UCASES ? *p >= 'a' && *p <= 'z' : *p >= 'A' && *p <= 'Z') *p ^= 32;
break;
}
case T_STRS: { case T_STRS: {
float v = expr(); float v = expr();
out[0] = ' '; out[0] = ' ';
@@ -1407,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++) {
@@ -1427,11 +1593,187 @@ static void st_read(void)
} while (accept(',')); } while (accept(','));
} }
/* ---------------------------------------------------- block structures */
/* Move tp to the start of the next statement, on to the next line if need
be. Returns 0 at the end of the program (or of a direct statement). */
static u8 next_stmt(void)
{
skip_statement();
if (*tp) { tp++; return 1; }
if (!curln || !*(curln + *curln)) return 0;
curln += *curln;
tp = curln + 3;
return 1;
}
/* Does the statement at p end its line with THEN (a block IF)? */
static u8 ends_then(u8 *p)
{
u8 q = 0, last = 0;
for (; *p; p++) {
if (*p == '"') q = !q;
else if (*p != ' ') last = q ? 0 : *p;
}
return last == T_THEN;
}
/* Skip to just past the NEXT that closes the FOR we are in, and its
variables. */
static void find_next(void)
{
u8 depth = 0, c;
for (;;) {
if (!next_stmt()) error(E_NONEXT);
c = peekc();
if (c == T_FOR) depth++;
else if (c == T_NEXT && !depth--) {
tp++;
while (!at_end()) { var_name(); if (!accept(',')) break; }
return;
}
}
}
/* Skip to just past the LOOP that closes the DO we are in, and its
condition. */
static void find_loop(void)
{
u8 depth = 0, c;
for (;;) {
if (!next_stmt()) error(E_NOLOOP);
c = peekc();
if (c == T_DO) depth++;
else if (c == T_LOOP && !depth--) { tp++; skip_statement(); return; }
}
}
/* Skip to just past the END IF or END SELECT (k is T_IF or T_SELECT) that
closes the block we are in. With els, a block IF's condition was false:
stop instead at its ELSE, or at an ELSEIF whose condition is true. */
static void find_end(u8 k, u8 els)
{
u8 depth = 0, c;
for (;;) {
if (!next_stmt()) error(k == T_IF ? E_ENDIF : E_ENDSEL);
c = peekc();
if (c == k && (k == T_SELECT || ends_then(tp))) depth++;
else if (c == T_END) {
tp++;
if (accept(k) && !depth--) break;
} else if (c == T_ELSE && els && !depth) {
tp++;
if (!accept(T_IF)) break; /* ELSE */
c = expr() != 0; /* ELSEIF */
expect(T_THEN);
if (c) break;
}
}
jumped = 1; /* run on from here */
}
static void st_do(void)
{
u8 *at = tp - 1, i, go = 1;
for (i = 0; i < ndo; i++) /* back at a DO left by GOTO: restart it */
if (dos[i].tp == at) { ndo = i; break; }
if (accept(T_WHILE)) go = expr() != 0;
else if (accept(T_UNTIL)) go = expr() == 0;
if (!go) { find_loop(); return; }
if (ndo >= DOMAX) error(E_DODEEP);
dos[ndo].tp = at;
dos[ndo].ln = curln;
ndo++;
}
static void st_loop(void)
{
u8 again = 1;
if (!ndo) error(E_NODO);
if (accept(T_WHILE)) again = expr() != 0;
else if (accept(T_UNTIL)) again = expr() == 0;
ndo--;
if (again) { /* back to the DO, which tests its condition */
tp = dos[ndo].tp;
curln = dos[ndo].ln;
jumped = 1;
}
}
static void st_exit(void)
{
if (accept(T_DO)) {
if (!ndo) error(E_NODO);
ndo--;
find_loop();
} else if (accept(T_FOR)) {
if (!nfor) error(E_NEXT);
nfor--;
find_next();
} else error(E_SYNTAX);
}
/* x compared with the next value: -1, 0 or 1 */
static i16 case_cmp(u8 str, float x, const char *xs)
{
if (str) {
char a[STRMAX];
i16 c;
if (!is_str_start()) error(E_TYPE);
sexpr(a);
c = strcmp(xs, a);
return c < 0 ? -1 : c > 0;
} else {
float a = expr();
return x < a ? -1 : x > a;
}
}
/* One item of a CASE list: value, low TO high, or IS relation value. */
static u8 case_item(u8 str, float x, const char *xs)
{
u8 op;
i16 c;
if (peekc() == 'I' && tp[1] == 'S') tp += 2;
op = relop();
c = case_cmp(str, x, xs);
if (op) return (c < 0 && (op & 1)) || (c == 0 && (op & 2)) || (c > 0 && (op & 4));
if (!accept(T_TO)) return c == 0;
return (c >= 0) & (case_cmp(str, x, xs) <= 0);
}
/* SELECT CASE: find the first CASE that matches and run on from it. */
static void st_select(void)
{
char s[STRMAX];
float x = 0;
u8 str = 0, depth = 0, c, m;
expect(T_CASE);
if (is_str_start()) { sexpr(s); str = 1; }
else x = expr();
for (;;) {
if (!next_stmt()) error(E_ENDSEL);
c = peekc();
if (c == T_SELECT) depth++;
else if (c == T_END) {
tp++;
if (accept(T_SELECT) && !depth--) break;
} else if (c == T_CASE && !depth) {
tp++;
if (accept(T_ELSE)) break;
m = 0;
do m |= case_item(str, x, s); while (accept(','));
if (m) break;
}
}
jumped = 1;
}
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 */
@@ -1447,38 +1789,19 @@ static void st_for(void)
nfor++; nfor++;
/* skip the body when the loop runs zero times */ /* skip the body when the loop runs zero times */
if ((f->step >= 0 && vars[v] > f->limit) || (f->step < 0 && vars[v] < f->limit)) { if ((f->step >= 0 && vars[v] > f->limit) || (f->step < 0 && vars[v] < f->limit)) {
u8 depth = 0;
nfor--; nfor--;
for (;;) { find_next();
u8 c;
skip_statement();
if (!*tp) {
if (!curln || !*(curln + *curln)) error(E_FOR);
curln += *curln;
tp = curln + 3;
} else tp++;
c = peekc();
if (c == T_FOR) depth++;
else if (c == T_NEXT) {
if (!depth) {
tp++;
while (!at_end()) { var_name(); if (!accept(',')) break; }
return;
}
depth--;
}
}
} }
} }
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);
} }
@@ -1492,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)
@@ -1512,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;
@@ -1561,10 +1885,17 @@ 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;
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); if (i < min) error(E_SYNTAX);
return i; return i;
} }
@@ -2191,7 +2522,7 @@ static void st_renum(void)
rn_put(0); rn_put(n); rn_put(n >> 8); rn_put(0); rn_put(n); rn_put(n >> 8);
for (q = p + 3; (t = *q++) != 0; ) { for (q = p + 3; (t = *q++) != 0; ) {
rn_put(t); rn_put(t);
if ((t < T_THEN || t > T_GOSUB) && t != T_RUN) continue; /* THEN GOTO GOSUB */ if ((t < T_THEN || t > T_GOSUB) && t != T_RUN && t != T_ELSE) continue; /* THEN GOTO GOSUB ELSE */
for (want = 1;;) { for (want = 1;;) {
while (*q == ' ') rn_put(*q++); while (*q == ' ') rn_put(*q++);
if (want && is_digit(*q)) { if (want && is_digit(*q)) {
@@ -2229,8 +2560,22 @@ static void statement(void);
static void st_if(void) static void st_if(void)
{ {
float c = expr(); float c = expr();
u8 depth = 0, q = 0;
if (!accept(T_THEN) && peekc() != T_GOTO) error(E_SYNTAX); if (!accept(T_THEN) && peekc() != T_GOTO) error(E_SYNTAX);
if (!c) { skip_line(); return; } if (!peekc()) { /* block IF: THEN ends the line */
if (!c && curln) find_end(T_IF, 1);
return;
}
if (!c) { /* on to this IF's ELSE, if it has one */
for (;; tp++) {
if (!*tp) return;
if (*tp == '"') q = !q;
else if (q) continue;
else if (*tp == T_IF) depth++;
else if (*tp == T_ELSE && !depth--) break;
}
tp++;
}
if (is_digit(peekc())) goto_line(get_lineno()); if (is_digit(peekc())) goto_line(get_lineno());
else statement(); else statement();
} }
@@ -2259,7 +2604,24 @@ static void statement(void)
case T_NEXT: st_next(); break; case T_NEXT: st_next(); break;
case T_DIM: st_dim(); break; case T_DIM: st_dim(); break;
case T_DEF: st_def(); break; case T_DEF: st_def(); break;
case T_END: close_all(); running = 0; break; case T_END:
if (accept(T_IF) || accept(T_SELECT)) break;
close_all();
running = 0;
break;
case T_DO: st_do(); break;
case T_OPTION: /* OPTION ANGLE DEGREES | RADIANS */
expect(T_ANGLE);
if (accept(T_DEG)) deg = 1;
else if (accept(T_RAD)) deg = 0;
else error(E_SYNTAX);
while (is_alpha(*tp)) tp++; /* the rest of the word */
break;
case T_LOOP: st_loop(); break;
case T_EXIT: st_exit(); break;
case T_SELECT: st_select(); break;
case T_ELSE: find_end(T_IF, 0); break; /* end of the THEN part */
case T_CASE: find_end(T_SELECT, 0); break; /* end of a CASE's part */
case T_STOP: error(E_STOP); break; case T_STOP: error(E_STOP); break;
case T_REM: skip_line(); break; case T_REM: skip_line(); break;
case T_DATA: skip_line(); break; case T_DATA: skip_line(); break;
@@ -2354,6 +2716,7 @@ static void execute(void)
if (!running) break; if (!running) break;
if (jumped) continue; if (jumped) continue;
if (accept(':')) continue; if (accept(':')) continue;
if (peekc() == T_ELSE) skip_line(); /* IF ... THEN's statement ran */
if (peekc()) error(E_SYNTAX); if (peekc()) error(E_SYNTAX);
if (!curln) break; /* end of a direct statement */ if (!curln) break; /* end of a direct statement */
curln += *curln; curln += *curln;
@@ -2363,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;
@@ -2377,7 +2842,7 @@ int main(void)
newline(); newline();
if (setjmp(errjmp)) { if (setjmp(errjmp)) {
running = 0; running = 0;
nfor = nsub = 0; nfor = nsub = ndo = 0;
curln = 0; curln = 0;
} }
for (;;) { for (;;) {
+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 = .;
+5098 -5098
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
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env python3
"""Try BASIC's block structures (DO ... LOOP, EXIT, IF ... ELSE ... END IF,
SELECT CASE) in tools/rv32emu.py, with the screen kept by pyte.
python3 test-blocks.py
"""
import importlib.util
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
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
def main():
b = te.Basic()
errors = 0
def check(what, ok, out=""):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok:
print(out)
errors += not ok
def screen():
return "\n".join(l.rstrip() for l in b.screen_text().display)
def run(prog):
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for line in prog.strip().splitlines():
b.type(line.encode() + CR)
b.type(b"RUN" + CR)
return screen().split("RUN")[-1]
b.type(b"")
out = run('''
10 I = 0
20 DO WHILE I < 5
30 PRINT I;
40 I = I + 1
50 LOOP
60 PRINT "/";
70 DO
80 I = I - 1: PRINT I;
90 LOOP UNTIL I = 0
100 PRINT "/";
110 DO UNTIL 1: PRINT "NEVER": LOOP
120 DO WHILE 0
130 PRINT "NEVER"
140 LOOP WHILE 1
150 PRINT "END"
''')
check("DO WHILE, LOOP UNTIL, and loops that run no times",
"0 1 2 3 4 / 4 3 2 1 0 /END" in out, out)
out = run('''
10 FOR I = 1 TO 3
20 J = 0
30 DO
40 J = J + 1
50 IF J > I THEN EXIT DO
60 PRINT J;
70 LOOP
80 PRINT ",";
90 NEXT I
100 FOR K = 1 TO 100
110 IF K = 4 THEN EXIT FOR
120 NEXT K
130 PRINT K
''')
check("nested DO in FOR, EXIT DO, EXIT FOR", "1 , 1 2 , 1 2 3 , 4" in out, out)
out = run('''
10 FOR I = 1 TO 4
20 IF I = 1 THEN
30 PRINT "ONE";
40 ELSEIF I = 2 THEN
50 PRINT "TWO";
60 IF I > 0 THEN
70 PRINT "+";
80 ELSE
90 PRINT "NEVER";
100 END IF
110 ELSE IF I = 3 THEN
120 PRINT "THREE";
130 ELSE
140 PRINT "MANY";
150 END IF
160 PRINT ",";
170 NEXT I
''')
check("block IF, ELSEIF, ELSE IF, ELSE, nested, END IF",
"ONE,TWO+,THREE,MANY," in out, out)
out = run('''
10 FOR I = 1 TO 3
20 IF I = 2 THEN PRINT "B"; ELSE PRINT "A";
30 IF I = 1 THEN 50 ELSE PRINT "-";
40 GOTO 60
50 PRINT "*";
60 NEXT I
70 IF 1 THEN IF 0 THEN PRINT "X" ELSE PRINT "Y" ELSE PRINT "Z"
80 IF 0 THEN IF 1 THEN PRINT "X" ELSE PRINT "Y" ELSE PRINT "Z"
90 IF 0 THEN PRINT "ELSE" ELSE PRINT "ELSE OK"
''')
check("one-line IF ... ELSE, with line numbers and nesting",
"A*B-A-Y\nZ\nELSE OK" in out, out)
out = run('''
10 FOR I = 0 TO 7
20 SELECT CASE I * 2
30 CASE 0
40 PRINT "ZERO";
50 CASE 2, 4
60 PRINT "SMALL";
70 CASE 6 TO 9
80 PRINT "MID";
90 CASE IS >= 12
100 PRINT "BIG";
110 CASE ELSE
120 PRINT "OTHER";
130 END SELECT
140 PRINT ",";
150 NEXT I
160 A$ = "PEAR"
170 SELECT CASE A$
180 CASE "APPLE": PRINT "A"
190 CASE "B" TO "Q": PRINT "IN RANGE"
200 END SELECT
210 SELECT CASE 5: CASE 1: PRINT "NO": END SELECT
220 PRINT "DONE"
''')
check("SELECT CASE numbers: values, TO, IS, ELSE",
"ZERO,SMALL,SMALL,MID,MID,OTHER,BIG,BIG," in out, out)
check("SELECT CASE strings, no CASE matching", "IN RANGE\nDONE" in out, out)
out = run('''
10 X = 0
20 DO
30 X = X + 1: PRINT X;
40 IF X < 30 THEN GOTO 20
50 IF X > 40 THEN EXIT DO
60 LOOP
70 PRINT "END"
''')
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())
out = run('10 LOOP')
check("LOOP without DO", "LOOP WITHOUT DO" in out, out)
out = run('10 DO WHILE 0\n20 PRINT')
check("DO without LOOP", "DO WITHOUT LOOP" in out, out)
out = run('10 IF 0 THEN\n20 PRINT')
check("IF without END IF", "IF WITHOUT END IF" in out, out)
out = run('10 SELECT CASE 1\n20 PRINT')
check("SELECT without END SELECT", "SELECT WITHOUT END SELECT" in out, out)
out = run('10 FOR I = 2 TO 1\n20 PRINT')
check("FOR without NEXT", "FOR WITHOUT NEXT" in out, out)
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for l in (b"10 IF A THEN 30 ELSE 40", b"30 END IF", b"40 END"):
b.type(l + CR)
b.type(b"RENUM 100" + CR)
b.type(b"LIST" + CR)
check("RENUM follows ELSE's line number", "100 IF A THEN 110 ELSE 120" in screen(), screen())
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()
+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()
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env python3
"""Check BASIC's scientific functions in tools/rv32emu.py.
python3 test-math.py [count]
First the maths library itself: each function in basic.bin (lib/mathf.c) is
called directly in the emulator, on random values across its range and on
the awkward ones, and its result compared bit for bit with Python's math
module (in double precision, so as good as exact here), in units in the last
place of single precision. Then BASIC: the functions as statements see them,
OPTION ANGLE DEGREES, and the errors outside each function's domain.
"""
import importlib.util
import math
import os
import random
import struct
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
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
RET = 0x12000 # the machine-code area: a return address never run
STACK = 0x12FF0
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def bits(x):
return struct.unpack("<I", struct.pack("<f", x))[0]
def unbits(i):
return struct.unpack("<f", struct.pack("<I", i & 0xFFFFFFFF))[0]
def ulp(x):
"""Single precision's unit in the last place at x."""
x = abs(x)
if x < 2.0 ** -126:
return 2.0 ** -149
return 2.0 ** (math.floor(math.log2(x)) - 23)
def ulps(got, want):
if math.isinf(want):
return 0 if got == want else math.inf
w = f32(want) if abs(want) < 3.4e38 else want
if math.isinf(w):
return 0 if math.isinf(got) and (got > 0) == (want > 0) else math.inf
return abs(got - want) / ulp(want)
def symbols():
s = {}
for line in open(os.path.join(HERE, "out", "basic.sym")):
a, t, n = line.split()
s[n] = int(a, 16)
return s
class Caller:
"""Call a float function in basic.bin, ilp32f: arguments in fa0, fa1."""
def __init__(self, board):
self.b = board
self.sym = symbols()
def __call__(self, name, *args):
b = self.b
x, f, pc = b.x[:], b.f[:], b.pc
for i, a in enumerate(args):
b.f[10 + i] = bits(a)
b.x[1] = RET
b.x[2] = STACK
b.pc = self.sym[name]
n = 0
while b.pc != RET:
b.step()
n += 1
if n > 100000:
raise RuntimeError(name + " did not return")
r = unbits(b.f[10])
b.x[:], b.f[:], b.pc = x, f, pc
return r
def logspace(rng, lo, hi, n, signed=False):
"""n random floats with magnitudes spread evenly in log between lo and hi"""
out = []
for _ in range(n):
v = f32(math.exp(rng.uniform(math.log(lo), math.log(hi))))
out.append(-v if signed and rng.random() < 0.5 else v)
return out
def main():
count = int(sys.argv[1]) if len(sys.argv) > 1 else 1500
rng = random.Random(1)
b = te.Basic()
b.type(b"")
call = Caller(b)
errors = 0
def check(what, ok, out=""):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok and out:
print(out)
errors += not ok
def uni(lo, hi, n):
return [f32(rng.uniform(lo, hi)) for _ in range(n)]
# name, reference, inputs, the most ulps allowed
n = count
tests = [
("asinf", math.asin, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True) + [1, -1, 0.5, 1 - 2 ** -24], 3),
("acosf", math.acos, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True) + [1, -1, 0, 1 - 2 ** -24, -1 + 2 ** -24], 3),
("sinhf", math.sinh, uni(-12, 12, n) + logspace(rng, 1e-30, 89, n, True) + [1, -1, 10, 89.4], 3),
("coshf", math.cosh, uni(-12, 12, n) + logspace(rng, 1e-30, 89, n, True) + [0, 1, 10, 89.4], 3),
("tanhf", math.tanh, uni(-12, 12, n) + logspace(rng, 1e-30, 30, n, True) + [0, 1, 10, -10], 3),
("asinhf", math.asinh, uni(-10, 10, n) + logspace(rng, 1e-30, 3e38, n, True) + [0, 1, 1e9, 2e9], 3),
("acoshf", math.acosh, [1 + abs(v) for v in uni(0, 10, n)] + logspace(rng, 1, 3e38, n)
+ [1 + 2 ** -23 * k for k in range(1, 40)] + [1, 1e9, 2e9], 3),
("atanhf", math.atanh, uni(-1, 1, n) + logspace(rng, 1e-30, 1, n, True)
+ [1 - 2 ** -24 * k for k in range(1, 40)] + [0, 0.5], 3),
("log1pf", math.log1p, logspace(rng, 1e-30, 1e30, n) + uni(-0.999, 1, n), 3),
("log10f", math.log10, logspace(rng, 1e-45, 3e38, n) + uni(0.5, 2, n) + [10.0 ** k for k in range(-37, 39)], 2),
("log2f", math.log2, logspace(rng, 1e-45, 3e38, n) + uni(0.5, 2, n), 2),
]
for name, ref, xs, most in tests:
worst, at = 0, None
for x in xs:
x = f32(x)
try:
want = ref(x)
except (ValueError, OverflowError):
want = math.inf if name in ("sinhf", "coshf") else None
if name == "sinhf":
want = math.copysign(math.inf, x)
if want is None:
continue
e = ulps(call(name, x), want)
if e > worst:
worst, at = e, x
check(f"{name}: {len(xs)} values, worst {worst:.2f} ulp (at {at!r}), "
f"allowed {most}", worst <= most)
# exact cases
check("log2f exact at powers of 2", all(call("log2f", 2.0 ** k) == k for k in range(-149, 128)))
check("asinf(1), acosf(-1), acosf(1) exact",
call("asinf", 1.0) == f32(math.pi / 2) and call("acosf", -1.0) == f32(math.pi)
and call("acosf", 1.0) == 0)
# atan2f
worst, at = 0, None
for _ in range(4 * n):
y, x = f32(rng.uniform(-10, 10)), f32(rng.uniform(-10, 10))
if rng.random() < 0.3:
y = f32(y * 10 ** rng.uniform(-20, 20))
e = ulps(call("atan2f", y, x), math.atan2(y, x))
if e > worst:
worst, at = e, (y, x)
axes = all(call("atan2f", y, x) == f32(math.atan2(y, x))
for y, x in [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1)])
check(f"atan2f: {4 * n} values, worst {worst:.2f} ulp (at {at!r}), allowed 3; axes exact",
worst <= 3 and axes)
# fmodf must be exact
bad = []
for _ in range(4 * n):
x = f32(rng.choice([-1, 1]) * 10 ** rng.uniform(-10, 30))
y = f32(rng.choice([-1, 1]) * 10 ** rng.uniform(-10, 10))
if call("fmodf", x, y) != f32(math.fmod(x, y)):
bad.append((x, y))
check(f"fmodf exact on {4 * n} values", not bad, repr(bad[:5]))
# ---------------------------------------------------------------- BASIC
def screen():
return "\n".join(l.rstrip() for l in b.screen_text().display)
def run(prog):
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
for line in prog.strip().splitlines():
b.type(line.encode() + CR)
b.type(b"RUN" + CR)
return screen().split("RUN")[-1]
def rows(out):
return [l.strip() for l in out.splitlines() if l.strip() and l.strip() != "READY"]
out = run('''
10 PRINT PI; DEG(PI); RAD(180); ATN(1) * 4
20 PRINT ASIN(.5); ACOS(-1); ANGLE(-1, 0); ANGLE(0, -2)
30 PRINT SINH(1); COSH(1); TANH(.5); ASINH(1); ACOSH(2); ATANH(.5)
40 PRINT LOG10(1000); LOG2(1024); LOG10(2); LOG(EXP(2))
50 PRINT SEC(0); CSC(PI / 2); COT(PI / 4)
''')
got = rows(out)
want = ["3.14159 180 3.14159 3.14159",
".523599 3.14159 3.14159 -1.5708",
"1.1752 1.54308 .462117 .881374 1.31696 .549306",
"3 10 .30103 2",
"1 1 1"]
check("PI, DEG, RAD, the inverse trig functions, ANGLE", got[:2] == want[:2], out)
check("hyperbolic functions and their inverses", got[2:3] == want[2:3], out)
check("LOG10, LOG2", got[3:4] == want[3:4], out)
check("SEC, CSC, COT", got[4:5] == want[4:5], out)
out = run('''
10 PRINT ROUND(2.567, 2); ROUND(2.5); ROUND(-2.5); ROUND(1250, -2); ROUND(-1.25, 1)
20 PRINT TRUNCATE(2.567, 1); TRUNCATE(-2.567, 1); TRUNCATE(1299, -2)
30 PRINT IP(3.7); IP(-3.7); FP(3.75); FP(-3.75); CEIL(3.2); CEIL(-3.2); CEIL(4)
40 PRINT MOD(7, 3); MOD(-7, 3); MOD(7, -3); MOD(-7, -3); MOD(7.5, 2); MOD(6, 3)
50 PRINT MIN(3, 1, 2); MAX(3, 1, 2); MIN(-1, -5); MAX(4)
60 PRINT FACT(0); FACT(5); FACT(10); FACT(13); FACT(34)
''')
got = rows(out)
want = ["2.57 3 -2 1300 -1.2",
"2.5 -2.5 1200",
"3 -3 .75 -.75 4 -3 4",
"1 2 -2 -1 1.5 0",
"1 3 -5 4",
"1 120 3.6288E+06 6.22702E+09 2.95233E+38"]
for w, g, what in zip(want, got + [""] * 6,
["ROUND", "TRUNCATE", "IP, FP, CEIL", "MOD", "MIN, MAX", "FACT"]):
check(what, g == w, f"got {g!r}, want {w!r}")
out = run('''
10 OPTION ANGLE DEGREES
20 PRINT SIN(30); SIN(180); COS(90); COS(60); TAN(45); SIN(-90); COS(720)
30 PRINT ASIN(1); ACOS(0); ATN(1); ANGLE(-1, -1); SEC(60); COT(45); CSC(30)
40 PRINT SIN(1E6); COS(-123.5)
50 OPTION ANGLE RADIANS
60 PRINT SIN(PI / 6); ATN(1)
''')
got = rows(out)
check("OPTION ANGLE DEGREES: exact at multiples of 30 and 45",
got[:2] == [".5 0 0 .5 1 -1 1", "90 90 45 -135 2 1 2"], out)
try:
big = [float(v) for v in got[2].split()]
except (IndexError, ValueError):
big = []
check("degrees: large and negative angles",
len(big) == 2 and abs(big[0] - math.sin(math.radians(1e6))) < 2e-6
and abs(big[1] - math.cos(math.radians(-123.5))) < 2e-6, out)
check("OPTION ANGLE RADIANS goes back", got[3:4] == [".5 .785398"], out)
out = run('10 PRINT SIN(90)')
check("RUN starts in radians again", rows(out) == [".893997"], out)
for expr, msg in [("ASIN(1.5)", "ILLEGAL"), ("ACOS(-2)", "ILLEGAL"), ("ACOSH(.5)", "ILLEGAL"),
("ATANH(1)", "ILLEGAL"), ("ATANH(-1)", "ILLEGAL"), ("LOG10(0)", "ILLEGAL"),
("LOG2(-1)", "ILLEGAL"), ("FACT(-1)", "ILLEGAL"), ("FACT(2.5)", "ILLEGAL"),
("FACT(35)", "ILLEGAL"), ("ANGLE(0, 0)", "ILLEGAL"), ("MOD(1, 0)", "DIVISION BY ZERO"),
("ROUND(1, 39)", "ILLEGAL"), ("CSC(0)", "ILLEGAL"), ("COT(0)", "ILLEGAL")]:
out = run(f"10 PRINT {expr}")
check(f"{expr} is an error", msg in out, out)
out = run("10 OPTION ANGLE DEGREES: PRINT TAN(90)")
check("TAN(90) in degrees is an error", "ILLEGAL" in out, out)
out = run("10 OPTION ANGLE DEGREES: PRINT SEC(90)")
check("SEC(90) in degrees is an error", "ILLEGAL" in out, out)
out = run("10 OPTION ANGLE GRADS")
check("OPTION ANGLE wants DEGREES or RADIANS", "SYNTAX" in out, out)
b.type(b"NEW" + CR)
b.type(b"CLS" + CR)
b.type(b"10 OPTION ANGLE DEGREES: X = TRUNCATE(PI, 3)" + CR)
b.type(b"LIST" + CR)
check("LIST spells the new words as typed",
"10 OPTION ANGLE DEGREES: X = TRUNCATE(PI, 3)" in screen(), screen())
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()
+18 -1
View File
@@ -18,9 +18,11 @@ def main():
b = te.Basic() b = te.Basic()
errors = 0 errors = 0
def check(what, ok): def check(what, ok, out=""):
nonlocal errors nonlocal errors
print(("PASS " if ok else "FAIL ") + what) print(("PASS " if ok else "FAIL ") + what)
if not ok and out:
print(out)
errors += not ok errors += not ok
def run(prog): def run(prog):
@@ -64,6 +66,21 @@ def main():
b.type(b"A, B" + CR) b.type(b"A, B" + CR)
check("LINE INPUT into an element", "<A, B>" in "\n".join(l.rstrip() for l in b.screen_text().display)) check("LINE INPUT into an element", "<A, B>" in "\n".join(l.rstrip() for l in b.screen_text().display))
out = run('''
10 A$ = "Hello, World! 123"
20 PRINT UCASE$(A$); "|"; LCASE$(A$); "|"; LCASE$(UCASE$("mIxEd"))
30 B$ = CHR$(64) + CHR$(91) + CHR$(96) + CHR$(123) + CHR$(224)
40 PRINT (UCASE$(B$) = B$); (LCASE$(B$) = B$); LEN(UCASE$("")); ASC(LCASE$("Z"))
50 DIM N$(1): N$(1) = "abc": PRINT UCASE$(N$(1) + "d")
''')
check("UCASE$ and LCASE$", "HELLO, WORLD! 123|hello, world! 123|mixed" in out, out)
check("only A-Z and a-z change", "-1 -1 0 122" in out, out)
check("UCASE$ of an expression", "ABCD" in out, out)
b.type(b"LIST 20" + CR)
check("LIST spells UCASE$ and LCASE$",
'20 PRINT UCASE$(A$); "|"; LCASE$(A$); "|"; LCASE$(UCASE$("mIxEd"))' in
"\n".join(l.rstrip() for l in b.screen_text().display))
out = run('10 DIM Q$(2): Q$(3) = "X"') out = run('10 DIM Q$(2): Q$(3) = "X"')
check("subscript out of range", "SUBSCRIPT" in out.upper()) check("subscript out of range", "SUBSCRIPT" in out.upper())
out = run('10 DIM Z$(300)') out = run('10 DIM Z$(300)')
+399 -75
View File
@@ -99,7 +99,7 @@ L End Enter now it is 10 PRINT "HELLO"
`RENUM` gives the lines new numbers, starting at 10 (or the first number `RENUM` gives the lines new numbers, starting at 10 (or the first number
given) and going up in tens (or the second). It also changes the line numbers given) and going up in tens (or the second). It also changes the line numbers
after `GOTO`, `GOSUB`, `THEN`, `RUN` and `ON … GOTO`/`GOSUB` so the program after `GOTO`, `GOSUB`, `THEN`, `ELSE`, `RUN` and `ON … GOTO`/`GOSUB` so the program
runs as before. A number that isn't a line in the program is left alone. runs as before. A number that isn't a line in the program is left alone.
Numbers inside quotes, `REM` and `DATA` are left as they are, and so is a Numbers inside quotes, `REM` and `DATA` are left as they are, and so is a
line number worked out at run time. If the new numbers would pass 65535, or line number worked out at run time. If the new numbers would pass 65535, or
@@ -270,6 +270,37 @@ by statements to run. When it is false, the rest of the line is skipped, so
statements after the colon run only when the condition is true. Any non-zero statements after the colon run only when the condition is true. Any non-zero
value counts as true. value counts as true.
`ELSE` gives the line a second part, run only when the condition is false:
```
IF X > 100 THEN 500 ELSE 600
IF A$ = "YES" THEN PRINT "OK": GOTO 20 ELSE PRINT "NO"
IF A THEN IF B THEN PRINT "BOTH" ELSE PRINT "A ONLY" ELSE PRINT "NOT A"
```
An `ELSE` belongs to the nearest `IF` before it that has none yet.
**Block IF.** When `THEN` is the last thing on its line, the statements that
follow, down to `END IF`, are the `THEN` part, and the block can have
`ELSEIF` and `ELSE` parts too:
```
10 IF T < 0 THEN
20 PRINT "FREEZING"
30 C = 1
40 ELSEIF T < 20 THEN
50 PRINT "COOL"
60 ELSE
70 PRINT "WARM"
80 END IF
```
Only the first part whose condition is true runs (or `ELSE`'s, if none is);
then the program carries on after `END IF`. Blocks nest inside each other and
inside loops. `ELSEIF` may be written `ELSE IF`, and `END IF` `ENDIF`. Each
`ELSEIF` must end its line with `THEN`. Block IFs work in a program, not in
a direct statement.
### GOTO, GOSUB, RETURN, ON ### GOTO, GOSUB, RETURN, ON
``` ```
@@ -304,6 +335,56 @@ NEXT J, I
- Loops nest 16 deep. - Loops nest 16 deep.
- Jumping out of a loop with `GOTO` is allowed. Starting a new `FOR` with the - Jumping out of a loop with `GOTO` is allowed. Starting a new `FOR` with the
same variable discards the old loop. same variable discards the old loop.
- `EXIT FOR` leaves the innermost loop at once, carrying on after its `NEXT`;
the variable keeps the value it had.
### DO … LOOP — loops on a condition
```
10 DO WHILE I < 10
20 I = I + 1
30 LOOP
10 DO
20 INPUT "GUESS"; G
30 LOOP UNTIL G = 7
```
- `DO WHILE` *condition* runs the loop while the condition is true, testing it
before each time round, so the body may not run at all. `DO UNTIL`
*condition* runs it until the condition is true.
- `LOOP WHILE` and `LOOP UNTIL` test at the end instead, so the body always
runs at least once.
- A plain `DO` … `LOOP` goes round for ever, until `EXIT DO` (or `GOTO`, `END`
or Ctrl-C) leaves it. `EXIT DO` carries on after the `LOOP`.
- Loops nest 16 deep, with `FOR` loops inside and out. A whole loop can be on
one line, or in a direct statement:
`I = 0: DO: I = I + 1: PRINT I: LOOP UNTIL I = 5`.
### SELECT CASE — choosing by value
```
10 SELECT CASE N
20 CASE 0
30 PRINT "NONE"
40 CASE 1, 2, 3
50 PRINT "A FEW"
60 CASE 4 TO 9
70 PRINT "SEVERAL"
80 CASE IS >= 10
90 PRINT "LOTS"
100 CASE ELSE
110 PRINT "LESS THAN NONE"
120 END SELECT
```
`SELECT CASE` works out its value once, then runs the statements under the
first `CASE` that matches it and carries on after `END SELECT`. A `CASE` lists
values, ranges (*low* `TO` *high*) and comparisons (`IS` followed by `<`,
`<=`, `=`, `<>`, `>=` or `>` and a value), separated by commas; any one of
them matching is enough. `CASE ELSE` matches anything, so it goes last. When
no `CASE` matches, nothing runs. The value may be a string, with strings in
the `CASE`s: `CASE "A" TO "M"` compares in alphabetical order, as `<` does.
### DIM — arrays ### DIM — arrays
@@ -338,6 +419,16 @@ in its formula are the program's ordinary variables.
the program. A `DATA` statement takes up the rest of its line. `RESTORE` starts the program. A `DATA` statement takes up the rest of its line. `RESTORE` starts
again from the first item. again from the first item.
### OPTION ANGLE
```
OPTION ANGLE DEGREES
OPTION ANGLE RADIANS
```
Chooses the units of the trigonometric functions (section 6). Radians are
the default, and `RUN` goes back to them.
### END, STOP, REM ### END, STOP, REM
- `END` stops the program quietly. - `END` stops the program quietly.
@@ -379,16 +470,74 @@ and `INK` are described in sections 7 and 8.
| `ABS(X)` | Absolute value | | `ABS(X)` | Absolute value |
| `SGN(X)` | -1, 0 or 1 | | `SGN(X)` | -1, 0 or 1 |
| `INT(X)` | Largest whole number not above *X*: `INT(-2.5)` is -3 | | `INT(X)` | Largest whole number not above *X*: `INT(-2.5)` is -3 |
| `IP(X)` | The whole-number part, towards 0: `IP(-2.5)` is -2 |
| `FP(X)` | The fraction part, `X - IP(X)`: `FP(-2.5)` is -.5 |
| `CEIL(X)` | Smallest whole number not below *X*: `CEIL(2.1)` is 3 |
| `ROUND(X [, N])` | *X* rounded to *N* decimal places (0 if left out); a negative *N* rounds to tens, hundreds…: `ROUND(2.567, 2)` is 2.57, `ROUND(1250, -2)` is 1300. Halves go up, as `INT(X + .5)` does: `ROUND(-2.5)` is -2 |
| `TRUNCATE(X, N)` | *X* cut short after *N* decimal places: `TRUNCATE(-2.567, 1)` is -2.5 |
| `MOD(A, B)` | Remainder of *A* divided by *B*, with the sign of *B*: `A - B * INT(A / B)`, but exact. `MOD(-7, 3)` is 2 |
| `MIN(A, B, …)`, `MAX(A, B, …)` | Smallest or largest of any number of values |
| `FACT(N)` | *N* factorial, for whole numbers 0 to 34 |
| `SQR(X)` | Square root | | `SQR(X)` | Square root |
| `EXP(X)` | e to the power *X* | | `EXP(X)` | e to the power *X* |
| `LOG(X)` | Natural logarithm | | `LOG(X)` | Natural logarithm |
| `SIN(X)`, `COS(X)`, `TAN(X)` | Trigonometry, in radians | | `LOG10(X)`, `LOG2(X)` | Logarithm to base 10 or 2 (`LOG2` is exact for powers of 2); powers of 10 are `10 ^ X` |
| `ATN(X)` | Arctangent, in radians; `4*ATN(1)` is pi | | `PI` | 3.14159265 (no brackets) |
| `RND` or `RND(X)` | Random number from 0 up to (not including) 1; *X* is ignored | | `RND` or `RND(X)` | Random number from 0 up to (not including) 1; *X* is ignored |
| `FNx(X)` | A function made with `DEF` | | `FNx(X)` | A function made with `DEF` |
A whole number from 1 to 6: `1 + INT(RND * 6)`. A whole number from 1 to 6: `1 + INT(RND * 6)`.
### Trigonometry
| Function | Result |
|---|---|
| `SIN(X)`, `COS(X)`, `TAN(X)` | Sine, cosine, tangent |
| `SEC(X)`, `CSC(X)`, `COT(X)` | Secant, cosecant, cotangent: `1/COS(X)`, `1/SIN(X)`, `1/TAN(X)` |
| `ATN(X)` | Arctangent, from -90° to 90° (-π/2 to π/2) |
| `ASIN(X)`, `ACOS(X)` | Arcsine (-90° to 90°) and arccosine (0° to 180°), for *X* from -1 to 1 |
| `ANGLE(X, Y)` | The direction of the point (*X*, *Y*) from the origin, from -180° to 180°, measured anticlockwise from the X axis; it gets the quarter right, as `ATN(Y / X)` can't (other languages call it `ATAN2(Y, X)`) |
| `DEG(X)`, `RAD(X)` | Radians to degrees, degrees to radians |
| `SINH(X)`, `COSH(X)`, `TANH(X)` | Hyperbolic sine, cosine, tangent |
| `ASINH(X)`, `ACOSH(X)`, `ATANH(X)` | Their inverses: `ACOSH` for *X* ≥ 1, `ATANH` for *X* between -1 and 1 |
Angles are in radians until a program says `OPTION ANGLE DEGREES`; from
then on the trigonometric functions take degrees and the inverse ones
(`ATN`, `ASIN`, `ACOS`, `ANGLE`) give degrees. `OPTION ANGLE RADIANS` goes
back, and so does `RUN`. In degrees, `SIN`, `COS` and the rest are exact at
multiples of 90, so `SIN(180)` is 0, not a tiny remainder.
A value outside a function's range, such as `ASIN(2)`, `LOG10(0)`,
`ACOSH(0)`, `FACT(2.5)`, `ANGLE(0, 0)` or, in degrees, `TAN(90)`, stops
the program with `ILLEGAL FUNCTION CALL`; `MOD(A, 0)` is
`DIVISION BY ZERO`. Every function is correct to within 3 units in the last
place of single precision (about 1 part in 3 million), checked against a
PC's double-precision maths by `basic/test-math.py`.
```
10 OPTION ANGLE DEGREES
20 FOR A = 0 TO 75 STEP 15
30 PRINT A, ROUND(SIN(A), 4), ROUND(COS(A), 4), ROUND(TAN(A), 4)
40 NEXT A
50 PRINT "BEARING OF (3, 4):"; ROUND(ANGLE(3, 4), 2); "DEGREES"
60 PRINT "ITS HYPOTENUSE:"; SQR(3^2 + 4^2)
70 PRINT "ACOS(-1) ="; ACOS(-1); " 20! ="; FACT(20)
```
prints
```
0 0 1 0
15 .2588 .9659 .2679
30 .5 .866 .5774
45 .7071 .7071 1
60 .866 .5 1.7321
75 .9659 .2588 3.7321
BEARING OF (3, 4): 53.13 DEGREES
ITS HYPOTENUSE: 5
ACOS(-1) = 180 20! = 2.4329E+18
```
### Strings ### Strings
| Function | Result | | Function | Result |
@@ -401,6 +550,20 @@ A whole number from 1 to 6: `1 + INT(RND * 6)`.
| `LEFT$(A$, N)` | First *N* characters | | `LEFT$(A$, N)` | First *N* characters |
| `RIGHT$(A$, N)` | Last *N* characters | | `RIGHT$(A$, N)` | Last *N* characters |
| `MID$(A$, S [, N])` | *N* characters (or the rest) starting at position *S* (from 1) | | `MID$(A$, S [, N])` | *N* characters (or the rest) starting at position *S* (from 1) |
| `UCASE$(A$)` | The string in capitals: only `a`–`z` change |
| `LCASE$(A$)` | The string in small letters: only `A`–`Z` change |
BASIC turns what you type into capitals outside quotes, but text that comes
from `INPUT`, a file or `CHR$` keeps its case. `UCASE$` is the way to compare
an answer whatever case it was typed in, `IF UCASE$(A$) = "YES" THEN …`, and
the two together tidy a name:
```
10 INPUT "YOUR NAME"; N$
20 PRINT "HELLO, "; UCASE$(LEFT$(N$, 1)); LCASE$(MID$(N$, 2))
```
typed `aDA LOVELACE`, prints `HELLO, Ada lovelace`.
### Machine and screen ### Machine and screen
@@ -843,9 +1006,9 @@ graphics come back exactly as they were.
T1 00000000 T2 00000000 S0 00013FB0 S1 0000A01E A0 00000000 A1 00012000 T1 00000000 T2 00000000 S0 00013FB0 S1 0000A01E A0 00000000 A1 00012000
... ...
ADDR WORD INSTRUCTION STACK ADDR WORD INSTRUCTION STACK
>*12000 04100513 LI A0,65 13F70 00000000 >*12000 04100513 li a0,65 13F70 00000000
12004 F0A000A3 SB A0,-255(ZERO) 13F74 0000A01E 12004 F0A000A3 sb a0,-255(zero) 13F74 0000A01E
12008 00008067 RET ... 12008 00008067 ret ...
MEMORY MEMORY
12000 13 05 10 04 A3 00 A0 F0-67 80 00 00 00 00 00 00 ....g........... 12000 13 05 10 04 A3 00 A0 F0-67 80 00 00 00 00 00 00 ....g...........
``` ```
@@ -856,9 +1019,69 @@ graphics come back exactly as they were.
breakpoint. breakpoint.
- The stack column shows the words at SP upwards. - The stack column shows the words at SP upwards.
**The wide screen.** When the terminal is 132 × 64, as it is from power-up,
the monitor uses all of it and shows everything at once, with nothing to
switch between. It goes by the width when it is entered, so after `ESC[?3l`
(80 × 32) it draws the screen above. Its left half:
```
RISC-V MONITOR
REGISTERS
PC 000065B4 ZERO 00000000 RA 00005364 SP 00013EF0
GP 0000F8B8 TP 00000000 T0 0000000A T1 0000000A
T2 00009000 S0 0000000A S1 000000AE A0 000000AE
...
T6 0000000A
CONTROL AND STATUS
MSTATUS 00001880 MEPC 00012008 MTVAL 00000000
MCAUSE 00000003 EBREAK
CYCLE 000000000002C110 INSTRET 000000000002C27A
BREAKPOINT NONE
ADDR WORD INSTRUCTION
> 065B4 80CFF06F j 0x55c0
065B8 8F8FD0EF jal 0x36b0
...
```
and its right half:
```
STOPPED BY MONITOR COMMAND
FLOAT REGISTERS
FT0 00000000 0 FA6 00000000 0
...
FA0 42900000 7.200000E+01 FS10 00000000 0
FA1 C2F6E979 -1.234560E+02 FS11 00000000 0
...
FA5 C7000000 -3.276800E+04 FT11 00000000 0
FCSR 00000001 ROUNDING RNE FLAGS -- -- -- -- NX
STACK
13EF0 00000000
...
```
- **Registers:** the PC and all 32 integer registers by name, and all 32 float
registers by their ABI names, each as its bit pattern and as a number
(to 7 digits). FCSR is shown whole and split into its rounding mode and
its five flags (`NV` invalid, `DZ` divide by zero, `OF` overflow, `UF`
underflow, `NX` inexact), a letter pair for each that is set.
- **After a step,** or whenever the monitor comes back, the registers the
program changed since the monitor last showed them are in bright yellow.
- **Control and status:** `mstatus`, `mepc`, `mcause` (with what it means),
`mtval`, the `cycle` and `instret` counters, and the breakpoint.
- **Below them:** 24 rows of disassembly with the stack beside it, and 14 rows
of memory, always there. `F` has nothing to switch, so it just says so; `M`
and `D`, the arrow keys and Page Up and Page Down move the windows as on
the narrow screen, and `DIR` and `ASM`'s errors use the memory window until
`M`.
### Commands ### Commands
Type a command on the bottom line and press Enter. Numbers are in hex. Type a command on the bottom line and press Enter. Numbers are in hex, with
or without `0x`.
| Command | Does | | Command | Does |
|---|---| |---|---|
@@ -871,11 +1094,11 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
| `D addr` | Show the disassembly from *addr* (`D` alone: from PC) | | `D addr` | Show the disassembly from *addr* (`D` alone: from PC) |
| `M addr` | Show memory from *addr* | | `M addr` | Show memory from *addr* |
| `E addr bytes…` | Write bytes into memory: `E 12000 13 05 10 04` | | `E addr bytes…` | Write bytes into memory: `E 12000 13 05 10 04` |
| `R reg=value` | Set PC or a register, by name or number: `R A0=1234`, `R X10=1234`; a float register as its bit pattern: `R F1=3FC00000` (1.5), or `R FCSR=0` | | `R reg=value` | Set PC or a register, by name or number: `R A0=1234`, `R X10=1234`; a float register as its bit pattern, by number or name: `R F1=3FC00000` (1.5), `R FA0=3FC00000`, or `R FCSR=0` |
| `F` | Show the float registers F0–F31 and FCSR, as bit patterns, in the memory window (`M` brings the memory back) | | `F` | On the 80 × 32 screen, show the float registers F0–F31 and FCSR, as bit patterns, in the memory window (`M` brings the memory back); the 132 × 64 screen always shows them |
| `SAVE "NAME" start end` | Save memory *start* to *end* (inclusive) to a file in flash | | `SAVE "NAME" start end` | Save memory *start* to *end* (inclusive) to a file in flash |
| `LOAD "NAME"` | Load a memory file back to where it was saved from | | `LOAD "NAME"` | Load a memory file back to where it was saved from |
| `LOAD "NAME" addr` | Load it at *addr* instead (0A000h or above) | | `LOAD "NAME" addr` | Load it at *addr* instead (A000 or above) |
| `DIR` | List the files in flash in the memory window (`M` brings the memory back) | | `DIR` | List the files in flash in the memory window (`M` brings the memory back) |
| `ASM "NAME"` | Assemble a source file into memory (see the assembler, below) | | `ASM "NAME"` | Assemble a source file into memory (see the assembler, below) |
| `A addr` | Assemble lines as you type them, from *addr*; an empty line ends | | `A addr` | Assemble lines as you type them, from *addr*; an empty line ends |
@@ -894,9 +1117,11 @@ Type a command on the bottom line and press Enter. Numbers are in hex.
- **The float registers** are saved and put back like the others, while the - **The float registers** are saved and put back like the others, while the
FPU is on (`mstatus.FS`, which BASIC turns on); `F` says when it is off. FPU is on (`mstatus.FS`, which BASIC turns on); `F` says when it is off.
- **The disassembler** shows every RV32IMF instruction and the CSR and system - **The disassembler** shows every RV32IMF instruction and the CSR and system
instructions, using the usual short forms where they apply (`LI`, `MV`, `J`, instructions the way GNU `objdump` does: in lower case, with the usual
`RET`, `BEQZ`, `CSRR` and so on), with hex numbers like `1F0H` and `0A200H`; short forms where they apply (`li`, `mv`, `j`, `ret`, `beqz`, `csrr` and so
anything else is shown as `DW` and its value. on), hex numbers like `0x1f0`, and the float registers by their ABI names
(`fa0`, `ft1`). Anything else is shown as `.word` and its value. What it
shows, the assembler reads back.
### A machine-code example ### A machine-code example
@@ -907,8 +1132,8 @@ RUN
MONITOR MONITOR
``` ```
The `POKE`s put `LI A0,65 : SB A0,-255(ZERO) : RET` at 12000h; it prints an The `POKE`s put `li a0,65`, `sb a0,-255(zero)` and `ret` at 0x12000; it
`A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`. prints an `A` (port 1 is at -255 from address 0). In the monitor, `B 12000` then `X`.
Back in BASIC, `CALL 73728` stops at the breakpoint. Press Enter to step Back in BASIC, `CALL 73728` stops at the breakpoint. Press Enter to step
through each instruction, or `X` to let it finish. through each instruction, or `X` to let it finish.
@@ -917,89 +1142,110 @@ through each instruction, or `X` to let it finish.
The monitor can assemble RISC-V source code into memory, either a whole file The monitor can assemble RISC-V source code into memory, either a whole file
or one line at a time. or one line at a time.
**Writing source.** Type it into BASIC as numbered lines, just like a **Writing source.** The assembler reads the GNU assembler's RISC-V syntax,
program, and save it. BASIC doesn't run it; it just keeps the lines. The as in the RISC-V manuals and `gcc -S` output. Type the source into BASIC as
assembler ignores the line numbers, and uses them in its error messages. numbered lines, just like a program, and save it. BASIC doesn't run it; it
just keeps the lines. The assembler ignores the line numbers, and uses them
in its error messages.
``` ```
NEW NEW
10 ; PRINT A MESSAGE 10 # print a message
20 ORG 12000H 20 .org 0x12000
30 START: LA A1,MSG 30 start: la a1, msg
40 LOOP: LBU A0,0(A1) 40 loop: lbu a0, 0(a1)
50 BEQZ A0,DONE 50 beqz a0, done
60 WAIT: LBU T0,-256(ZERO) ; CAN THE SCREEN TAKE A CHARACTER? 60 wait: lbu t0, -256(zero) # can the screen take a character?
70 ANDI T0,T0,2 70 andi t0, t0, 2
80 BEQZ T0,WAIT 80 beqz t0, wait
90 SB A0,-255(ZERO) 90 sb a0, -255(zero)
100 ADDI A1,A1,1 100 addi a1, a1, 1
110 J LOOP 110 j loop
120 DONE: RET 120 done: ret
130 MSG: DB "HELLO FROM ASSEMBLY",13,10,0 130 msg: .string "Hello from assembly\r\n"
SAVE "HELLO" SAVE "HELLO"
``` ```
A text file sent from the PC with `tools/send-bas.py` works the same way, as A text file sent from the PC with `tools/send-bas.py` works the same way, as
long as each line starts with a number. long as each line starts with a number.
BASIC stores what you type in capitals, except inside double quotes, so
`LIST` shows `30 START: LA A1, MSG`. The assembler doesn't mind either way,
but a character constant changes: `'a'` becomes `'A'`. BASIC also drops the
spaces after the line number, so a label needs its colon. And BASIC knows
nothing of `\"`, so a string can't contain a double quote; use `.byte 34`.
**Assembling.** `MONITOR`, then `ASM "HELLO"`. The monitor says **Assembling.** `MONITOR`, then `ASM "HELLO"`. The monitor says
`ASSEMBLED 12000-12041` and shows the code; errors are listed in the memory `ASSEMBLED 12000-12041` and shows the code; errors are listed in the memory
window with their line numbers. Back in BASIC (`X`), `CALL 73728` runs it. window with their line numbers. Back in BASIC (`X`), `CALL 73728` runs it.
Or set a breakpoint first and step through it. Or set a breakpoint first and step through it.
**One line at a time.** `A 12100` starts the line assembler at 12100h: type **One line at a time.** `A 12100` starts the line assembler at 0x12100: type
an instruction, press Enter, and it is assembled and shown, then the next an instruction, press Enter, and it is assembled and shown, then the next
address is offered. An empty line ends. Labels from the last `ASM` can be used. address is offered. An empty line ends. Labels from the last `ASM` can be used.
**Syntax**: as the disassembler shows it. **Syntax**: GNU as's, which is also what the disassembler shows.
| | | | | |
|---|---| |---|---|
| Labels | `NAME:` before an instruction, up to 8 letters and digits; `NAME EQU value` for constants | | Labels | `name:` before an instruction, or on a line of its own; letters, digits, `_` and `.`, of which the first 8 count |
| Numbers | `123`, `0FFH`, `$FF`, `0x1F`, `1010B`, `'A'`; `$` alone is the current address | | Constants | `.equ name, value`, `.set name, value` or `name = value` |
| Expressions | `+ - * / & |` and brackets: `LI A0,END-START`, `LI A1,'Z'-1` | | Numbers | `123`, `0x1f`, `0b1010`, `'A'`, `'\n'`; `.` is the current address |
| Registers | `X0`–`X31` or `ZERO RA SP GP TP T0`–`T6 S0`–`S11 FP A0`–`A7` | | Expressions | <code>+ - * / &amp; &#124; ^ &lt;&lt; &gt;&gt; ~</code> and brackets: `li a0, end - start`, `li a1, 'Z' - 1`; `%hi(x)` and `%lo(x)` split an address for `lui` and `addi`, or a load or store: `lui a5, %hi(table)` then `lw a0, %lo(table)(a5)` |
| Memory operands | *offset*`(`*register*`)`: `LW A0,8(SP)`, `SB A0,-255(ZERO)`, `LBU T0,(A1)` | | Registers | `x0`–`x31` or `zero ra sp gp tp t0`–`t6 s0`–`s11 fp a0`–`a7` |
| CSRs | by name (`MSTATUS`, `MEPC`, `MCAUSE`, `CYCLE`, `TIME`, `INSTRET`, …) or number | | Memory operands | *offset*`(`*register*`)`: `lw a0, 8(sp)`, `sb a0, -255(zero)`, `lbu t0, (a1)` |
| `ORG addr` | assemble from *addr* (12000h if there is no `ORG`) | | CSRs | by name (`mstatus`, `mepc`, `mcause`, `cycle`, `time`, `instret`, …) or number |
| `DB` / `DEFB` / `DEFM` | bytes and `"strings"`: `DB "HI",13,10,0` | | `.org addr` | assemble from *addr* (0x12000 if there is no `.org`) |
| `DH` | 16-bit halfwords, low byte first | | `.byte` | bytes: `.byte 13, 10, 'A'` |
| `DW` / `DEFW` | 32-bit words, low byte first | | `.half` / `.short` | 16-bit halfwords, low byte first |
| `DS n` / `DEFS n` | skip *n* bytes | | `.word` / `.long` | 32-bit words, low byte first: `.word start, 0x12345678` |
| `ALIGN n` | skip to a multiple of *n* (instructions must be on a multiple of 4) | | `.ascii "text"` | the characters of the text; `\n`, `\r`, `\t`, `\0`, `\\` and `\"` stand for a line feed, return, tab, 0, `\` and `"` |
| `END` | stop here | | `.string "text"` / `.asciz "text"` | the same with a 0 after it |
| `;` | comment to the end of the line | | `.space n` / `.skip n` / `.zero n` | *n* bytes of 0, or of *fill* with `.space n, fill` |
| `.align n` / `.p2align n` | to a multiple of 2*ⁿ*: `.align 2` for a word. The gap is filled with zeros up to a word, then `nop`s, so code can run through it; `.align n, fill` fills it with *fill* |
| `.balign n` | to a multiple of *n* bytes |
| `.end` | stop here |
| `.text`, `.data`, `.section`, `.globl`, `.global`, `.option`, `.type` | accepted and ignored, so code written for GNU as needn't be changed |
| `#` or `;` | comment to the end of the line |
- **Instructions:** all of RV32I and M, `CSRRW`…`CSRRCI`, `ECALL`, `EBREAK`, The assembler of earlier versions used other spellings, and sources written
`MRET`, `MNRET`, `WFI`, `FENCE`, `FENCE.I`, and the short forms `NOP`, `LI`, for it still assemble: `ORG`, `NAME EQU value`, `DB`/`DEFB`/`DEFM` (with
`LA`, `MV`, `NOT`, `NEG`, `SEQZ`, `SNEZ`, `SLTZ`, `SGTZ`, `J`, `JR`, `JAL` strings taken as they are, no escapes), `DH`, `DW`/`DEFW`, `DS n`/`DEFS n`
*target* (saving RA), `JALR` *register*, `RET`, `CALL`, `BEQZ`, `BNEZ`, (skip *n* bytes), `ALIGN n` (to a multiple of *n*), `END`, numbers like
`BLEZ`, `BGEZ`, `BLTZ`, `BGTZ`, `BGT`, `BLE`, `BGTU`, `BLEU`, `CSRR`, `CSRW`, `0FFH`, `$FF` and `1010B`, and `$` for the current address.
`CSRS`, `CSRC`, `CSRWI`, `CSRSI`, `CSRCI`.
- **Floating point:** `FLW`, `FSW`, `FADD.S`, `FSUB.S`, `FMUL.S`, `FDIV.S`, - **Instructions:** all of RV32I and M, `csrrw`…`csrrci`, `ecall`, `ebreak`,
`FSQRT.S`, `FMADD.S`, `FMSUB.S`, `FNMSUB.S`, `FNMADD.S`, `FMIN.S`, `FMAX.S`, `mret`, `mnret`, `wfi`, `fence`, `fence.i`, and the short forms `nop`, `li`,
`FSGNJ.S`, `FSGNJN.S`, `FSGNJX.S` (and `FMV.S`, `FNEG.S`, `FABS.S`), `FEQ.S`, `la`, `mv`, `not`, `neg`, `seqz`, `snez`, `sltz`, `sgtz`, `j`, `jr`, `jal`
`FLT.S`, `FLE.S`, `FCVT.W.S`, `FCVT.WU.S`, `FCVT.S.W`, `FCVT.S.WU`, `FMV.X.W`, *target* (saving `ra`), `jalr` *register*, `ret`, `call`, `beqz`, `bnez`,
`FMV.W.X`, `FCLASS.S`. Float registers are `F0`–`F31` or `FT0`–`FT11`, `blez`, `bgez`, `bltz`, `bgtz`, `bgt`, `ble`, `bgtu`, `bleu`, `csrr`,
`FS0`–`FS11`, `FA0`–`FA7`; a rounding mode (`RNE`, `RTZ`, `RDN`, `RUP`, `RMM`) `csrw`, `csrs`, `csrc`, `csrwi`, `csrsi`, `csrci`.
may follow the operands, `FADD.S FA0,FA1,FA2,RTZ`, and without one the - **Floating point:** `flw`, `fsw`, `fadd.s`, `fsub.s`, `fmul.s`, `fdiv.s`,
instruction uses FCSR's (round to nearest unless changed). CSRs `FFLAGS`, `fsqrt.s`, `fmadd.s`, `fmsub.s`, `fnmsub.s`, `fnmadd.s`, `fmin.s`, `fmax.s`,
`FRM` and `FCSR`. `fsgnj.s`, `fsgnjn.s`, `fsgnjx.s` (and `fmv.s`, `fneg.s`, `fabs.s`),
- **`LI`** is one instruction (`ADDI`) for a value from −2048 to 2047 that is `feq.s`, `flt.s`, `fle.s`, `fcvt.w.s`, `fcvt.wu.s`, `fcvt.s.w`, `fcvt.s.wu`,
known by then, otherwise two (`LUI`, `ADDI`); **`LA`** is always two `fmv.x.w`, `fmv.w.x`, `fclass.s`. Float registers are `f0`–`f31` or
(`AUIPC`, `ADDI`); **`CALL`** is `JAL RA`, which reaches 1 MB either way. `ft0`–`ft11`, `fs0`–`fs11`, `fa0`–`fa7`; a rounding mode (`rne`, `rtz`,
- **Where code can go:** RAM from 0A000h up. 12000h–12FFFh is the safe place, `rdn`, `rup`, `rmm`) may follow the operands, `fadd.s fa0, fa1, fa2, rtz`,
since BASIC doesn't use it. and without one the instruction uses FCSR's (round to nearest unless
changed). CSRs `fflags`, `frm` and `fcsr`, and the short forms `frcsr`,
`fscsr`, `frrm`, `fsrm`, `frflags`, `fsflags`.
- **`li`** is one instruction (`addi`) for a value from −2048 to 2047 that is
known by then, `lui` alone for one whose low 12 bits are 0, otherwise two
(`lui`, `addi`); **`la`** is always two (`auipc`, `addi`). **`call`** is
`jal ra`, which reaches 1 MB either way (GNU as makes it `auipc` and
`jalr`, 8 bytes, to reach anywhere).
- **Where code can go:** RAM from 0xA000 up. 0x12000–0x12FFF is the safe
place, since BASIC doesn't use it.
- **Labels:** up to 200. - **Labels:** up to 200.
- **Typing source into BASIC:** BASIC turns lower case to upper case (except
inside double quotes), so `'a'` becomes `'A'`. Indentation after the line
number isn't kept, so labels need their colon.
**Errors:** `UNKNOWN INSTRUCTION`, `BAD REGISTER`, `MISSING OPERAND`, `TOO **Errors:** `UNKNOWN INSTRUCTION`, `BAD REGISTER`, `MISSING OPERAND`, `TOO
MANY OPERANDS`, `OFFSET(REGISTER)`, `UNDEFINED LABEL`, `DUPLICATE LABEL`, MANY OPERANDS`, `OFFSET(REGISTER)`, `UNDEFINED LABEL`, `DUPLICATE LABEL`,
`VALUE OUT OF RANGE` (an immediate, offset or `LUI` value that doesn't fit), `VALUE OUT OF RANGE` (an immediate, offset or `lui` value that doesn't fit),
`BRANCH TOO FAR` (beyond ±4 KB), `JUMP TOO FAR` (beyond ±1 MB), `NOT ON A `BRANCH TOO FAR` (beyond ±4 KB), `JUMP TOO FAR` (beyond ±1 MB), `NOT ON A
WORD: USE ALIGN 4`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`. WORD: USE .ALIGN 2`, `CAN'T WRITE THERE`, `BAD NUMBER`, `BAD EXPRESSION`,
`BAD STRING` (`.ascii` or `.string` without a string), `ALIGN TO A POWER OF
2`, `EQU NEEDS A NAME`.
### How it works ### How it works
@@ -1205,6 +1451,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.
@@ -1222,13 +1539,20 @@ An error stops the program and reports the line, for example
| `NEXT WITHOUT FOR` | `NEXT` with no loop open (or the wrong variable) | | `NEXT WITHOUT FOR` | `NEXT` with no loop open (or the wrong variable) |
| `OUT OF DATA` | `READ` after the last `DATA` item | | `OUT OF DATA` | `READ` after the last `DATA` item |
| `SUBSCRIPT OUT OF RANGE` | An array subscript below 0 or beyond its `DIM` | | `SUBSCRIPT OUT OF RANGE` | An array subscript below 0 or beyond its `DIM` |
| `DIVISION BY ZERO` | Dividing by 0 | | `DIVISION BY ZERO` | Dividing by 0, or `MOD(A, 0)` |
| `OUT OF MEMORY` | The program and arrays don't fit | | `OUT OF MEMORY` | The program and arrays don't fit |
| `TYPE MISMATCH` | A string where a number belongs, or the other way round | | `TYPE MISMATCH` | A string where a number belongs, or the other way round |
| `STRING TOO LONG` | A string over 79 characters, or a program line too long to store (also from `RENUM`) | | `STRING TOO LONG` | A string over 79 characters, or a program line too long to store (also from `RENUM`) |
| `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE`, a `RENUM` past 65535 or with a step of 0 | | `ILLEGAL FUNCTION CALL` | A bad argument: `SQR(-1)`, `LOG(0)`, `ASIN(2)`, `FACT(-1)` (section 6), a colour over 15, `AND` on a number beyond ±32767, a file number other than 1–3, an impossible `DATE`, a `RENUM` past 65535 or with a step of 0 |
| `UNDEFINED FUNCTION` | `FNx` used before its `DEF` | | `UNDEFINED FUNCTION` | `FNx` used before its `DEF` |
| `FOR NESTED TOO DEEPLY` | More than 16 loops open | | `FOR NESTED TOO DEEPLY` | More than 16 `FOR` loops open |
| `DO NESTED TOO DEEPLY` | More than 16 `DO` loops open |
| `FOR WITHOUT NEXT` | A `FOR` that runs no times, or `EXIT FOR`, with no `NEXT` after it |
| `DO WITHOUT LOOP` | A `DO` whose condition fails, or `EXIT DO`, with no `LOOP` after it |
| `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 |
| `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.
+20 -25
View File
@@ -1,29 +1,24 @@
#!/bin/bash #!/bin/bash
# Turn docs/basic-manual.md into docs/basic-manual.pdf (needs python3-markdown and Chrome). # Turn docs/basic-manual.md into docs/basic-manual.pdf.
# The Markdown is the only source: md2tex.py converts it to LaTeX, and XeLaTeX
# typesets it in IBM Plex. Needs python3-markdown, XeLaTeX (texlive-xetex,
# -latex-extra for KOMA-Script, tcolorbox, xltabular) and the IBM Plex fonts
# in /usr/share/fonts/truetype/ibm-plex (fonts-ibm-plex).
set -e set -e
cd "$(dirname "$0")" cd "$(dirname "$0")"
python3 - <<'PY' work=$(mktemp -d)
import markdown trap 'rm -rf "$work"' EXIT
body = markdown.markdown(open("basic-manual.md").read(), extensions=["tables", "fenced_code"]) python3 md2tex.py basic-manual.md "$work/basic-manual.tex"
css = """ # three passes: contents, then page numbers in the contents, then settled
@page { size: A4; margin: 18mm 16mm; } for pass in 1 2 3; do
body { font-family: "DejaVu Serif", Georgia, serif; font-size: 10.5pt; line-height: 1.45; color: #111; } if ! (cd "$work" && xelatex -interaction=nonstopmode -halt-on-error basic-manual.tex >/dev/null); then
h1 { font-size: 24pt; margin: 0 0 4pt; } grep -A8 '^!' "$work/basic-manual.log" >&2 || tail -40 "$work/basic-manual.log" >&2
h1 + p { font-size: 12pt; color: #444; margin-bottom: 18pt; } exit 1
h2 { font-size: 15pt; border-bottom: 1px solid #999; padding-bottom: 2pt; margin-top: 22pt; fi
page-break-after: avoid; } done
h3 { font-size: 12pt; margin-top: 14pt; page-break-after: avoid; } if grep -q 'Missing character' "$work/basic-manual.log"; then
code, pre { font-family: "DejaVu Sans Mono", monospace; font-size: 9pt; } echo "warning: characters missing from the fonts:" >&2
pre { background: #f2f2f2; border-left: 3px solid #4a7; padding: 6pt 8pt; page-break-inside: avoid; } grep 'Missing character' "$work/basic-manual.log" | sort -u >&2
table { border-collapse: collapse; margin: 6pt 0; page-break-inside: avoid; } fi
th, td { border: 1px solid #bbb; padding: 3pt 6pt; vertical-align: top; text-align: left; } cp "$work/basic-manual.pdf" basic-manual.pdf
th { background: #e8e8e8; }
"""
open("basic-manual.html", "w").write(
"<!doctype html><html><head><meta charset='utf-8'><title>Basys 3 RISC-V BASIC</title>"
"<style>%s</style></head><body>%s</body></html>" % (css, body))
PY
google-chrome --headless --disable-gpu --no-pdf-header-footer \
--print-to-pdf="$PWD/basic-manual.pdf" "file://$PWD/basic-manual.html" 2>/dev/null
rm basic-manual.html
echo "wrote docs/basic-manual.pdf" echo "wrote docs/basic-manual.pdf"
Executable
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""Turn docs/basic-manual.md into LaTeX for XeLaTeX (docs/build-manual.sh runs it).
The Markdown stays the only source. It is read with python-markdown (tables and
fenced code), and the HTML that gives is walked and written out as LaTeX:
## headings become numbered chapters (their "N." prefix must count up from 1,
since the text refers to "section N"), ### headings unnumbered sections in the
contents, tables booktabs tables that can break across pages, and code blocks
framed verbatim text.
md2tex.py basic-manual.md basic-manual.tex
"""
import html.parser
import re
import sys
import markdown
# ------------------------------------------------------------- HTML to a tree
class Node:
def __init__(self, tag, attrs=None, parent=None):
self.tag, self.attrs, self.parent, self.kids = tag, dict(attrs or []), parent, []
def text(self):
return "".join(k if isinstance(k, str) else k.text() for k in self.kids)
class TreeBuilder(html.parser.HTMLParser):
VOID = {"br", "hr", "img"}
def __init__(self):
super().__init__(convert_charrefs=True)
self.root = self.cur = Node("root")
def handle_starttag(self, tag, attrs):
n = Node(tag, attrs, self.cur)
self.cur.kids.append(n)
if tag not in self.VOID:
self.cur = n
def handle_endtag(self, tag):
n = self.cur
while n is not self.root and n.tag != tag:
n = n.parent
if n is not self.root:
self.cur = n.parent
def handle_data(self, data):
self.cur.kids.append(data)
# ------------------------------------------------------------------ escaping
SPECIAL = {
"\\": r"\textbackslash{}", "{": r"\{", "}": r"\}", "$": r"\$", "&": r"\&",
"#": r"\#", "%": r"\%", "_": r"\_", "~": r"\textasciitilde{}",
"^": r"\textasciicircum{}",
}
def esc(s):
return "".join(SPECIAL.get(c, c) for c in s)
def esc_code(s):
"""Inline code: escaped, in a font where -- and '' are not ligatures, with
break points after punctuation so long expressions can wrap."""
out = []
for c in s:
if c in SPECIAL:
out.append(SPECIAL[c])
elif c == "-":
out.append("-{}")
elif c in "'`\"<>":
out.append("\\char`\\%s{}" % c)
elif c == " ":
out.append("\\ ")
else:
out.append(c)
if c in ",;:/=+(":
out.append(r"\allowbreak{}")
return "".join(out)
class Quotes:
"""Straight double quotes in running text become curly, alternately."""
def __init__(self):
self.open = True
def __call__(self, s):
out = []
for c in s:
if c == '"':
out.append("“" if self.open else "”")
self.open = not self.open
else:
out.append(c)
return "".join(out)
# -------------------------------------------------------------- the converter
class Converter:
def __init__(self, codeblocks):
self.codeblocks = codeblocks
self.quotes = Quotes()
# inline content
def inline(self, node):
out = []
for k in node.kids:
if isinstance(k, str):
out.append(self.text(k))
elif k.tag == "code":
out.append(r"\code{%s}" % esc_code(k.text()))
elif k.tag == "strong":
out.append(r"\textbf{%s}" % self.inline(k))
elif k.tag == "em":
out.append(r"\emph{%s}" % self.inline(k))
elif k.tag == "br":
out.append(r"\\")
elif k.tag == "a":
out.append(r"\href{%s}{%s}" % (esc(k.attrs.get("href", "")), self.inline(k)))
elif k.tag in ("p", "ul", "ol", "pre", "table"):
out.append(self.block(k))
else:
out.append(self.inline(k))
return "".join(out)
def text(self, s):
# a code block that sat inside a list item comes through as a marker
parts = re.split(r"@@CODE(\d+)@@", s)
out = []
for i, p in enumerate(parts):
if i % 2:
out.append("\n" + self.verbatim(self.codeblocks[int(p)]) + "\n")
else:
out.append(esc(self.quotes(re.sub(r"\s+", " ", p))))
return "".join(out)
# blocks
def verbatim(self, code):
code = code.rstrip("\n")
return "\\begin{codebox}\n\\begin{Verbatim}\n%s\n\\end{Verbatim}\n\\end{codebox}" % code
def heading(self, node, level):
title = node.text().strip()
if level == 2:
m = re.match(r"(\d+)\.\s+(.*)", title)
if not m:
sys.exit("md2tex: ## heading without a number: %r" % title)
self.chapter += 1
if int(m.group(1)) != self.chapter:
sys.exit("md2tex: ## %s is out of order (expected %d)" % (title, self.chapter))
return "\\chapter{%s}\n" % self.inline_title(m.group(2))
t = self.inline_title(title)
return "\\section*{%s}\\addcontentsline{toc}{section}{%s}\n" % (t, t)
def inline_title(self, s):
return esc(self.quotes(s))
def table(self, node):
rows = []
for tr in self.find(node, "tr"):
cells = [c for c in tr.kids if not isinstance(c, str) and c.tag in ("th", "td")]
rows.append((cells[0].tag == "th" if cells else False, cells))
if not rows:
return ""
ncol = max(len(c) for _, c in rows)
lens = [0] * ncol
for _, cells in rows:
for i, c in enumerate(cells):
lens[i] = max(lens[i], len(c.text().strip()))
total = sum(lens) or 1
wide = total > 70
spec = []
for n in lens:
if not wide or n <= 22:
spec.append(r">{\raggedright\arraybackslash}l" if n <= 22 or not wide else "L")
else:
spec.append("L")
if wide and "L" not in spec:
spec[-1] = "L"
head, body = [], []
for is_head, cells in rows:
if is_head:
if any(c.text().strip() for c in cells):
head.append(" & ".join(r"\thead{%s}" % self.inline(c).strip() for c in cells))
else:
body.append(" & ".join(self.inline(c).strip() for c in cells))
env = "xltabular" if wide else "longtable"
width = "{\\linewidth}" if wide else ""
out = ["\\begin{%s}%s{%s}" % (env, width, "".join(spec))]
if head:
hrow = r"\rowcolor{gray10}" + head[0] + r" \\ \toprow"
out += [hrow, r"\endfirsthead", hrow, r"\endhead"]
else:
out += [r"\toprow"]
out.append(r"\endlastfoot")
out += [b + r" \\ \rowrule" for b in body]
out.append("\\end{%s}" % env)
return "\n".join(out) + "\n"
def find(self, node, tag):
for k in node.kids:
if isinstance(k, str):
continue
if k.tag == tag:
yield k
else:
yield from self.find(k, tag)
def block(self, node):
t = node.tag
if t == "h1":
return ""
if t in ("h2", "h3"):
return self.heading(node, int(t[1]))
if t == "p":
return self.inline(node).strip() + "\n\n"
if t == "pre":
return self.verbatim(node.text()) + "\n\n"
if t in ("ul", "ol"):
env = "itemize" if t == "ul" else "enumerate"
items = [r"\item " + self.inline(li).strip()
for li in node.kids if not isinstance(li, str) and li.tag == "li"]
return "\\begin{%s}\n%s\n\\end{%s}\n\n" % (env, "\n".join(items), env)
if t == "table":
return self.table(node)
if t == "hr":
return "\\bigskip\\hrule\\bigskip\n"
return self.inline(node)
def convert(self, root):
self.chapter = 0
title = subtitle = ""
kids = [k for k in root.kids if not isinstance(k, str) or k.strip()]
if kids and not isinstance(kids[0], str) and kids[0].tag == "h1":
title = kids.pop(0).text().strip()
if kids and not isinstance(kids[0], str) and kids[0].tag == "p" \
and len(kids[0].kids) == 1 and not isinstance(kids[0].kids[0], str) \
and kids[0].kids[0].tag == "em":
subtitle = self.inline(kids.pop(0).kids[0])
body = "".join(self.block(k) if not isinstance(k, str) else self.text(k) for k in kids)
return title, subtitle, body
PREAMBLE = r"""\documentclass[a4paper,10pt,chapterprefix=false,headings=small,
parskip=half-,toc=flat,numbers=noenddot]{scrreprt}
% ---- type: IBM Plex throughout
\usepackage{fontspec}
\defaultfontfeatures{Path=/usr/share/fonts/truetype/ibm-plex/,Extension=.ttf}
\setmainfont{IBMPlexSans}[UprightFont=*-Regular,BoldFont=*-SemiBold,
ItalicFont=*-Italic,BoldItalicFont=*-SemiBoldItalic]
\setsansfont{IBMPlexSans}[UprightFont=*-Regular,BoldFont=*-SemiBold,
ItalicFont=*-Italic,BoldItalicFont=*-SemiBoldItalic]
\setmonofont{IBMPlexMono}[UprightFont=*-Regular,BoldFont=*-SemiBold,
ItalicFont=*-Italic,BoldItalicFont=*-SemiBoldItalic,Scale=0.92]
\newfontfamily\plexlight{IBMPlexSans}[UprightFont=*-Light,ItalicFont=*-LightItalic]
\newfontfamily\plexthin{IBMPlexSans}[UprightFont=*-ExtraLight]
\newfontfamily\plexmed{IBMPlexSans}[UprightFont=*-Medium]
\newfontfamily\plexmono{IBMPlexMono}[UprightFont=*-Regular,BoldFont=*-Medium]
\newfontfamily\plexmonolabel{IBMPlexMono}[UprightFont=*-Medium,LetterSpace=14]
\usepackage{newunicodechar}
\newunicodechar{ⁿ}{\textsuperscript{\textit{n}}}
% ---- colour: Carbon greys and one blue
\usepackage[table]{xcolor}
\definecolor{blue60}{HTML}{0F62FE}
\definecolor{blue70}{HTML}{0043CE}
\definecolor{gray100}{HTML}{161616}
\definecolor{gray90}{HTML}{262626}
\definecolor{gray80}{HTML}{393939}
\definecolor{gray70}{HTML}{525252}
\definecolor{gray50}{HTML}{8D8D8D}
\definecolor{gray30}{HTML}{C6C6C6}
\definecolor{gray20}{HTML}{E0E0E0}
\definecolor{gray10}{HTML}{F4F4F4}
\color{gray100}
% ---- page
\usepackage[a4paper,top=28mm,bottom=26mm,inner=26mm,outer=26mm,headsep=10mm,
footskip=12mm]{geometry}
\usepackage{microtype}
\usepackage{ragged2e}
\setlength{\RaggedRightRightskip}{0pt plus 4em}
\AtBeginDocument{\RaggedRight}
\usepackage{tikz}
\newcommand{\twodig}[1]{\ifnum#1<10 0\fi\number#1}
\renewcommand{\thechapter}{\twodig{\value{chapter}}}
% ---- tables: grey header band, hairlines between rows
\usepackage{booktabs,longtable,xltabular,array}
\newcolumntype{L}{>{\raggedright\arraybackslash}X}
\setlength{\LTpre}{8pt}\setlength{\LTpost}{10pt}\setlength{\LTleft}{0pt}\setlength{\LTright}{\fill}
\setlength{\aboverulesep}{0pt}\setlength{\belowrulesep}{0pt}
\setlength{\tabcolsep}{7pt}
\renewcommand{\arraystretch}{1.55}
\arrayrulecolor{gray20}
\newcommand{\thead}[1]{\leavevmode{\plexmed\footnotesize\color{gray100}#1}}
\newcommand{\rowrule}{\arrayrulecolor{gray20}\specialrule{0.4pt}{0pt}{0pt}}
\newcommand{\toprow}{\arrayrulecolor{gray100}\specialrule{0.8pt}{0pt}{0pt}\arrayrulecolor{gray20}}
% ---- code
\usepackage{fancyvrb}
\fvset{fontsize=\small,formatcom=\color{gray100}}
\usepackage[most]{tcolorbox}
\newtcolorbox{codebox}{breakable,enhanced,sharp corners,boxrule=0pt,
colback=gray10,frame hidden,borderline west={2pt}{0pt}{blue60},
left=10pt,right=8pt,top=5pt,bottom=3pt,before skip=8pt,after skip=10pt}
\newcommand{\code}[1]{\leavevmode{\plexmono\color{gray80}#1}}
% ---- lists: small blue squares
\usepackage{enumitem}
\setlist{itemsep=3pt,topsep=4pt,parsep=0pt,leftmargin=1.4em}
\setlist[itemize]{label={\color{blue60}\rule[0.22em]{0.38em}{0.38em}}}
\setlist[enumerate]{label={\plexmono\color{blue60}0\arabic*},
leftmargin=2em}
% ---- headings
\setkomafont{disposition}{\normalfont\color{gray100}}
\setkomafont{section}{\plexmed\large}
\RedeclareSectionCommand[beforeskip=-1.6\baselineskip,afterskip=0.35\baselineskip]{section}
\RedeclareSectionCommand[beforeskip=0pt,afterskip=2.2\baselineskip]{chapter}
\renewcommand*{\chapterformat}{\thechapter}
\renewcommand*{\chapterlinesformat}[3]{%
\parbox[b]{\linewidth}{%
{\plexmonolabel\scriptsize\color{blue60}%
\ifx\relax#2\relax BASYS 3 RISC-V BASIC\else SECTION\ #2\fi\par}
\vspace{3mm}{\color{gray100}\rule{\linewidth}{0.8pt}}\par\vspace{9mm}
\begin{minipage}[t]{0.17\linewidth}
{\plexthin\fontsize{40}{40}\selectfont\color{blue60}#2}
\end{minipage}%
\begin{minipage}[t]{0.83\linewidth}
{\plexlight\fontsize{30}{34}\selectfont\color{gray100}#3\par}
\end{minipage}}}
% ---- running heads: mono caps, quiet
\usepackage[automark]{scrlayer-scrpage}
\clearpairofpagestyles
\renewcommand*{\chaptermarkformat}{\thechapter\enskip/\enskip}
\ihead{\plexmonolabel\fontsize{6.5}{8}\selectfont\color{gray50}BASYS 3 RISC-V BASIC}
\ohead{\plexmonolabel\fontsize{6.5}{8}\selectfont\color{gray50}\MakeUppercase{\leftmark}}
\ofoot*{\plexmono\footnotesize\color{gray100}\thepage}
\ifoot*{\color{blue60}\rule[0.2em]{6mm}{1.2pt}}
\setkomafont{pageheadfoot}{\normalfont}
\setkomafont{pagenumber}{\normalfont}
% ---- contents
\DeclareTOCStyleEntry[beforeskip=1.1em,entryformat=\plexmed,pagenumberformat=\plexmono,
linefill=\hfill,numwidth=2.4em,entrynumberformat=\tocnum]{tocline}{chapter}
\DeclareTOCStyleEntry[indent=2.4em,numwidth=0pt,linefill=\hfill,
entryformat=\color{gray70},pagenumberformat=\plexmono\color{gray70}]{tocline}{section}
\newcommand{\tocnum}[1]{{\plexmono\color{blue60}#1}}
\usepackage[hidelinks,unicode]{hyperref}
\usepackage{bookmark}
\raggedbottom
\widowpenalty=10000\clubpenalty=10000
"""
TITLE = r"""\hypersetup{pdftitle={%(title)s}}
\begin{document}
\begin{titlepage}
\begin{tikzpicture}[remember picture,overlay]
\fill[gray100] (current page.south west) rectangle (current page.north east);
\begin{scope}[shift={(current page.south west)}]
\foreach \x in {0,1,...,21} \draw[gray90,line width=0.3pt] (\x,0) -- (\x,29.7);
\foreach \y in {0,1,...,29} \draw[gray90,line width=0.3pt] (0,\y) -- (21,\y);
\fill[blue60] (2,21) rectangle (3,22);
\draw[gray80,line width=0.4pt] (2,6) -- (19,6);
\node[anchor=north west,inner sep=0,text width=16cm] at (2,20.2)
{\plexlight\fontsize{46}{50}\selectfont\color{white}%(titlewords)s};
\node[anchor=north west,inner sep=0,text width=14cm] at (2,15.7)
{\plexlight\large\color{gray30}%(subtitle)s};
\node[anchor=north west,inner sep=0] at (2,24.6)
{\plexmonolabel\scriptsize\color{blue60}REFERENCE MANUAL};
\node[anchor=north west,inner sep=0,text width=17cm] at (2,5.3)
{\plexmonolabel\scriptsize\color{gray50}RV32IMF\quad/\quad 100 MHZ\quad/\quad
VT220\quad/\quad 320\texttimes240 \& 640\texttimes480\quad/\quad DIGILENT BASYS 3};
\node[anchor=north west,inner sep=0] at (2,3.6)
{\plexmono\footnotesize\color{gray30}barant.com/opensource/basys3};
\node[anchor=north west,inner sep=0] at (2,3.0)
{\plexmono\footnotesize\color{gray50}git.barant.com/barant/Basys3RiscV};
\end{scope}
\end{tikzpicture}
\end{titlepage}
\pagenumbering{roman}
\tableofcontents
\cleardoublepage
\pagenumbering{arabic}
"""
def main(src, dst):
md = open(src, encoding="utf-8").read()
# Code fences indented inside a list item: python-markdown would turn
# them into inline code, so take them out and put a marker in their place.
codeblocks = []
def take(m):
indent = m.group(1)
body = "\n".join(l[len(indent):] if l.startswith(indent) else l
for l in m.group(2).split("\n"))
codeblocks.append(body)
return "%s@@CODE%d@@" % (indent, len(codeblocks) - 1)
md = re.sub(r"^( +)```[^\n]*\n(.*?)\n\1```[ \t]*$", take, md, flags=re.S | re.M)
htm = markdown.markdown(md, extensions=["tables", "fenced_code"])
tb = TreeBuilder()
tb.feed(htm)
title, subtitle, body = Converter(codeblocks).convert(tb.root)
with open(dst, "w", encoding="utf-8") as f:
f.write(PREAMBLE)
f.write(TITLE % {"title": esc(title), "subtitle": subtitle,
"titlewords": " ".join(r"\mbox{%s}" % esc(w) for w in title.split())})
f.write(body)
f.write("\n\\end{document}\n")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
+133 -1
View File
@@ -1,5 +1,6 @@
/* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf /* Single-precision maths for BASIC: sinf cosf tanf atanf expf logf sqrtf
floorf. Range reduction by Cody and Waite, minimax polynomials as in the floorf, and from them asinf acosf atan2f sinhf coshf tanhf asinhf acoshf
atanhf log1pf log10f log2f and an exact fmodf. Range reduction by Cody and Waite, minimax polynomials as in the
Cephes library; good to an ulp or two, which BASIC's 6-7 printed digits Cephes library; good to an ulp or two, which BASIC's 6-7 printed digits
don't show. sqrtf (the FPU's FSQRT.S when there is one) and floorf are don't show. sqrtf (the FPU's FSQRT.S when there is one) and floorf are
exact. (newlib's versions are larger and exact. (newlib's versions are larger and
@@ -190,3 +191,134 @@ float floorf(float x)
else if (u.i << 1) u.f = -1.0f; else if (u.i << 1) u.f = -1.0f;
return u.f; return u.f;
} }
/* ------------------------------------------------- built on the above */
static const float PI_F = 3.14159265358979f, LN2_F = 0.693147180559945f;
/* log(1 + u), accurate for small u: Goldberg's trick, since w - 1 is exact */
float log1pf(float u)
{
float w = 1.0f + u;
if (w == 1.0f) return u;
return logf(w) * (u / (w - 1.0f));
}
float asinf(float x) /* |x| <= 1 */
{
return atanf(x / sqrtf((1.0f - x) * (1.0f + x)));
}
float acosf(float x) /* |x| <= 1 */
{
return 2.0f * atanf(sqrtf((1.0f - x) / (1.0f + x)));
}
float atan2f(float y, float x)
{
float a;
if (x == 0.0f) return y > 0 ? PI_F / 2 : y < 0 ? -PI_F / 2 : 0.0f;
a = atanf(y / x);
if (x < 0) a += y < 0 ? -PI_F : PI_F;
return a;
}
/* e^|x| / 2 for large |x|, without overflowing on the way */
static float half_exp(float a)
{
float h = expf(0.5f * a);
return (0.5f * h) * h;
}
float sinhf(float x)
{
float a = x < 0 ? -x : x, r, z, e;
if (a < 1.0f) { /* the series: no cancellation */
z = a * a;
r = a + a * z * (1.6666667163e-1f + z * (8.3333337680e-3f + z * (1.9841270114e-4f
+ z * (2.7557318845e-6f + z * 2.5052108385e-8f))));
} else if (a < 10.0f) {
e = expf(a);
r = 0.5f * (e - 1.0f / e);
} else r = half_exp(a);
return x < 0 ? -r : r;
}
float coshf(float x)
{
float a = x < 0 ? -x : x, e;
if (a >= 10.0f) return half_exp(a);
e = expf(a);
return 0.5f * (e + 1.0f / e);
}
float tanhf(float x)
{
float a = x < 0 ? -x : x, r;
r = a >= 10.0f ? 1.0f : sinhf(a) / coshf(a);
return x < 0 ? -r : r;
}
float asinhf(float x)
{
float a = x < 0 ? -x : x, r;
if (a > 1e9f) r = logf(a) + LN2_F;
else r = log1pf(a + a * a / (1.0f + sqrtf(1.0f + a * a)));
return x < 0 ? -r : r;
}
float acoshf(float x) /* x >= 1 */
{
float t;
if (x > 1e9f) return logf(x) + LN2_F;
t = x - 1.0f;
return log1pf(t + sqrtf(2.0f * t + t * t));
}
float atanhf(float x) /* |x| < 1 */
{
float a = x < 0 ? -x : x, r;
r = 0.5f * log1pf(2.0f * a / (1.0f - a));
return x < 0 ? -r : r;
}
/* log of x = m * 2^e, m in [sqrt(1/2), sqrt(2)): returns log(m), sets e */
static float log_split(float x, int *e)
{
fbits u = { x };
int k = 0;
if (u.i < 0x00800000) { u.f *= 16777216.0f; k = -24; } /* subnormal */
k += (int)(u.i >> 23) - 127;
u.i = (u.i & 0x007FFFFF) | 0x3F800000; /* [1, 2) */
if (u.f > 1.41421356f) { u.f *= 0.5f; k++; }
*e = k;
return logf(u.f);
}
float log2f(float x) /* x > 0: exact for powers of 2 */
{
int e;
float y = log_split(x, &e);
return y * 1.44269504088896341f + (float)e;
}
float log10f(float x) /* x > 0 */
{
int e;
float y = log_split(x, &e), f = (float)e;
/* log10(2) and log10(e) each split in two, as in Cephes */
return ((f * 2.48745663981195213739e-4f + y * 7.00731903251827651129e-4f)
+ y * 4.3359375e-1f) + f * 3.0078125e-1f;
}
/* exactly x - n*y, n = x/y truncated, by binary long division: each step
subtracts t from r with t <= r < 2t, which is exact */
float fmodf(float x, float y)
{
float r = x < 0 ? -x : x, d = y < 0 ? -y : y, t;
if (d == 0.0f || r < d) return x;
t = d;
while (t <= 0.5f * r) t += t;
for (; t >= d; t *= 0.5f)
if (r >= t) r -= t;
return x < 0 ? -r : r;
}
+169 -57
View File
@@ -1,26 +1,37 @@
/* RISC-V assembler for the monitor (included by monitor.c). /* RISC-V assembler for the monitor (included by monitor.c).
* *
* The syntax the disassembler prints. A line is * GNU as syntax, as the disassembler prints it. A line is
* [line number] [label:] [instruction or directive] [; comment] * [line number] [label:] [instruction or directive] [# comment]
* (the line number is there when the source was typed into BASIC). Numbers: * (the line number is there when the source was typed into BASIC; ; also
* 123, 0FFH, $FF, 0x1F, 1010B, 'A'; $ alone is the current address. * starts a comment). Case doesn't matter: lines are upper-cased outside
* Expressions use + - * / & | and parentheses. Registers are X0-X31 or their * quotes before they are read. Numbers: 123, 0x1F, 0b1010, 'A', '\n'; . is
* ABI names (ZERO RA SP GP TP T0-T6 S0-S11 FP A0-A7); memory operands are * the current address. Expressions use + - * / & | ^ << >> ~ and parentheses,
* offset(register). CSRs by name (MSTATUS, MEPC, CYCLE...) or number. * and %hi(x) and %lo(x), the LUI/AUIPC and ADDI parts of x. Registers are
* x0-x31 or their ABI names (zero ra sp gp tp t0-t6 s0-s11 fp a0-a7); memory
* operands are offset(register). CSRs by name (mstatus, mepc, cycle...) or
* number.
* *
* Instructions: RV32I and M, CSRRW..CSRRCI, ECALL EBREAK MRET MNRET WFI FENCE * Instructions: RV32I and M, csrrw..csrrci, ecall ebreak mret mnret wfi fence
* FENCE.I, and the usual short forms: NOP LI LA MV NOT NEG SEQZ SNEZ SLTZ SGTZ * fence.i, and the usual short forms: nop li la mv not neg seqz snez sltz sgtz
* J JR JAL target RET CALL BEQZ BNEZ BLEZ BGEZ BLTZ BGTZ BGT BLE BGTU BLEU CSRR * j jr jal target ret call beqz bnez blez bgez bltz bgtz bgt ble bgtu bleu
* CSRW CSRS CSRC CSRWI CSRSI CSRCI. * csrr csrw csrs csrc csrwi csrsi csrci.
* F: FLW FSW FMADD.S FMSUB.S FNMSUB.S FNMADD.S FADD.S FSUB.S FMUL.S FDIV.S * F: flw fsw fmadd.s fmsub.s fnmsub.s fnmadd.s fadd.s fsub.s fmul.s fdiv.s
* FSQRT.S FSGNJ.S FSGNJN.S FSGNJX.S FMIN.S FMAX.S FEQ.S FLT.S FLE.S FCVT.W.S * fsqrt.s fsgnj.s fsgnjn.s fsgnjx.s fmin.s fmax.s feq.s flt.s fle.s fcvt.w.s
* FCVT.WU.S FCVT.S.W FCVT.S.WU FMV.X.W FMV.W.X FCLASS.S and FMV.S FNEG.S * fcvt.wu.s fcvt.s.w fcvt.s.wu fmv.x.w fmv.w.x fclass.s and fmv.s fneg.s
* FABS.S; float registers F0-F31 or FT0-FT11 FS0-FS11 FA0-FA7; a rounding * fabs.s; float registers f0-f31 or ft0-ft11 fs0-fs11 fa0-fa7; a rounding
* mode (RNE RTZ RDN RUP RMM DYN) may follow the operands, DYN if not. LI is one instruction for a constant of * mode (rne rtz rdn rup rmm dyn) may follow the operands, dyn if not. li is
* -2048..2047 known by then, else LUI and ADDI; LA is AUIPC and ADDI. * one instruction for a constant of -2048..2047 known by then, else lui and
* Directives: ORG, EQU (NAME EQU value), DB/DEFB/DEFM (numbers and "strings"), * addi; la is auipc and addi.
* DH (16 bits), DW/DEFW (32 bits), DS/DEFS n, ALIGN n, END. Instructions must * Directives: .org, .equ/.set name, value (or name = value), .byte, .half
* be on a 4-byte boundary. Labels are up to 8 characters. * (.short .2byte), .word (.long .4byte), .ascii, .string/.asciz (a 0 after
* each string; \n \r \t \0 \\ \" escapes), .space/.skip/.zero n, .align n
* and .p2align n (to 2^n), .balign n (to n), .end; .text .data .section .globl
* .global .option and .type are accepted and ignored. Instructions must be on
* a 4-byte boundary. Labels are up to 8 characters (more are allowed; the
* first 8 count).
* The older forms still work: ORG, NAME EQU value, DB/DEFB/DEFM (no escapes),
* DH, DW/DEFW, DS/DEFS n, ALIGN n (to n), END; numbers 0FFH, $FF, 1010B; $
* for the current address.
*/ */
#define MAXSYM 200 #define MAXSYM 200
struct sym { char name[8]; u32 val; u16 line; }; struct sym { char name[8]; u32 val; u16 line; };
@@ -42,6 +53,28 @@ static void a_sp(void) { while (*ap == ' ' || *ap == '\t') ap++; }
static u8 a_alpha(char c) { return (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; } static u8 a_alpha(char c) { return (c >= 'A' && c <= 'Z') || c == '_' || c == '.'; }
static u8 a_alnum(char c) { return a_alpha(c) || (c >= '0' && c <= '9'); } static u8 a_alnum(char c) { return a_alpha(c) || (c >= '0' && c <= '9'); }
/* the length of the character constant at p ('A' or '\N'), 0 if none */
static u8 a_chlen(const char *p)
{
if (p[0] != '\'') return 0;
if (p[1] == '\\' && p[2] && p[3] == '\'') return 4;
if (p[1] && p[2] == '\'') return 3;
return 0;
}
/* the character an escape stands for: \N \R \T \0 \E, else itself */
static u8 a_esc(char c)
{
switch (c) {
case 'n': case 'N': return 10;
case 'r': case 'R': return 13;
case 't': case 'T': return 9;
case '0': return 0;
case 'e': case 'E': return 27;
}
return c;
}
static void a_emit(u8 b) static void a_emit(u8 b)
{ {
if (a_pass == 2) { if (a_pass == 2) {
@@ -85,15 +118,19 @@ static void a_name(char *n)
/* ---------------------------------------------------------- expressions */ /* ---------------------------------------------------------- expressions */
static u32 a_expr(void); static u32 a_expr(void);
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
static u32 a_number(void) static u32 a_number(void)
{ {
const char *s = ap; const char *s = ap;
u32 v = 0; u32 v = 0;
u8 base = 10, n = 0; u8 base = 10, n = 0;
while (a_alnum(s[n])) n++;
if (s[0] == '0' && s[1] == 'X') { base = 16; s += 2; } if (s[0] == '0' && s[1] == 'X') { base = 16; s += 2; }
else if (s[0] == '0' && s[1] == 'B' && s[n - 1] != 'H') { base = 2; s += 2; }
else { else {
while (a_alnum(s[n])) n++;
if (s[n - 1] == 'H') base = 16; if (s[n - 1] == 'H') base = 16;
else if (s[n - 1] == 'B') { else if (s[n - 1] == 'B') {
u8 k; u8 k;
@@ -104,7 +141,7 @@ static u32 a_number(void)
for (; a_alnum(*s); s++) { for (; a_alnum(*s); s++) {
char c = *s; char c = *s;
u8 d = c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : 99; u8 d = c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : 99;
if ((c == 'H' && base == 16) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; } if ((c == 'H' && base == 16 && !a_alnum(s[1])) || (c == 'B' && base == 2 && !a_alnum(s[1]))) { s++; break; }
if (d >= base) { a_fail("BAD NUMBER"); break; } if (d >= base) { a_fail("BAD NUMBER"); break; }
v = v * base + d; v = v * base + d;
} }
@@ -118,6 +155,15 @@ static u32 a_factor(void)
a_sp(); a_sp();
if (*ap == '-') { ap++; return -a_factor(); } if (*ap == '-') { ap++; return -a_factor(); }
if (*ap == '+') { ap++; return a_factor(); } if (*ap == '+') { ap++; return a_factor(); }
if (*ap == '~') { ap++; return ~a_factor(); }
if (*ap == '%') { /* %HI(x), %LO(x) */
u8 hi = !strncmp(ap + 1, "HI(", 3);
if (!hi && strncmp(ap + 1, "LO(", 3)) { a_fail("BAD EXPRESSION"); return 0; }
ap += 3;
v = a_factor();
return hi ? hi20(v) : (u32)lo12(v);
}
if (*ap == '.' && !a_alnum(ap[1])) { ap++; return a_pc; }
if (*ap == '(') { if (*ap == '(') {
ap++; ap++;
v = a_expr(); v = a_expr();
@@ -125,7 +171,8 @@ static u32 a_factor(void)
if (*ap == ')') ap++; else a_fail("MISSING )"); if (*ap == ')') ap++; else a_fail("MISSING )");
return v; return v;
} }
if (*ap == '\'' && ap[1] && ap[2] == '\'') { v = (u8)ap[1]; ap += 3; return v; } if (a_chlen(ap) == 4) { v = a_esc(ap[2]); ap += 4; return v; }
if (a_chlen(ap) == 3) { v = (u8)ap[1]; ap += 3; return v; }
if (*ap == '$') { if (*ap == '$') {
ap++; ap++;
if ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F')) { if ((*ap >= '0' && *ap <= '9') || (*ap >= 'A' && *ap <= 'F')) {
@@ -174,6 +221,9 @@ static u32 a_expr(void)
else if (*ap == '-') { ap++; v -= a_term(); } else if (*ap == '-') { ap++; v -= a_term(); }
else if (*ap == '&') { ap++; v &= a_term(); } else if (*ap == '&') { ap++; v &= a_term(); }
else if (*ap == '|') { ap++; v |= a_term(); } else if (*ap == '|') { ap++; v |= a_term(); }
else if (*ap == '^') { ap++; v ^= a_term(); }
else if (*ap == '<' && ap[1] == '<') { ap += 2; v <<= a_term(); }
else if (*ap == '>' && ap[1] == '>') { ap += 2; v >>= a_term(); }
else return v; else return v;
} }
} }
@@ -192,7 +242,8 @@ static void a_split(void)
const char *s = ap; const char *s = ap;
u8 d = 0, q = 0, len; u8 d = 0, q = 0, len;
while (*ap && (d || q || *ap != ',')) { while (*ap && (d || q || *ap != ',')) {
if (*ap == '\'' && !q && ap[1] && ap[2] == '\'') ap += 2; if (!q && a_chlen(ap)) ap += a_chlen(ap) - 1;
else if (q && *ap == '\\' && ap[1]) ap++;
else if (*ap == '"') q = !q; else if (*ap == '"') q = !q;
else if (*ap == '(') d++; else if (*ap == '(') d++;
else if (*ap == ')' && d) d--; else if (*ap == ')' && d) d--;
@@ -315,9 +366,6 @@ static u32 enc_u(u32 base, u8 rd, u32 imm)
if (a_pass == 2 && imm > 0xFFFFF) a_fail("VALUE OUT OF RANGE"); if (a_pass == 2 && imm > 0xFFFFF) a_fail("VALUE OUT OF RANGE");
return base | rd << 7 | (imm & 0xFFFFF) << 12; return base | rd << 7 | (imm & 0xFFFFF) << 12;
} }
/* the LUI/AUIPC part and the ADDI part of a 32-bit value */
static u32 hi20(u32 v) { return (v + 0x800) >> 12 & 0xFFFFF; }
static i32 lo12(u32 v) { return sx(v, 12); }
/* ----------------------------------------------------------------- F */ /* ----------------------------------------------------------------- F */
static void a_need(u8 n); static void a_need(u8 n);
@@ -385,7 +433,7 @@ static void a_finstr(const struct fins *t)
u32 b = t->base; u32 b = t->base;
i32 off; i32 off;
u8 r, s; u8 r, s;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE ALIGN 4"); return; } if (a_pc & 3) { a_fail("NOT ON A WORD: USE .ALIGN 2"); return; }
switch (t->f) { switch (t->f) {
case G_LD: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_i(b, r, s, off)); return; case G_LD: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_i(b, r, s, off)); return;
case G_ST: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_s(b, s, r, off)); return; case G_ST: a_need(2); r = a_freg(0); s = a_mem(1, &off); a_emit32(enc_s(b, s, r, off)); return;
@@ -413,9 +461,9 @@ static void a_finstr(const struct fins *t)
enum { enum {
F_R, F_I, F_SH, F_LD, F_ST, F_B, F_U, F_JAL, F_JALR, F_CSR, F_CSRI, F_FIX, F_R, F_I, F_SH, F_LD, F_ST, F_B, F_U, F_JAL, F_JALR, F_CSR, F_CSRI, F_FIX,
P_LI, P_LA, P_MV, P_NOT, P_NEG, P_SEQZ, P_SNEZ, P_SLTZ, P_SGTZ, P_J, P_JR, P_RET, P_LI, P_LA, P_MV, P_NOT, P_NEG, P_SEQZ, P_SNEZ, P_SLTZ, P_SGTZ, P_J, P_JR, P_RET,
P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI P_CALL, P_BZ, P_BZS, P_BSW, P_CSRR, P_CSRW, P_CSRWI, P_FR, P_FS
}; };
struct ins { char name[8]; u8 f; u32 base; }; struct ins { char name[7]; u8 f; u32 base; }; /* 12 bytes: a 7-letter name has no 0 */
static const struct ins itab[] = { static const struct ins itab[] = {
{ "ADD", F_R, 0x00000033 }, { "SUB", F_R, 0x40000033 }, { "SLL", F_R, 0x00001033 }, { "ADD", F_R, 0x00000033 }, { "SUB", F_R, 0x40000033 }, { "SLL", F_R, 0x00001033 },
{ "SLT", F_R, 0x00002033 }, { "SLTU", F_R, 0x00003033 }, { "XOR", F_R, 0x00004033 }, { "SLT", F_R, 0x00002033 }, { "SLTU", F_R, 0x00003033 }, { "XOR", F_R, 0x00004033 },
@@ -450,6 +498,9 @@ static const struct ins itab[] = {
{ "CSRR", P_CSRR, 0 }, { "CSRW", P_CSRW, 0x00001073 }, { "CSRS", P_CSRW, 0x00002073 }, { "CSRR", P_CSRR, 0 }, { "CSRW", P_CSRW, 0x00001073 }, { "CSRS", P_CSRW, 0x00002073 },
{ "CSRC", P_CSRW, 0x00003073 }, { "CSRWI", P_CSRWI, 0x00005073 }, { "CSRC", P_CSRW, 0x00003073 }, { "CSRWI", P_CSRWI, 0x00005073 },
{ "CSRSI", P_CSRWI, 0x00006073 }, { "CSRCI", P_CSRWI, 0x00007073 }, { "CSRSI", P_CSRWI, 0x00006073 }, { "CSRCI", P_CSRWI, 0x00007073 },
/* the float CSRs: read (CSRR), and write ([rd,] rs: CSRRW) */
{ "FRFLAGS", P_FR, 0x00102073 }, { "FRRM", P_FR, 0x00202073 }, { "FRCSR", P_FR, 0x00302073 },
{ "FSFLAGS", P_FS, 0x00101073 }, { "FSRM", P_FS, 0x00201073 }, { "FSCSR", P_FS, 0x00301073 },
}; };
#define NINS (sizeof itab / sizeof itab[0]) #define NINS (sizeof itab / sizeof itab[0])
@@ -460,7 +511,7 @@ static void a_instr(const struct ins *t)
u32 b = t->base, v; u32 b = t->base, v;
i32 off; i32 off;
u8 rd, rs; u8 rd, rs;
if (a_pc & 3) { a_fail("NOT ON A WORD: USE ALIGN 4"); return; } if (a_pc & 3) { a_fail("NOT ON A WORD: USE .ALIGN 2"); return; }
switch (t->f) { switch (t->f) {
case F_R: a_need(3); a_emit32(enc_r(b, a_reg(0), a_reg(1), a_reg(2))); return; case F_R: a_need(3); a_emit32(enc_r(b, a_reg(0), a_reg(1), a_reg(2))); return;
case F_I: a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return; case F_I: a_need(3); a_emit32(enc_i(b, a_reg(0), a_reg(1), (i32)a_imm(2))); return;
@@ -496,6 +547,8 @@ static void a_instr(const struct ins *t)
v = a_imm(1); v = a_imm(1);
if (!a_undef && !a_fwd && (i32)v >= -2048 && (i32)v <= 2047) { if (!a_undef && !a_fwd && (i32)v >= -2048 && (i32)v <= 2047) {
a_emit32(enc_i(0x13, rd, 0, (i32)v)); a_emit32(enc_i(0x13, rd, 0, (i32)v));
} else if (!a_undef && !a_fwd && !(v & 0xFFF)) {
a_emit32(enc_u(0x37, rd, v >> 12)); /* LUI alone, as GNU as does */
} else { } else {
a_emit32(enc_u(0x37, rd, hi20(v))); a_emit32(enc_u(0x37, rd, hi20(v)));
a_emit32(enc_i(0x13, rd, rd, lo12(v))); a_emit32(enc_i(0x13, rd, rd, lo12(v)));
@@ -524,6 +577,10 @@ static void a_instr(const struct ins *t)
case P_BSW: a_need(3); rs = a_reg(0); a_emit32(enc_b(b, a_reg(1), rs, a_imm(2))); return; case P_BSW: a_need(3); rs = a_reg(0); a_emit32(enc_b(b, a_reg(1), rs, a_imm(2))); return;
case P_CSRR: a_need(2); a_emit32(0x2073 | a_reg(0) << 7 | (u32)a_csr(1) << 20); return; case P_CSRR: a_need(2); a_emit32(0x2073 | a_reg(0) << 7 | (u32)a_csr(1) << 20); return;
case P_CSRW: a_need(2); a_emit32(b | a_reg(1) << 15 | (u32)a_csr(0) << 20); return; case P_CSRW: a_need(2); a_emit32(b | a_reg(1) << 15 | (u32)a_csr(0) << 20); return;
case P_FR: a_need(1); a_emit32(b | a_reg(0) << 7); return;
case P_FS:
if (a_nops == 1) { a_emit32(b | a_reg(0) << 15); return; }
a_need(2); a_emit32(b | a_reg(0) << 7 | a_reg(1) << 15); return;
case P_CSRWI: case P_CSRWI:
a_need(2); a_need(2);
v = a_imm(1); v = a_imm(1);
@@ -533,15 +590,24 @@ static void a_instr(const struct ins *t)
} }
} }
/* DB/DH/DW items: numbers and (for DB) strings */ /* data items: numbers, and for bytes "strings". str: 1 strings with
static void a_data(u8 size) escapes (.ascii), 2 the same with a 0 after each (.string); 0 DB's, kept
as they are. */
static void a_data(u8 size, u8 str)
{ {
for (;;) { for (;;) {
a_sp(); a_sp();
if (*ap == '"' && size == 1) { if (*ap == '"' && size == 1) {
ap++; ap++;
while (*ap && *ap != '"') a_emit(*ap++); while (*ap && *ap != '"') {
if (str && *ap == '\\' && ap[1]) { a_emit(a_esc(ap[1])); ap += 2; }
else a_emit(*ap++);
}
if (*ap) ap++; if (*ap) ap++;
if (str == 2) a_emit(0);
} else if (str) {
a_fail("BAD STRING");
return;
} else { } else {
u32 v = a_expr(); u32 v = a_expr();
u8 k; u8 k;
@@ -556,20 +622,37 @@ static void a_data(u8 size)
static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); } static u8 is_w(const char *w, const char *s) { return !strncmp(w, s, 8); }
/* directives, and the old names that mean the same */
enum { D_EQU = 1, D_SET, D_ORG, D_END, D_DB, D_ASCII, D_STRING, D_DH, D_DW, D_DS, D_SPACE,
D_ALIGN, D_P2ALIGN, D_IGNORE };
static const struct { char n[8]; u8 d; } dtab[] = {
{ "EQU", D_EQU }, { ".EQU", D_SET }, { ".SET", D_SET }, { "ORG", D_ORG }, { ".ORG", D_ORG },
{ "END", D_END }, { ".END", D_END }, { "DB", D_DB }, { "DEFB", D_DB }, { "DEFM", D_DB },
{ ".BYTE", D_DB }, { ".ASCII", D_ASCII }, { ".STRING", D_STRING }, { ".ASCIZ", D_STRING },
{ "DH", D_DH }, { ".HALF", D_DH }, { ".SHORT", D_DH }, { ".2BYTE", D_DH }, { "DW", D_DW },
{ "DEFW", D_DW }, { ".WORD", D_DW }, { ".LONG", D_DW }, { ".4BYTE", D_DW }, { "DS", D_DS },
{ "DEFS", D_DS }, { ".SPACE", D_SPACE }, { ".SKIP", D_SPACE }, { ".ZERO", D_SPACE },
{ "ALIGN", D_ALIGN }, { ".BALIGN", D_ALIGN }, { ".ALIGN", D_P2ALIGN }, { ".P2ALIGN", D_P2ALIGN },
{ ".TEXT", D_IGNORE }, { ".DATA", D_IGNORE }, { ".SECTION", D_IGNORE }, { ".GLOBL", D_IGNORE },
{ ".GLOBAL", D_IGNORE }, { ".OPTION", D_IGNORE }, { ".TYPE", D_IGNORE }, { "", 0 }
};
/* Assemble one source line (uppercase except in quotes). */ /* Assemble one source line (uppercase except in quotes). */
static void a_line(char *s) static void a_line(char *s)
{ {
char w[8], lab[8], fm[12]; char w[8], lab[8], fm[12];
const char *mn; const char *mn;
u8 has_lab = 0, q = 0; u8 has_lab = 0, q = 0, d;
u16 m; u16 m;
u32 n, f;
char *c; char *c;
a_err = 0; a_err = 0;
/* cut the comment */ /* cut the comment */
for (c = s; *c; c++) { for (c = s; *c; c++) {
if (*c == '"') q = !q; if (q && *c == '\\' && c[1]) c++;
else if (*c == '\'' && !q && c[1] && c[2] == '\'') c += 2; else if (*c == '"') q = !q;
else if (*c == ';' && !q) { *c = 0; break; } else if (!q && a_chlen(c)) c += a_chlen(c) - 1;
else if ((*c == ';' || *c == '#') && !q) { *c = 0; break; }
} }
ap = s; ap = s;
a_sp(); a_sp();
@@ -593,30 +676,58 @@ static void a_line(char *s)
mn = ap; mn = ap;
a_name(w); a_name(w);
a_sp(); a_sp();
} else if (!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) { } else if ((!strncmp(ap, "EQU", 3) && !a_alnum(ap[3])) || (*ap == '=' && w[0] != '.')) {
memcpy(lab, w, 8); has_lab = 1; memcpy(lab, w, 8); has_lab = 1; /* NAME EQU value, NAME = value */
ap += *ap == '=' ? 1 : 3;
memcpy(w, "EQU\0\0\0\0\0", 8); memcpy(w, "EQU\0\0\0\0\0", 8);
ap += 3;
} }
if (is_w(w, "EQU")) { for (m = 0; dtab[m].d && !is_w(w, dtab[m].n); m++);
u32 v = a_expr(); d = dtab[m].d;
if (d == D_SET) { /* .EQU NAME, value */
if (!a_alpha(*ap)) { a_fail("EQU NEEDS A NAME"); return; }
a_name(lab); has_lab = 1;
a_sp();
if (*ap == ',') ap++;
d = D_EQU;
}
if (d == D_EQU) {
n = a_expr();
if (!has_lab) a_fail("EQU NEEDS A NAME"); if (!has_lab) a_fail("EQU NEEDS A NAME");
else if (a_undef && a_pass == 1) a_fail("EQU BEFORE ITS VALUE"); else if (a_undef && a_pass == 1) a_fail("EQU BEFORE ITS VALUE");
else sym_def(lab, v); else sym_def(lab, n);
return; return;
} }
if (has_lab) sym_def(lab, a_pc); if (has_lab) sym_def(lab, a_pc);
if (is_w(w, "ORG")) { a_pc = a_expr(); return; } switch (d) {
if (is_w(w, "END")) { a_end = 1; return; } case D_ORG: a_pc = a_expr(); return;
if (is_w(w, "DB") || is_w(w, "DEFB") || is_w(w, "DEFM")) { a_data(1); return; } case D_END: a_end = 1; return;
if (is_w(w, "DH")) { a_data(2); return; } case D_DB: a_data(1, 0); return;
if (is_w(w, "DW") || is_w(w, "DEFW")) { a_data(4); return; } case D_ASCII: a_data(1, 1); return;
if (is_w(w, "DS") || is_w(w, "DEFS")) { a_pc += a_expr(); return; } case D_STRING: a_data(1, 2); return;
if (is_w(w, "ALIGN")) { case D_DH: a_data(2, 0); return;
u32 n = a_expr(); case D_DW: a_data(4, 0); return;
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2"); case D_DS: a_pc += a_expr(); return;
else while (a_pc & (n - 1)) a_emit(0); case D_SPACE: /* n [, fill] */
n = a_expr(); f = 0;
a_sp();
if (*ap == ',') { ap++; f = a_expr(); }
while (n--) a_emit(f);
return; return;
case D_ALIGN: case D_P2ALIGN:
n = a_expr();
if (d == D_P2ALIGN) n = n < 32 ? 1u << n : 0; /* .ALIGN, .P2ALIGN: to 2^n */
a_sp();
if (!n || (n & (n - 1))) a_fail("ALIGN TO A POWER OF 2");
else if (*ap == ',') { /* n, fill */
ap++;
f = a_expr();
while (a_pc & (n - 1)) a_emit(f);
} else { /* zeros to a word, then NOPs */
while (a_pc & (n - 1) & 3) a_emit(0);
while (a_pc & (n - 1)) a_emit32(0x13);
}
return;
case D_IGNORE: return;
} }
/* F instructions, whose names can be longer than 8 */ /* F instructions, whose names can be longer than 8 */
for (m = 0; m < 11 && a_alnum(mn[m]); m++) fm[m] = mn[m]; for (m = 0; m < 11 && a_alnum(mn[m]); m++) fm[m] = mn[m];
@@ -629,7 +740,7 @@ static void a_line(char *s)
return; return;
} }
for (m = 0; m < NINS; m++) for (m = 0; m < NINS; m++)
if (!strncmp(w, itab[m].name, 8)) break; if (!strncmp(w, itab[m].name, 7) && !w[7]) break;
if (m == NINS) { a_fail("UNKNOWN INSTRUCTION"); return; } if (m == NINS) { a_fail("UNKNOWN INSTRUCTION"); return; }
a_split(); a_split();
if (a_err) return; if (a_err) return;
@@ -641,8 +752,9 @@ static void a_upper(char *s)
{ {
u8 q = 0; u8 q = 0;
for (; *s; s++) { for (; *s; s++) {
if (*s == '"') q = !q; if (q && *s == '\\' && s[1]) s++;
else if (*s == '\'' && !q && s[1] && s[2] == '\'') s += 2; else if (*s == '"') q = !q;
else if (!q && a_chlen(s)) s += a_chlen(s) - 1;
else if (!q && *s >= 'a' && *s <= 'z') *s -= 32; else if (!q && *s >= 'a' && *s <= 'z') *s -= 32;
if (*s == '\t') *s = ' '; if (*s == '\t') *s = ' ';
} }
+2 -1
View File
@@ -5,7 +5,8 @@ set -e
cd "$(dirname "$0")" cd "$(dirname "$0")"
source ../scripts/rv_env.sh source ../scripts/rv_env.sh
mkdir -p out mkdir -p out
CFLAGS="$RV_ARCH -Os -ffunction-sections -fdata-sections -fno-common -Wall -I../include" # -msave-restore: shared register saving, 2 KB smaller (the ROM is 32 KB)
CFLAGS="$RV_ARCH -Os -msave-restore -ffunction-sections -fdata-sections -fno-common -Wall -I../include"
${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S ${RV_PREFIX}gcc $CFLAGS -c -o out/crt0.o crt0.S
${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c ${RV_PREFIX}gcc $CFLAGS -c -o out/monitor.o monitor.c
${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c ${RV_PREFIX}gcc $CFLAGS -c -o out/string.o ../lib/string.c
Binary file not shown.
+224 -56
View File
@@ -80,14 +80,13 @@ static void s_udec(u32 v)
s_str(q); s_str(q);
} }
static void s_dec(i32 v) { if (v < 0) { s_ch('-'); v = -v; } s_udec((u32)v); } static void s_dec(i32 v) { if (v < 0) { s_ch('-'); v = -v; } s_udec((u32)v); }
/* assembler style: 1F0H, 0A200H (a leading 0 when it starts with a letter) */ /* GNU style: 0x1f0 (disasm() lower-cases it) */
static void s_lit(u32 v) static void s_lit(u32 v)
{ {
u8 n = 1; u8 n = 1;
while (n < 8 && v >> (4 * n)) n++; while (n < 8 && v >> (4 * n)) n++;
if ((v >> (4 * (n - 1)) & 15) >= 10) s_ch('0'); s_str("0X");
s_hex(v, n); s_hex(v, n);
s_ch('H');
} }
/* ---------------------------------------------------------- disassembler */ /* ---------------------------------------------------------- disassembler */
@@ -129,7 +128,17 @@ static const char *const csrin[8] = { 0, "CSRRW", "CSRRS", "CSRRC", 0, "CSRRWI",
/* F: registers F0-F31, the rounding mode after the operands unless DYN */ /* F: registers F0-F31, the rounding mode after the operands unless DYN */
static const char *const rmn[8] = { "RNE", "RTZ", "RDN", "RUP", "RMM", 0, 0, "DYN" }; static const char *const rmn[8] = { "RNE", "RTZ", "RDN", "RUP", "RMM", 0, 0, "DYN" };
static void s_freg(u8 r) { s_ch('F'); s_udec(r); } /* float registers by their ABI names, as objdump shows them: ft0-7 fs0-1
fa0-7 fs2-11 ft8-11 */
static void s_freg(u8 r)
{
s_ch('F');
if (r < 8) { s_ch('T'); s_udec(r); }
else if (r < 10) { s_ch('S'); s_udec(r - 8); }
else if (r < 18) { s_ch('A'); s_udec(r - 10); }
else if (r < 28) { s_ch('S'); s_udec(r - 16); }
else { s_ch('T'); s_udec(r - 20); }
}
static void s_rm(u8 m) { if (m != 7) { s_c(); s_str(rmn[m]); } } static void s_rm(u8 m) { if (m != 7) { s_c(); s_str(rmn[m]); } }
/* An F instruction (not FLW/FSW); 0 if it isn't one */ /* An F instruction (not FLW/FSW); 0 if it isn't one */
@@ -194,8 +203,8 @@ static u8 dis_f(u32 w)
return 0; return 0;
} }
/* One instruction at a into line (at lp); returns its length, 4. */ /* One instruction at a into line (at lp), in capitals; returns its length, 4. */
static u8 disasm(u32 a) static u8 dis_up(u32 a)
{ {
u32 w = rd32(a); u32 w = rd32(a);
u8 op = w & 0x7F, rd = w >> 7 & 31, f3 = w >> 12 & 7, rs1 = w >> 15 & 31, rs2 = w >> 20 & 31; u8 op = w & 0x7F, rd = w >> 7 & 31, f3 = w >> 12 & 7, rs1 = w >> 15 & 31, rs2 = w >> 20 & 31;
@@ -306,10 +315,20 @@ static u8 disasm(u32 a)
return 4; return 4;
} }
} }
s_mn("DW"); s_lit(w); s_mn(".WORD"); s_lit(w);
return 4; return 4;
} }
/* One instruction at a into line (at lp), in lower case as GNU tools show
it; returns its length, 4. */
static u8 disasm(u32 a)
{
char *s = lp;
u8 n = dis_up(a);
for (; s < lp; s++) if (*s >= 'A' && *s <= 'Z') *s += 32;
return n;
}
#ifndef __riscv #ifndef __riscv
#include "asm.c" #include "asm.c"
@@ -392,26 +411,41 @@ int main(int argc, char **argv)
/* ------------------------------------------------------------- screen */ /* ------------------------------------------------------------- screen */
static void puts_(const char *s) { while (*s) putc_(*s++); } static void puts_(const char *s) { while (*s) putc_(*s++); }
static void esc_n(u8 n) /* 1 to 3 digits */
{
if (n >= 100) putc_('0' + n / 100);
if (n >= 10) putc_('0' + n / 10 % 10);
putc_('0' + n % 10);
}
static void at(u8 r, u8 c) /* r, c from 0 */ static void at(u8 r, u8 c) /* r, c from 0 */
{ {
char b[12], *p = b; putc_(27); putc_('[');
*p++ = 27; *p++ = '['; esc_n(r + 1); putc_(';'); esc_n(c + 1); putc_('H');
if (r >= 9) *p++ = '0' + (r + 1) / 10;
*p++ = '0' + (r + 1) % 10; *p++ = ';';
if (c >= 9) *p++ = '0' + (c + 1) / 10;
*p++ = '0' + (c + 1) % 10; *p++ = 'H'; *p = 0;
puts_(b);
} }
static void sgr(const char *s) { putc_(27); putc_('['); puts_(s); putc_('m'); } static void sgr(const char *s) { putc_(27); putc_('['); puts_(s); putc_('m'); }
static void flush_line(void) { *lp = 0; puts_(line); } static void flush_line(void) { *lp = 0; puts_(line); }
static void clr_eol(void) { puts_("\033[K"); } static void clr_eol(void) { puts_("\033[K"); }
/* --------------------------------------------------------------- state */ /* --------------------------------------------------------------- state */
#define REG_TOP 2 /* six rows of registers */ /* The screen's layout: 80x32 (narrow) or 132x64 (wide, everything at once),
#define DIS_ROWS 12 chosen from port 0 bit 2 when the monitor is entered. */
#define MEM_ROWS 6 #define REG_TOP 2 /* narrow: six rows of registers */
#define DIS_TOP 9 static u8 wide;
#define MEM_TOP 22 static u8 DIS_ROWS, MEM_ROWS, DIS_TOP, MEM_TOP, STK_COL, HELP_ROW, CMD_ROW, MSG_COL;
static void layout(void)
{
wide = con_stat & 4;
DIS_ROWS = wide ? 24 : 12;
MEM_ROWS = wide ? 14 : 6;
DIS_TOP = wide ? 22 : 9;
MEM_TOP = wide ? 48 : 22;
STK_COL = wide ? 66 : 54;
HELP_ROW = wide ? 62 : 28;
CMD_ROW = wide ? 63 : 29;
MSG_COL = wide ? 66 : 40;
}
static u32 px[32], pf[32]; /* the registers when last shown */
static u8 pv; /* ... saved */
static u32 dis_a; /* first line of the disassembly window */ static u32 dis_a; /* first line of the disassembly window */
static u32 mem_a; /* first line of the memory window */ static u32 mem_a; /* first line of the memory window */
@@ -435,9 +469,125 @@ static void s_rv(const char *n, u32 v)
s_str(n); s_ch(' '); s_h8(v); s_ch(' '); s_str(n); s_ch(' '); s_h8(v); s_ch(' ');
} }
/* a float's value in decimal, " 1.500000E+00", from its bits, without the
FPU (the monitor leaves it alone): 7 digits, the last may be 1 out */
static void s_fdec(u32 b)
{
u32 m = b & 0x7FFFFF, x;
i32 e = b >> 23 & 255, d = 0;
u8 k;
char g[11];
s_ch(b >> 31 ? '-' : ' ');
if (e == 255) { s_str(m ? "NAN" : "INF"); return; }
if (e) m |= 0x800000; else e = 1;
if (!m) { s_str("0"); return; }
x = m;
for (e -= 150; e > 0; e--) /* x * 2^e * 10^d, x kept large */
if (x < 0x80000000u) x <<= 1; else { x /= 10; d++; e++; }
for (; e < 0; e++)
if (x < 0x19999999u) { x *= 10; d--; e--; } else x >>= 1;
while (x >= 100000000u) { x = (x + (x >= 1000000000u ? 0 : 5)) / 10; d++; } /* 8 digits */
x = (x + 5) / 10; d++; /* 7, rounded */
if (x >= 10000000u) { x /= 10; d++; }
for (k = 0; k < 7; k++) { g[6 - k] = '0' + x % 10; x /= 10; }
d += 6;
s_ch(g[0]); s_ch('.');
for (k = 1; k < 7; k++) s_ch(g[k]);
s_ch('E'); s_ch(d < 0 ? '-' : '+');
if (d < 0) d = -d;
s_ch('0' + d / 10); s_ch('0' + d % 10);
}
static u32 csr_mepc(void) { u32 v; __asm__ volatile("csrr %0, mepc" : "=r"(v)); return v; }
static u32 csr_mstatus(void) { u32 v; __asm__ volatile("csrr %0, mstatus" : "=r"(v)); return v; }
static u32 csr_mcause(void) { u32 v; __asm__ volatile("csrr %0, mcause" : "=r"(v)); return v; }
static u32 csr_mtval(void) { u32 v; __asm__ volatile("csrr %0, mtval" : "=r"(v)); return v; }
static void s_cycle(void)
{
u32 h, l;
__asm__ volatile("csrr %0, cycleh; csrr %1, cycle" : "=r"(h), "=r"(l));
s_h8(h); s_h8(l);
}
static void s_instret(void)
{
u32 h, l;
__asm__ volatile("csrr %0, instreth; csrr %1, instret" : "=r"(h), "=r"(l));
s_h8(h); s_h8(l);
}
static const char *cause_text(u32 c);
/* the line built so far at r, c: highlighted when it changed */
static void w_put(u8 r, u8 c, u8 changed)
{
at(r, c);
if (changed) sgr("1;33");
flush_line();
if (changed) sgr("0");
}
static void w_head(u8 r, u8 c, const char *t) { at(r, c); sgr("36"); puts_(t); sgr("0"); }
/* 132x64: the integer registers, the float registers, the CSRs */
static void draw_wregs(void)
{
u8 k;
u32 v;
static const char fl[] = "NVDZOFUFNX";
w_head(2, 1, "REGISTERS");
for (k = 0; k < 33; k++) {
lp = line;
s_ch(' '); /* names of up to 4 letters (ZERO) */
s_rv(k ? regn[k - 1] : "PC", k ? u.x[k - 1] : u.pc);
w_put(3 + k / 4, 1 + (k & 3) * 15, k > 1 && pv && px[k - 1] != u.x[k - 1]);
}
w_head(2, 66, "FLOAT REGISTERS");
for (k = 0; k < 32; k++) {
char n[6];
lp = n; s_freg(k); *lp = 0;
if (!u.fs) { if (!k) { at(3, 66); puts_("THE FPU IS OFF (MSTATUS.FS = 0)"); } continue; }
lp = line;
if (n[3] == 0) s_ch(' '); /* FT0 and FT10 in line */
s_rv(n, u.f[k]);
s_fdec(u.f[k]);
w_put(3 + (k & 15), 66 + (k >> 4) * 33, pv && pf[k] != u.f[k]);
}
if (u.fs) {
lp = line;
s_str("FCSR "); s_h8(u.fcsr); s_str(" ROUNDING "); s_str(rmn[u.fcsr >> 5 & 7] ? rmn[u.fcsr >> 5 & 7] : "?");
s_str(" FLAGS");
for (k = 0; k < 5; k++) {
u8 on = u.fcsr >> (4 - k) & 1;
s_ch(' '); s_ch(on ? fl[2 * k] : '-'); s_ch(on ? fl[2 * k + 1] : '-');
}
at(19, 66); flush_line();
}
w_head(13, 1, "CONTROL AND STATUS");
lp = line;
/* u.status is saved only for a trap; an NMI leaves mstatus as it was */
s_str("MSTATUS "); s_h8(u.how ? u.status : csr_mstatus()); s_str(" MEPC "); s_h8(csr_mepc());
s_str(" MTVAL "); s_h8(csr_mtval());
at(14, 1); flush_line();
v = csr_mcause();
{
const char *ct = cause_text(v);
lp = line;
s_str("MCAUSE "); s_h8(v); s_ch(' '); s_str(ct);
}
while (lp < line + 58) s_ch(' ');
at(15, 1); flush_line();
lp = line;
s_str("CYCLE "); s_cycle(); s_str(" INSTRET "); s_instret();
at(16, 1); flush_line();
lp = line;
s_str("BREAKPOINT ");
if (bp_set) s_hex(bp, 5); else s_str("NONE ");
at(17, 1); flush_line();
}
static void draw_regs(void) static void draw_regs(void)
{ {
u8 r, i; u8 r, i;
if (wide) { draw_wregs(); return; }
for (r = 0; r < 6; r++) { for (r = 0; r < 6; r++) {
lp = line; lp = line;
for (i = 0; i < 6; i++) { for (i = 0; i < 6; i++) {
@@ -460,7 +610,7 @@ static void draw_dis(void)
s_hex(a, 5); s_str(" "); s_hex(a, 5); s_str(" ");
s_h8(rd32(a)); s_str(" "); s_h8(rd32(a)); s_str(" ");
disasm(a); disasm(a);
while (lp < line + 50) s_ch(' '); while (lp < line + STK_COL - 4) s_ch(' ');
at(DIS_TOP + r, 0); at(DIS_TOP + r, 0);
if (a == pc) sgr("1;33;44"); if (a == pc) sgr("1;33;44");
flush_line(); flush_line();
@@ -473,11 +623,11 @@ static void draw_stack(void)
{ {
u32 s = u.x[2]; u32 s = u.x[2];
u8 r; u8 r;
at(DIS_TOP - 1, 54); sgr("36"); puts_("STACK"); sgr("0"); at(DIS_TOP - 1, STK_COL); sgr("36"); puts_("STACK"); sgr("0");
for (r = 0; r < DIS_ROWS; r++) { for (r = 0; r < DIS_ROWS; r++) {
lp = line; lp = line;
s_hex(s, 5); s_str(" "); s_h8(rd32(s)); s_hex(s, 5); s_str(" "); s_h8(rd32(s));
at(DIS_TOP + r, 54); flush_line(); clr_eol(); at(DIS_TOP + r, STK_COL); flush_line(); clr_eol();
s += 4; s += 4;
} }
} }
@@ -507,7 +657,7 @@ static void draw_mem(void)
{ {
u32 a = mem_a; u32 a = mem_a;
u8 r, j, c; u8 r, j, c;
if (show_f) { draw_fregs(); return; } if (show_f && !wide) { draw_fregs(); return; }
at(MEM_TOP - 1, 0); sgr("36"); puts_(" MEMORY"); sgr("0"); clr_eol(); at(MEM_TOP - 1, 0); sgr("36"); puts_(" MEMORY"); sgr("0"); clr_eol();
for (r = 0; r < MEM_ROWS; r++) { for (r = 0; r < MEM_ROWS; r++) {
lp = line; lp = line;
@@ -520,22 +670,27 @@ static void draw_mem(void)
} }
} }
/* an mcause value in words (in t, so not while line is being built) */
static const char *cause_text(u32 c) /* uses lp: call before building a line */
{
static char t[16];
const char *r = t;
if (c >> 31) { lp = t; s_str("INTERRUPT "); s_udec(c & 31); *lp = 0; }
else switch (c) {
case 0: r = "MISALIGNED JUMP"; break;
case 2: r = "ILLEGAL INSTRUCTION"; break;
case 3: r = "EBREAK"; break;
case 4: r = "MISALIGNED LOAD"; break;
case 6: r = "MISALIGNED STORE"; break;
case 11: r = "ECALL"; break;
default: lp = t; s_str("TRAP "); s_udec(c); *lp = 0;
}
return r;
}
static const char *why_text(void) static const char *why_text(void)
{ {
static char t[32]; if (u.how) return cause_text(u.cause);
if (u.how) {
u32 c = u.cause;
if (c >> 31) { lp = t; s_str("INTERRUPT "); s_udec(c & 31); *lp = 0; return t; }
switch (c) {
case 0: return "MISALIGNED JUMP";
case 2: return "ILLEGAL INSTRUCTION";
case 3: return "EBREAK";
case 4: return "MISALIGNED LOAD";
case 6: return "MISALIGNED STORE";
case 11: return "ECALL";
default: lp = t; s_str("TRAP "); s_udec(c); *lp = 0; return t;
}
}
switch (why_in) { switch (why_in) {
case 1: return "PAUSE KEY"; case 1: return "PAUSE KEY";
case 2: return "MONITOR COMMAND"; case 2: return "MONITOR COMMAND";
@@ -548,23 +703,28 @@ static const char *why_text(void)
static void draw_all(void) static void draw_all(void)
{ {
u8 w = wide ? 132 : 80, n;
puts_("\033[2J"); puts_("\033[2J");
at(0, 0); sgr("1;37;44"); at(0, 0); sgr("1;37;44");
lp = line; {
s_str(" RISC-V MONITOR"); const char *wt = why_text();
while (lp < line + 50) s_ch(' '); lp = line;
s_str("STOPPED BY "); s_str(" RISC-V MONITOR");
s_str(why_text()); while (lp < line + (wide ? 66 : 50)) s_ch(' ');
while (lp < line + 80) s_ch(' '); s_str("STOPPED BY ");
s_str(wt);
}
*lp = 0; *lp = 0;
line[80] = 0; n = lp - line;
puts_(line); sgr("0"); puts_(line);
while (n++ < w) putc_(' ');
sgr("0");
draw_regs(); draw_regs();
at(DIS_TOP - 1, 0); sgr("36"); puts_(" ADDR WORD INSTRUCTION"); sgr("0"); at(DIS_TOP - 1, 0); sgr("36"); puts_(" ADDR WORD INSTRUCTION"); sgr("0");
draw_dis(); draw_dis();
draw_stack(); draw_stack();
draw_mem(); draw_mem();
at(28, 0); sgr("36"); at(HELP_ROW, 0); sgr("36");
puts_(" ENTER step O over G go X exit B bp D/M addr E edit R reg F fp ? help"); puts_(" ENTER step O over G go X exit B bp D/M addr E edit R reg F fp ? help");
sgr("0"); sgr("0");
} }
@@ -580,6 +740,7 @@ static u8 get_hex(u32 *v)
u8 n = 0; u8 n = 0;
skip_sp(); skip_sp();
*v = 0; *v = 0;
if (cp[0] == '0' && (cp[1] == 'X' || cp[1] == 'x') && is_hex(cp[2])) cp += 2; /* 0x is optional */
while (is_hex(*cp)) { while (is_hex(*cp)) {
*v = *v << 4 | (*cp <= '9' ? *cp - '0' : *cp - 'A' + 10); *v = *v << 4 | (*cp <= '9' ? *cp - '0' : *cp - 'A' + 10);
cp++; n++; cp++; n++;
@@ -589,7 +750,7 @@ static u8 get_hex(u32 *v)
static void show_msg(void) static void show_msg(void)
{ {
at(29, 40); clr_eol(); at(CMD_ROW, MSG_COL); clr_eol();
if (msg) { sgr(msg_err ? "1;31" : "32"); puts_(msg); sgr("0"); } if (msg) { sgr(msg_err ? "1;31" : "32"); puts_(msg); sgr("0"); }
} }
@@ -599,9 +760,9 @@ static const char *prompt = "> ";
static u8 read_cmd(void) static u8 read_cmd(void)
{ {
u8 n = 0, c; u8 n = 0, c;
at(29, 0); puts_(prompt); clr_eol(); at(CMD_ROW, 0); puts_(prompt); clr_eol();
show_msg(); show_msg();
at(29, strlen(prompt)); at(CMD_ROW, strlen(prompt));
puts_("\033[?25h"); puts_("\033[?25h");
for (;;) { for (;;) {
c = getk(); c = getk();
@@ -1033,14 +1194,16 @@ static u8 set_reg(void)
u8 r; u8 r;
u32 v; u32 v;
skip_sp(); skip_sp();
if (cp[0] == 'F' && ((cp[1] >= '0' && cp[1] <= '9') || !memcmp(cp, "FCSR", 4))) { { /* F0-F31, FT0, FA0 ..., FCSR */
char n[6];
u8 k = 0;
while (k < 5 && cp[k] && cp[k] != '=' && cp[k] != ' ') { n[k] = cp[k]; k++; }
n[k] = 0;
r = !strcmp(n, "FCSR") ? 32 : a_fregname(n);
}
if (r != 0xFF) {
if (!u.fs) return 0; /* not saved: the FPU is off */ if (!u.fs) return 0; /* not saved: the FPU is off */
if (cp[1] == 'C') { cp += 4; r = 32; } while (*cp && *cp != '=' && *cp != ' ') cp++;
else {
r = *++cp - '0';
if (*++cp >= '0' && *cp <= '9') r = r * 10 + (*cp++ - '0');
if (r > 31) return 0;
}
skip_sp(); skip_sp();
if (*cp == '=') cp++; if (*cp == '=') cp++;
if (!get_hex(&v)) return 0; if (!get_hex(&v)) return 0;
@@ -1183,6 +1346,7 @@ static u8 command(void)
draw_all(); draw_all();
return 0; return 0;
case 'F': case 'F':
if (wide) { msg = "THE FLOAT REGISTERS ARE ALWAYS SHOWN"; return 0; }
show_f = 1; show_f = 1;
draw_mem(); draw_mem();
msg = "M TO SHOW MEMORY AGAIN"; msg = "M TO SHOW MEMORY AGAIN";
@@ -1223,6 +1387,7 @@ void mon_main(void)
} }
steps = 0; steps = 0;
go_after = 0; go_after = 0;
layout();
if (!dis_shows(u.pc)) dis_a = u.pc; if (!dis_shows(u.pc)) dis_a = u.pc;
puts_("\0337\033[?47h\033[?25l"); /* save the cursor, alternate screen */ puts_("\0337\033[?47h\033[?25l"); /* save the cursor, alternate screen */
@@ -1240,6 +1405,9 @@ void mon_main(void)
else if (k == 'Q') mem_a += 16 * MEM_ROWS; else if (k == 'Q') mem_a += 16 * MEM_ROWS;
if (k == 'U' || k == 'N') draw_dis(); else draw_mem(); if (k == 'U' || k == 'N') draw_dis(); else draw_mem();
} }
memcpy(px, u.x, sizeof px); /* to show what the program changes */
memcpy(pf, u.f, sizeof pf);
pv = 1;
puts_("\033[?25h\033[?47l\0338"); puts_("\033[?25h\033[?47l\0338");
} }
#endif #endif
+5 -1
View File
@@ -11,8 +11,12 @@ SECTIONS
{ {
.text : { .text : {
KEEP(*(.text.start)) KEEP(*(.text.start))
*(.text .text.*) /* the constants before the code: they are reached by LUI and ADDI,
and relaxation must never take them for gp-relative data, which
it would if the code (larger before relaxing) pushed them past
28000h */
*(.rodata .rodata.* .srodata .srodata.*) *(.rodata .rodata.* .srodata .srodata.*)
*(.text .text.*)
. = ALIGN(4); . = ALIGN(4);
} > ROM } > ROM
.data : ALIGN(4) { .data : ALIGN(4) {
+6956 -6956
View File
File diff suppressed because it is too large. Load diff
+117 -22
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Assemble a test program with the monitor's assembler (out/monitor-host) """Assemble test programs with the monitor's assembler (out/monitor-host)
and with GNU as, and check the bytes are the same. and with GNU as, and check the bytes are the same: one in GNU syntax, given
to both as it is, and one in the older forms the monitor still takes.
python3 test-asm.py python3 test-asm.py
""" """
@@ -12,7 +13,72 @@ import tempfile
HERE = os.path.dirname(os.path.abspath(__file__)) HERE = os.path.dirname(os.path.abspath(__file__))
# the monitor's syntax; to_gnu() below turns it into GNU as's # GNU syntax: both assemblers read this text (GNU as without the .org)
GNU_SRC = r"""
.org 0x12000
.text
.option norvc
.globl _start
.equ count, 10
.set mask, 0b1010 << 4 | 1 # 161
width = (count * 3) ^ ~0xf # mixed operators
big = 0x12345
_start: la a1, message # auipc and addi
li a2, count
li a3, 0x12000 # lui alone
li a4, 0x12345 # lui and addi
li a5, -1
li t0, mask
li t1, width & 0x7ff
lui a6, %hi(big)
addi a6, a6, %lo(big)
lui a7, %hi(table)
lw a7, %lo(table)(a7)
sw zero, %lo(table)(a7)
print_char:
lbu a0, 0(a1)
beqz a0, finish
wait: lbu t0, -256(zero)
andi t0, t0, 2
beqz t0, wait
sb a0, -255(zero)
addi a1, a1, 1
j print_char
finish: li a0, '\n'
li a1, 'Z' - 1
csrr a2, mstatus
csrw mscratch, a2
csrrs a3, cycle, zero
frrm a4
fadd.s fa0, fa1, fa2, rtz
fmadd.s ft0, ft1, ft2, ft3
flw fs0, 4(sp)
fsw ft11, -8(sp)
fcvt.w.s t2, fa0, rtz
jal print_char
jalr t0
ret
.align 4 # NOPs from a word
message:
.string "hello, \"world\"\n", "two"
.ascii "tab\there"
.asciz "back\\slash"
.p2align 2, 0 # GNU leaves bytes unaligned without a fill
table: .word _start, finish, . - _start, 0x12345678
.long -1
.4byte 'A'
.half 1234, 0xffff
.short 7
.2byte -2
.byte 1, 2, 0x7f, 'X', '\t' # (GNU reads '\0' as '0')
.space 3, 0xaa
.zero 2
.skip 1
.balign 8
.byte 0xee
"""
# the older forms; to_gnu() below turns them into GNU as's
SRC = r""" SRC = r"""
ORG 12000H ORG 12000H
COUNT EQU 10 COUNT EQU 10
@@ -130,36 +196,65 @@ def to_gnu(src):
return "\n".join(out) + "\n" return "\n".join(out) + "\n"
def main(): def assemble_gnu(pre, text, tmp):
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE], open(os.path.join(tmp, "t.s"), "w").write(text)
capture_output=True, text=True).stdout.strip()
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=SRC,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL the monitor's assembler: " + ours)
sys.exit(1)
start, ours = ours.split()
tmp = tempfile.mkdtemp()
open(os.path.join(tmp, "t.s"), "w").write(to_gnu(SRC))
subprocess.run([pre + "as", "-march=rv32imf_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"), subprocess.run([pre + "as", "-march=rv32imf_zicsr_zifencei", "-mno-relax", "-o", os.path.join(tmp, "t.o"),
os.path.join(tmp, "t.s")], check=True) os.path.join(tmp, "t.s")], check=True)
subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o", os.path.join(tmp, "t.elf"), subprocess.run([pre + "ld", "-m", "elf32lriscv", "--no-relax", "-e", "0x12000", "-Ttext=0x12000", "-o",
os.path.join(tmp, "t.o")], check=True) os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.o")], check=True)
subprocess.run([pre + "objcopy", "-O", "binary", os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.bin")], subprocess.run([pre + "objcopy", "-O", "binary", os.path.join(tmp, "t.elf"), os.path.join(tmp, "t.bin")],
check=True) check=True)
gnu = open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper() return open(os.path.join(tmp, "t.bin"), "rb").read().hex().upper()
# GNU pads the section's end to a word
if len(gnu) > len(ours) and set(gnu[len(ours):]) <= {"0"}:
def compare(what, src, gnu_text, pre):
ours = subprocess.run([os.path.join(HERE, "out", "monitor-host"), "asmbin"], input=src,
capture_output=True, text=True).stdout.strip()
if not re.fullmatch(r"[0-9A-F]{5} [0-9A-F]+", ours):
print("FAIL %s: the monitor's assembler says %s" % (what, ours))
return False
start, ours = ours.split()
gnu = assemble_gnu(pre, gnu_text, tempfile.mkdtemp())
if 0 < len(gnu) - len(ours) < 32: # GNU pads the section's end to 16 bytes
gnu = gnu[:len(ours)] gnu = gnu[:len(ours)]
ok = start == "12000" and ours == gnu ok = start == "12000" and ours == gnu
if not ok: if not ok:
for i in range(0, max(len(ours), len(gnu)), 8): for i in range(0, max(len(ours), len(gnu)), 8):
if ours[i:i + 8] != gnu[i:i + 8]: if ours[i:i + 8] != gnu[i:i + 8]:
print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8], gnu[i:i + 8])) print("first difference at %05X: monitor %s, GNU %s" % (0x12000 + i // 2, ours[i:i + 8],
gnu[i:i + 8]))
break break
print("lengths: monitor %d bytes, GNU %d" % (len(ours) // 2, len(gnu) // 2)) print("lengths: monitor %d bytes, GNU %d" % (len(ours) // 2, len(gnu) // 2))
print(("PASS" if ok else "FAIL") + " %d bytes from 12000h the same as GNU as" % (len(ours) // 2)) print(("PASS" if ok else "FAIL") + " %s: %d bytes from 12000h the same as GNU as" % (what, len(ours) // 2))
sys.exit(0 if ok else 1) return ok
def host(cmd, text):
return subprocess.run([os.path.join(HERE, "out", "monitor-host"), cmd], input=text,
capture_output=True, text=True).stdout
def main():
pre = subprocess.run(["bash", "-c", "source %s/../scripts/rv_env.sh; echo $RV_PREFIX" % HERE],
capture_output=True, text=True).stdout.strip()
ok = compare("GNU syntax", GNU_SRC, GNU_SRC.replace(".org 0x12000", ""), pre)
ok &= compare("the older forms", SRC, to_gnu(SRC), pre)
# the same lines as BASIC stores them, in capitals outside double quotes
# (BASIC knows nothing of \" in a string, so that line is left out), and
# with ; comments
plain = "\n".join(l for l in GNU_SRC.splitlines() if '\\"' not in l)
upper = re.sub(r'("[^"]*")|[a-z]', lambda m: m.group(1) or m.group(0).upper(), plain)
upper = upper.replace("#", ";")
want = host("asmbin", plain)
same = host("asmbin", upper) == want and "ERROR" not in want
print(("PASS" if same else "FAIL") + " the same in capitals, with ; comments")
ok &= same
# errors
errs = {".align 33": "ALIGN", ".equ 5": "NAME", "li a0, %mid(5)": "BAD EXPRESSION",
".ascii 5": "BAD STRING", "lw a0, 0(q9)": "REGISTER", ".byte 0b102": "BAD NUMBER"}
bad = [k for k, v in errs.items() if v not in host("asm", k + "\n")]
print(("PASS" if not bad else "FAIL %s" % bad) + " errors")
sys.exit(0 if ok and not bad else 1)
if __name__ == "__main__": if __name__ == "__main__":
+9 -2
View File
@@ -124,7 +124,14 @@ FCSR_ALIAS = {"FRCSR": ("FCSR", "R"), "FRRM": ("FRM", "R"), "FRFLAGS": ("FFLAGS"
"FSRMI": ("FRM", "I"), "FSFLAGSI": ("FFLAGS", "I")} "FSRMI": ("FRM", "I"), "FSFLAGSI": ("FFLAGS", "I")}
FABI = ["FT%d" % i for i in range(8)] + ["FS0", "FS1"] + ["FA%d" % i for i in range(8)] + \
["FS%d" % i for i in range(2, 12)] + ["FT%d" % i for i in range(8, 12)]
def same(gnu_mn, gnu_ops, our): def same(gnu_mn, gnu_ops, our):
# ours is in lower case, with float registers by ABI name: objdump -M
# numeric's f0-f31
our = re.sub(r"\bF[TSA]\d+\b", lambda q: "F%d" % FABI.index(q.group(0)), our.upper())
m = our.split(None, 1) m = our.split(None, 1)
mn = m[0] mn = m[0]
ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else [] ops = [o.strip() for o in m[1].split(",")] if len(m) > 1 else []
@@ -145,7 +152,7 @@ def same(gnu_mn, gnu_ops, our):
gnu_mn, gnu_ops = "CSRW" + kind, [csr] + gnu_ops gnu_mn, gnu_ops = "CSRW" + kind, [csr] + gnu_ops
gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops] gnu_ops = [str(CSRN[o]) if o in CSRN else o for o in gnu_ops]
ops = [str(CSRN[o]) if o in CSRN else o for o in ops] ops = [str(CSRN[o]) if o in CSRN else o for o in ops]
alias = {"FENCE.I": "FENCE.I", "UNIMP": "DW"} alias = {"FENCE.I": "FENCE.I", "UNIMP": ".WORD"}
if alias.get(gnu_mn, gnu_mn) != mn: if alias.get(gnu_mn, gnu_mn) != mn:
return False return False
# objdump writes "fence iorw,iorw" # objdump writes "fence iorw,iorw"
@@ -208,7 +215,7 @@ def main():
print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o)) print("DIS %08X: objdump '%s', monitor '%s'" % (w, g, o))
# round trip through the monitor's assembler, one instruction at 1000h each # round trip through the monitor's assembler, one instruction at 1000h each
bad_asm = 0 bad_asm = 0
back = subprocess.run([HOST, "asm"], input="".join("ORG 1000H\n%s\n" % o for o in ours), back = subprocess.run([HOST, "asm"], input="".join(".org 0x1000\n%s\n" % o for o in ours),
capture_output=True, text=True).stdout.splitlines() capture_output=True, text=True).stdout.splitlines()
for w, o, b in zip(ws, ours, back): for w, o, b in zip(ws, ours, back):
want = 0x0FF0000F if (w & 0x707F) == 0x0F else w want = 0x0FF0000F if (w & 0x707F) == 0x0F else w
+4 -2
View File
@@ -247,11 +247,13 @@ module rv32_cpu #(
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// CSRs // CSRs
reg mie_b, mpie_b; // mstatus reg mie_b, mpie_b; // mstatus
reg [31:0] mie_r, mtvec, mscratch, mepc, mcause, mtval; // 0 at power-up (no logic: the flip-flops' initial state), so the
// monitor shows 0 rather than whatever they held before the first trap
reg [31:0] mie_r = 0, mtvec = 0, mscratch = 0, mepc = 0, mcause = 0, mtval = 0;
reg [63:0] mcycle, minstret; reg [63:0] mcycle, minstret;
reg tsel, mte, mpte; reg tsel, mte, mpte;
reg nmie, stepped; reg nmie, stepped;
reg [31:0] mnscratch, mnepc, mncause; reg [31:0] mnscratch = 0, mnepc = 0, mncause = 0;
reg [1:0] t_m, t_x, t_s, t_l; reg [1:0] t_m, t_x, t_s, t_l;
reg [31:0] t_a0, t_a1; reg [31:0] t_a0, t_a1;
reg [31:0] irq_r; reg [31:0] irq_r;
+71 -11
View File
@@ -113,6 +113,14 @@ module tb_terminal;
end end
endfunction endfunction
function [9:0] cellattr(input integer rr, input integer cc); // its colours
reg [17:0] v;
begin
v = dut.screen.cell_at((dut.alt_scr ? 8448 : 0) + rr * 132 + cc);
cellattr = v[17:8];
end
endfunction
function [7:0] cellch(input integer rr, input integer cc); function [7:0] cellch(input integer rr, input integer cc);
reg [7:0] v; reg [7:0] v;
begin begin
@@ -208,6 +216,7 @@ module tb_terminal;
ch = cellraw(rr, cc); ch = cellraw(rr, cc);
if (go && ch >= "0" && ch <= "9") hex_at = hex_at * 16 + (ch - "0"); if (go && ch >= "0" && ch <= "9") hex_at = hex_at * 16 + (ch - "0");
else if (go && ch >= "A" && ch <= "F") hex_at = hex_at * 16 + (ch - "A" + 10); else if (go && ch >= "A" && ch <= "F") hex_at = hex_at * 16 + (ch - "A" + 10);
else if (go && ch >= "a" && ch <= "f") hex_at = hex_at * 16 + (ch - "a" + 10);
else go = 0; else go = 0;
end end
end end
@@ -380,6 +389,56 @@ module tb_terminal;
cellraw(8, 104), cellraw(8, 106), cellraw(9, 0)); cellraw(8, 104), cellraw(8, 106), cellraw(9, 0));
errors = errors + 1; errors = errors + 1;
end end
// ---- the monitor's wide layout: everything at once
uart_str("\025MONITOR\015");
wait_at(0, 66, "STOPPED BY MONITOR COMMAND");
wait_at(2, 1, "REGISTERS");
wait_at(3, 1, " PC ");
wait_at(3, 16, " ZERO 00000000");
wait_at(2, 66, "FLOAT REGISTERS");
wait_at(3, 66, " FT0 ");
wait_at(18, 99, "FT11 ");
wait_at(19, 66, "FCSR ");
wait_at(13, 1, "CONTROL AND STATUS");
wait_at(14, 1, "MSTATUS ");
wait_at(15, 1, "MCAUSE ");
wait_at(16, 1, "CYCLE ");
wait_at(17, 1, "BREAKPOINT NONE");
wait_at(21, 0, " ADDR WORD INSTRUCTION");
wait_at(22, 0, ">");
wait_at(21, 66, "STACK");
wait_at(47, 0, " MEMORY");
wait_at(48, 1, " ");
wait_at(62, 0, " ENTER step");
wait_at(63, 0, "> ");
// a float register, in hex and decimal, without asking for it (F)
// (each command redraws the whole screen: give it time before the next)
uart_str("R FA0=3FC00000\015");
wait_at(13, 66, " FA0 3FC00000 1.500000E+00");
#300_000_000;
uart_str("R FA1=C2F6E979\015");
wait_at(14, 66, " FA1 C2F6E979 -1.234560E+02");
#300_000_000;
// a step that changes A0 shows it highlighted (A1 beside it is not)
uart_str("A 12000\015"); #300_000_000;
uart_str("LI A0,66\015"); #300_000_000;
uart_str("\015"); #300_000_000;
uart_str("R PC=12000\015"); #300_000_000;
uart_str("\015");
wait_at(0, 66, "STOPPED BY STEP");
wait_at(5, 46, " A0 00000042");
wait_at(3, 6, "00012004");
// (ZERO is never highlighted, and LI leaves A1 alone)
if (cellattr(5, 52) != cellattr(3, 23) && cellattr(6, 7) == cellattr(3, 23))
$display("PASS a register a step changed is highlighted");
else begin
$display("FAIL highlight: A0 %h, A1 %h, ZERO %h", cellattr(5, 52), cellattr(6, 7), cellattr(3, 23));
errors = errors + 1;
end
// F says the float registers are already there; M is the memory
#300_000_000;
uart_str("F\015");
wait_at(63, 66, "THE FLOAT REGISTERS ARE ALWAYS SHOWN");
if (errors == 0) $display("ALL TESTS PASSED"); if (errors == 0) $display("ALL TESTS PASSED");
else $display("%0d TESTS FAILED", errors); else $display("%0d TESTS FAILED", errors);
$finish; $finish;
@@ -428,7 +487,7 @@ module tb_terminal;
"OUT 112,1:OUT 113,108:OUT 114,0:OUT 115,158:OUT 116,1:OUT 117,1\015"}); "OUT 112,1:OUT 113,108:OUT 114,0:OUT 115,158:OUT 116,1:OUT 117,1\015"});
uart_str({"FILL 0,200,319,239,4:OUT 112,2:OUT 113,54:OUT 114,1:OUT 115,230:", uart_str({"FILL 0,200,319,239,4:OUT 112,2:OUT 113,54:OUT 114,1:OUT 115,230:",
"OUT 116,2:OUT 117,3\015"}); "OUT 116,2:OUT 117,3\015"});
#40_000_000; #300_000_000;
@(posedge vs); @(posedge vs); @(posedge vs); @(posedge vs); @(posedge vs); @(posedge vs);
uart_str("LOCATE 30,1:PRINT INP(128);INP(129);INP(132)\015"); uart_str("LOCATE 30,1:PRINT INP(128);INP(129);INP(132)\015");
wait_row(29, " 3 0 4"); wait_row(29, " 3 0 4");
@@ -559,7 +618,7 @@ module tb_terminal;
pc_a = screen_pc(0); pc_a = screen_pc(0);
wait_at(9, 0, ">"); wait_at(9, 0, ">");
jp_txt = {cellraw(9, 19), cellraw(9, 20)}; jp_txt = {cellraw(9, 19), cellraw(9, 20)};
jp_to = hex_at(9, 21); jp_to = hex_at(9, 23); // "j 0x54a4"
dump_screen; dump_screen;
// the float registers, in place of the memory window, and setting one // the float registers, in place of the memory window, and setting one
uart_str("F\015"); uart_str("F\015");
@@ -573,9 +632,9 @@ module tb_terminal;
wait_at(0, 50, "STOPPED BY STEP"); wait_at(0, 50, "STOPPED BY STEP");
wait_at(29, 0, "> "); wait_at(29, 0, "> ");
pc_b = screen_pc(0); pc_b = screen_pc(0);
// MONITOR stops on a J (to the end of BASIC's statement routine): one // MONITOR stops on a j (to the end of BASIC's statement routine): one
// step must land exactly on its target // step must land exactly on its target
if (jp_txt == "J " && pc_b == jp_to) $display("PASS step: PC %h -> %h", pc_a, pc_b); if (jp_txt == "j " && pc_b == jp_to) $display("PASS step: PC %h -> %h", pc_a, pc_b);
else begin $display("FAIL step: PC %h -> %h, wanted %h (%0s)", pc_a, pc_b, jp_to, jp_txt); errors = errors + 1; end else begin $display("FAIL step: PC %h -> %h, wanted %h (%0s)", pc_a, pc_b, jp_to, jp_txt); errors = errors + 1; end
// a breakpoint where the step stopped (the end of BASIC's statement // a breakpoint where the step stopped (the end of BASIC's statement
// routine), hit again by OUT; leaving from it steps off it first // routine), hit again by OUT; leaving from it steps off it first
@@ -632,16 +691,17 @@ module tb_terminal;
wait_row(0, " 72 73"); wait_row(0, " 72 73");
// ---- the assembler: source typed into BASIC, saved, assembled by the monitor // ---- the assembler: source typed into BASIC, saved, assembled by the monitor
uart_str({"NEW\01510 ORG 12000H\01520 START: LA A1,MSG\01530 LOOP: LBU A0,0(A1)\015", // GNU as syntax, typed in lower case (BASIC stores it in capitals)
"40 BEQZ A0,DONE\01550 WAIT: LBU T0,-256(ZERO)\01560 ANDI T0,T0,2\015"}); uart_str({"NEW\01510 .org 0x12000\01520 start: la a1, msg\01530 loop: lbu a0, 0(a1)\015",
uart_str({"70 BEQZ T0,WAIT\01580 SB A0,-255(ZERO)\01590 ADDI A1,A1,1\015100 J LOOP\015", "40 beqz a0, done\01550 wait: lbu t0, -256(zero)\01560 andi t0, t0, 2\015"});
"110 DONE: RET\015"}); uart_str({"70 beqz t0, wait\01580 sb a0, -255(zero)\01590 addi a1, a1, 1\015100 j loop\015",
uart_str({"120 MSG: DB \"ASM OK\",0 ; THE MESSAGE\015SAVE \"HELLO\"\015MONITOR\015"}); "110 done: ret\015"});
uart_str({"120 msg: .string \"ASM OK\" # the message\015SAVE \"HELLO\"\015MONITOR\015"});
wait_at(29, 0, "> "); wait_at(29, 0, "> ");
uart_str("ASM \"HELLO\"\015"); uart_str("ASM \"HELLO\"\015");
wait_at(29, 40, "ASSEMBLED 12000-12032"); wait_at(29, 40, "ASSEMBLED 12000-12032");
uart_str("A 12100\015LI A0,66\015\015"); uart_str("A 12100\015LI A0,'B'\015\015"); // the line assembler, in capitals
wait_at(9, 2, "12100 04200513 LI A0,66"); wait_at(9, 2, "12100 04200513 li a0,66");
// an Intel HEX record above 64K (an extended address first) and the end record // an Intel HEX record above 64K (an extended address first) and the end record
uart_str(":020000040001F9\015:03210000AABBCCAB\015:00000001FF\015"); uart_str(":020000040001F9\015:03210000AABBCCAB\015:00000001FF\015");
wait_at(29, 40, "HEX LOADED 12100-12102"); wait_at(29, 40, "HEX LOADED 12100-12102");
Executable
+1510
View File
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -74,9 +74,10 @@ def wait_for(pattern, timeout=10.0):
raise SystemExit("no answer from the board (waiting for %r); last output: %r" % (pattern, buf[-200:])) raise SystemExit("no answer from the board (waiting for %r); last output: %r" % (pattern, buf[-200:]))
# the monitor's command line, redrawn after each command; its message comes # the monitor's command line, redrawn after each command (row 30 on the 80x32
# after the prompt, and the cursor is turned back on last # screen, 64 on the 132x64 one); its message comes after the prompt, and the
PROMPT = rb"\x1b\[30;1H> .*?\x1b\[\?25h" # cursor is turned back on last
PROMPT = rb"\x1b\[\d+;1H> .*?\x1b\[\?25h"
send("\r") send("\r")
time.sleep(0.3) time.sleep(0.3)
if not a.no_date: # the file gets the PC's date if not a.no_date: # the file gets the PC's date