Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
305c608bb5 | ||
|
|
addf0157fc | ||
|
|
1e44ce4383 | ||
|
|
2e668c708f |
No files matched your search
@@ -10,19 +10,21 @@ RISC-V processor written from scratch in Verilog:
|
|||||||
in a double-size font.
|
in a double-size font.
|
||||||
- **Graphics** over the text: 320 × 240 in 16 colours with hardware scrolling,
|
- **Graphics** over the text: 320 × 240 in 16 colours with hardware scrolling,
|
||||||
or 640 × 480 in two colours, plus 32 hardware sprites.
|
or 640 × 480 in two colours, plus 32 hardware sprites.
|
||||||
- **Sound**: a three-voice chip with noise and envelopes (PmodAMP2 on JA).
|
|
||||||
- **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,
|
- **Software**: Dartmouth-style BASIC with graphics and files,
|
||||||
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
|
`DO … LOOP`, block `IF … ELSE … END IF` and `SELECT CASE`, and scientific
|
||||||
functions (inverse and hyperbolic trigonometry in radians or degrees,
|
functions (inverse and hyperbolic trigonometry in radians or degrees,
|
||||||
`LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a
|
`LOG10`, `ROUND`, `MOD`, `FACT` …), and `UCASE$`/`LCASE$`; a
|
||||||
machine-code monitor with a RISC-V disassembler and assembler, and five
|
machine-code monitor with a RISC-V disassembler and assembler, and five
|
||||||
original games.
|
original games.
|
||||||
|
- **A BASIC compiler** for the PC (`tools/basc.py`): the same program, the
|
||||||
|
same results and error messages, 7 to 26 times as fast in loops and
|
||||||
|
arithmetic.
|
||||||
|
|
||||||
The [BASIC manual](docs/basic-manual.md) ([PDF](docs/basic-manual.pdf))
|
The [BASIC manual](docs/basic-manual.md) ([PDF](docs/basic-manual.pdf))
|
||||||
describes the computer from the user's side: BASIC, graphics, sprites, sound,
|
describes the computer from the user's side: BASIC, graphics, sprites,
|
||||||
files, the monitor and the games.
|
files, the monitor and the games.
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
@@ -31,7 +33,7 @@ Download `basys3_terminal.bit` (or `basys3_terminal.mcs` to keep it in the
|
|||||||
flash) from the [latest release](https://git.barant.com/barant/Basys3RiscV/releases),
|
flash) from the [latest release](https://git.barant.com/barant/Basys3RiscV/releases),
|
||||||
or build it yourself (below).
|
or build it yourself (below).
|
||||||
|
|
||||||
1. Plug a VGA monitor, a USB keyboard, and optionally a PmodAMP2 into JA.
|
1. Plug in a VGA monitor and a USB keyboard.
|
||||||
2. Load the bitstream with Vivado's Hardware Manager, or `scripts/build.sh
|
2. Load the bitstream with Vivado's Hardware Manager, or `scripts/build.sh
|
||||||
program` / `flash` from a checkout.
|
program` / `flash` from a checkout.
|
||||||
3. Flip **SW15 up**. The screen shows BASIC's banner and `READY`.
|
3. Flip **SW15 up**. The screen shows BASIC's banner and `READY`.
|
||||||
@@ -70,8 +72,8 @@ then `SAVE "KEEP"` in BASIC, and `RUN "KEEP"` from then on.
|
|||||||
| SW15 | Computer mode: the terminal is the computer's console |
|
| SW15 | Computer mode: the terminal is the computer's console |
|
||||||
| BTNC | Reset everything |
|
| BTNC | Reset everything |
|
||||||
| BTNU | Clear the screen |
|
| BTNU | Clear the screen |
|
||||||
| BTND | Restart the computer only (or Ctrl-Alt-Del in computer mode) |
|
| BTND | Restart the computer only |
|
||||||
| Pause key | Stop the program in the machine-code monitor |
|
| Pause key, or Ctrl-Alt-Del | Stop the program in the machine-code monitor, with its registers (Ctrl-Alt-Del again within 2 s, or while the monitor shows, restarts the computer; so does the monitor's `RESET`) |
|
||||||
| LED7:0 | Last byte received |
|
| LED7:0 | Last byte received |
|
||||||
| LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) |
|
| LED11:8 | VT220 keyboard LEDs L4..L1 (`ESC[n q`) |
|
||||||
| LED12–15 | Bell, Caps Lock, serial activity, keyboard activity |
|
| LED12–15 | Bell, Caps Lock, serial activity, keyboard activity |
|
||||||
@@ -138,9 +140,9 @@ LUTs (3,000 of them the FPU), 1,900 flip-flops and 6 DSP slices.
|
|||||||
|
|
||||||
The ports (listed at the top of `rv32_system.v` and in the manual) cover the
|
The ports (listed at the top of `rv32_system.v` and in the manual) cover the
|
||||||
console, the millisecond counter, the 7-segment display, graphics, sprites,
|
console, the millisecond counter, the 7-segment display, graphics, sprites,
|
||||||
sound, the keys held down and the flash. The peripherals are `term_ctrl.v`
|
the keys held down and the flash. The peripherals are `term_ctrl.v`
|
||||||
(the VT220), `text_display.v` (video), `sprites.v`, `sound.v`,
|
(the VT220), `text_display.v` (video), `sprites.v`, `flash_spi.v`,
|
||||||
`flash_spi.v`, `uart.v`, `ps2_keyboard.v` and `sevenseg.v`.
|
`uart.v`, `ps2_keyboard.v` and `sevenseg.v`.
|
||||||
|
|
||||||
The graphics memory is 76,800 four-bit entries: 320 × 240 pixels in 16
|
The graphics memory is 76,800 four-bit entries: 320 × 240 pixels in 16
|
||||||
colours, or, with port 38 set, 640 × 480 pixels at one bit each (four to an
|
colours, or, with port 38 set, 640 × 480 pixels at one bit each (four to an
|
||||||
@@ -163,10 +165,19 @@ All in C (plus a little assembly), compiled with GCC:
|
|||||||
ulp), since
|
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
|
||||||
|
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`,
|
assembler that both use GNU as syntax (`.org`, `.word`, `.string`,
|
||||||
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
|
`%hi`/`%lo`, `#` comments; the disassembly reads like `objdump`'s), Intel
|
||||||
HEX in and out.
|
HEX in and out.
|
||||||
|
- `tools/basc.py` — the BASIC compiler. It reads a program with BASIC's own
|
||||||
|
tokens and turns it into C for GCC: arithmetic, variables, arrays, control
|
||||||
|
statements and graphics become machine code on the FPU; everything else is
|
||||||
|
handed, as tokens, to the interpreter in ROM through a jump table at 9F00h
|
||||||
|
(`rt_table` in `basic.c`), so it behaves the same. It loads at A200h like the
|
||||||
|
games.
|
||||||
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
|
- `games/` — The Iron Keep, Bastion Raid, Star Warden, Star Swarm and Crystal
|
||||||
Cavern; they load at A200h (`CALL 41472`).
|
Cavern; they load at A200h (`CALL 41472`).
|
||||||
|
|
||||||
@@ -202,6 +213,7 @@ the configuration flash.
|
|||||||
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
|
| `scripts/cputest.sh` | the official [riscv-tests](https://github.com/riscv-software-src/riscv-tests) (`rv32ui`, `rv32um`, `rv32uf`, `rv32mi`, fetched into `third_party/`) and `tests/` (interrupts, the NMI and single step) on `rv32_cpu.v` in xsim, with random wait states on the data bus. Two riscv-tests don't apply: `ma_data` expects misaligned loads and stores to work (here they trap, as the spec allows) and `pmpaddr` needs PMP. |
|
||||||
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
|
| `scripts/sim.sh` | the whole design in xsim: the terminal, BASIC, both graphics modes, sprites, scrolling, flash files, the monitor (step, breakpoint, Pause, memory files, the assembler, Intel HEX), 3 Mbaud. `scripts/sim.sh quick` skips the terminal and the monitor; `wide` checks the 132 × 64 start-up. |
|
||||||
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings |
|
| `monitor/test-disasm.py`, `test-asm.py` | the disassembler against GNU objdump on thousands of random instructions, and the assembler against GNU as, byte for byte, on a program in GNU syntax and one in the assembler's older spellings |
|
||||||
|
| `basic/test-compile.py` | every program in `basic/examples` and in the other BASIC tests, plus programs for each statement and error, run interpreted and compiled in the emulator: the screen and the graphics must come out the same. It also times them. |
|
||||||
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
|
| `basic/test-*.py`, `games/*/test-*.py` | BASIC's line editor, RENUM, string arrays, block structures, graphics modes and maths functions (bit for bit against Python's `math`), and each game, on `tools/rv32emu.py` (a Python RV32IMF emulator of the machine; `tools/boardemu.py` models the game hardware). They need `pyte` and Pillow. |
|
||||||
| `bench/` | the processor alone with 64 KB of RAM, for timing |
|
| `bench/` | the processor alone with 64 KB of RAM, for timing |
|
||||||
|
|
||||||
@@ -211,6 +223,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
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
+166
-24
@@ -239,10 +239,10 @@ static char svars[26][STRMAX];
|
|||||||
struct array { u8 *p; u16 d1, d2; };
|
struct array { u8 *p; u16 d1, d2; };
|
||||||
static struct array arrays[52]; /* A()-Z(), then A$()-Z$() */
|
static struct array arrays[52]; /* A()-Z(), then A$()-Z$() */
|
||||||
|
|
||||||
struct fn { u8 *body; u8 var; };
|
struct fn { u8 *body; u16 var; };
|
||||||
static struct fn fns[26];
|
static struct fn fns[26];
|
||||||
|
|
||||||
struct forent { u8 var; float limit, step; u8 *tp, *ln; };
|
struct forent { u16 var; float limit, step; u8 *tp, *ln; };
|
||||||
static struct forent fors[FORMAX];
|
static struct forent fors[FORMAX];
|
||||||
static u8 nfor;
|
static u8 nfor;
|
||||||
|
|
||||||
@@ -254,6 +254,8 @@ struct doent { u8 *tp, *ln; }; /* tp is the DO itself */
|
|||||||
static struct doent dos[DOMAX];
|
static struct doent dos[DOMAX];
|
||||||
static u8 ndo;
|
static u8 ndo;
|
||||||
|
|
||||||
|
static u8 *data_base; /* where READ looks for DATA: 0 = the program */
|
||||||
|
static u8 *rt_floor; /* arrays stay above this (a compiled program) */
|
||||||
static u8 *tp; /* text pointer */
|
static u8 *tp; /* text pointer */
|
||||||
static u8 *curln; /* line being run, 0 in direct mode */
|
static u8 *curln; /* line being run, 0 in direct mode */
|
||||||
static u8 *datap; /* next DATA item, 0 = search from the start */
|
static u8 *datap; /* next DATA item, 0 = search from the start */
|
||||||
@@ -301,7 +303,7 @@ enum {
|
|||||||
E_SYNTAX, E_LINE, E_RETURN, E_NEXT, E_DATA, E_SUBSCRIPT, E_DIV0, E_MEMORY,
|
E_SYNTAX, E_LINE, E_RETURN, E_NEXT, E_DATA, E_SUBSCRIPT, E_DIV0, E_MEMORY,
|
||||||
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_NOFILE, E_DISKFULL,
|
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_NOFILE, E_DISKFULL,
|
||||||
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_NOLOOP,
|
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_NOLOOP,
|
||||||
E_NODO, E_DODEEP, E_NONEXT, E_ENDIF, E_ENDSEL, E_BREAK, E_STOP
|
E_NODO, E_DODEEP, E_NONEXT, E_ENDIF, E_ENDSEL, E_VERSION, E_BREAK, E_STOP
|
||||||
};
|
};
|
||||||
static const char *const errmsg[] = {
|
static const char *const errmsg[] = {
|
||||||
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
|
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
|
||||||
@@ -311,7 +313,7 @@ static const char *const errmsg[] = {
|
|||||||
"FILE NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
|
"FILE NOT FOUND", "DISK FULL", "TOO MANY FILES", "BAD FILE NAME", "FLASH ERROR",
|
||||||
"FILE TOO BIG", "FILE ALREADY OPEN", "FILE NOT OPEN", "INPUT PAST END",
|
"FILE TOO BIG", "FILE ALREADY OPEN", "FILE NOT OPEN", "INPUT PAST END",
|
||||||
"DO WITHOUT LOOP", "LOOP WITHOUT DO", "DO NESTED TOO DEEPLY", "FOR WITHOUT NEXT",
|
"DO WITHOUT LOOP", "LOOP WITHOUT DO", "DO NESTED TOO DEEPLY", "FOR WITHOUT NEXT",
|
||||||
"IF WITHOUT END IF", "SELECT WITHOUT END SELECT",
|
"IF WITHOUT END IF", "SELECT WITHOUT END SELECT", "PROGRAM NEEDS ANOTHER BASIC",
|
||||||
"BREAK", "STOP"
|
"BREAK", "STOP"
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -597,6 +599,7 @@ static void clear_vars(void)
|
|||||||
nfor = nsub = ndo = 0;
|
nfor = nsub = ndo = 0;
|
||||||
datap = 0;
|
datap = 0;
|
||||||
deg = 0;
|
deg = 0;
|
||||||
|
data_base = rt_floor = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void new_prog(void)
|
static void new_prog(void)
|
||||||
@@ -663,16 +666,18 @@ static u16 get_lineno(void)
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Numeric variable name: letter with an optional digit. Returns its index, or
|
/* Numeric variable name: letter with an optional digit. Returns its index,
|
||||||
255 if the text is not a numeric variable (does not move tp then). */
|
0 to 285 (so not a byte: X1 to Z9 once wrapped onto A to B9), or NOVAR if
|
||||||
static u8 var_name(void)
|
the text is not a numeric variable (does not move tp then). */
|
||||||
|
#define NOVAR 0xFFFF
|
||||||
|
static u16 var_name(void)
|
||||||
{
|
{
|
||||||
u8 c = peekc(), d;
|
u8 c = peekc(), d;
|
||||||
if (!is_alpha(c)) return 255;
|
if (!is_alpha(c)) return NOVAR;
|
||||||
d = tp[1];
|
d = tp[1];
|
||||||
if (d == '$') return 255;
|
if (d == '$') return NOVAR;
|
||||||
if (is_digit(d)) {
|
if (is_digit(d)) {
|
||||||
if (tp[2] == '$') return 255;
|
if (tp[2] == '$') return NOVAR;
|
||||||
tp += 2;
|
tp += 2;
|
||||||
return (c - 'A') * 11 + 1 + d - '0';
|
return (c - 'A') * 11 + 1 + d - '0';
|
||||||
}
|
}
|
||||||
@@ -708,7 +713,7 @@ static void arr_alloc(u8 a, u16 d1, u16 d2)
|
|||||||
if ((i16)d1 < 0 || (i16)d2 < 0 || n > (a < 26 ? 6000 : 255)) error(E_SUBSCRIPT);
|
if ((i16)d1 < 0 || (i16)d2 < 0 || n > (a < 26 ? 6000 : 255)) error(E_SUBSCRIPT);
|
||||||
sz = n * (a < 26 ? sizeof(float) : STRMAX);
|
sz = n * (a < 26 ? sizeof(float) : STRMAX);
|
||||||
np = arr_low - sz;
|
np = arr_low - sz;
|
||||||
if (np <= prog_end + 1) error(E_MEMORY);
|
if (np <= prog_end + 1 || np < rt_floor) error(E_MEMORY);
|
||||||
arr_low = np;
|
arr_low = np;
|
||||||
memset(np, 0, sz);
|
memset(np, 0, sz);
|
||||||
ar->p = np;
|
ar->p = np;
|
||||||
@@ -716,9 +721,10 @@ static void arr_alloc(u8 a, u16 d1, u16 d2)
|
|||||||
ar->d2 = d2;
|
ar->d2 = d2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static u8 *elem_at(u8 a, i16 i, i16 j, u8 two);
|
||||||
|
|
||||||
static u8 *array_elem(u8 a)
|
static u8 *array_elem(u8 a)
|
||||||
{
|
{
|
||||||
struct array *ar = &arrays[a];
|
|
||||||
i16 i, j = 0;
|
i16 i, j = 0;
|
||||||
u8 two;
|
u8 two;
|
||||||
expect('(');
|
expect('(');
|
||||||
@@ -726,6 +732,13 @@ static u8 *array_elem(u8 a)
|
|||||||
two = accept(',');
|
two = accept(',');
|
||||||
if (two) j = to_int(expr());
|
if (two) j = to_int(expr());
|
||||||
expect(')');
|
expect(')');
|
||||||
|
return elem_at(a, i, j, two);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* element i (, j) of array a */
|
||||||
|
static u8 *elem_at(u8 a, i16 i, i16 j, u8 two)
|
||||||
|
{
|
||||||
|
struct array *ar = &arrays[a];
|
||||||
if (!ar->p) arr_alloc(a, 10, two ? 10 : 0); /* undeclared: 0..10 */
|
if (!ar->p) arr_alloc(a, 10, two ? 10 : 0); /* undeclared: 0..10 */
|
||||||
if (i < 0 || i > (i16)ar->d1 || j < 0 || j > (i16)ar->d2) error(E_SUBSCRIPT);
|
if (i < 0 || i > (i16)ar->d1 || j < 0 || j > (i16)ar->d2) error(E_SUBSCRIPT);
|
||||||
return ar->p + ((u16)i * (ar->d2 + 1) + j) * (a < 26 ? sizeof(float) : STRMAX);
|
return ar->p + ((u16)i * (ar->d2 + 1) + j) * (a < 26 ? sizeof(float) : STRMAX);
|
||||||
@@ -743,14 +756,14 @@ static char *str_ref(void)
|
|||||||
/* A numeric variable or array element as an lvalue. */
|
/* A numeric variable or array element as an lvalue. */
|
||||||
static float *num_ref(void)
|
static float *num_ref(void)
|
||||||
{
|
{
|
||||||
u8 v;
|
u16 v;
|
||||||
if (is_alpha(peekc()) && tp[1] == '(') {
|
if (is_alpha(peekc()) && tp[1] == '(') {
|
||||||
v = *tp - 'A';
|
v = *tp - 'A';
|
||||||
tp++;
|
tp++;
|
||||||
return (float *)array_elem(v);
|
return (float *)array_elem(v);
|
||||||
}
|
}
|
||||||
v = var_name();
|
v = var_name();
|
||||||
if (v == 255) error(E_SYNTAX);
|
if (v == NOVAR) error(E_SYNTAX);
|
||||||
return &vars[v];
|
return &vars[v];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -813,11 +826,12 @@ static float round_to(float x, i16 n, u8 rnd)
|
|||||||
return (n < 0 ? s * p : s / p) + 0.0f;
|
return (n < 0 ? s * p : s / p) + 0.0f;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static float func2v(u8 t, float v);
|
||||||
|
|
||||||
static float func2(u8 t, float v)
|
static float func2(u8 t, float v)
|
||||||
{
|
{
|
||||||
float w;
|
float w;
|
||||||
i16 n = 0;
|
i16 n = 0;
|
||||||
u8 i;
|
|
||||||
switch (t) {
|
switch (t) {
|
||||||
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
|
case T_ANGLE: /* ANGLE(x, y): the direction of (x, y) */
|
||||||
expect(',');
|
expect(',');
|
||||||
@@ -846,6 +860,14 @@ static float func2(u8 t, float v)
|
|||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
expect(')');
|
expect(')');
|
||||||
|
return func2v(t, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* the one-argument functions from DEG on, of v */
|
||||||
|
static float func2v(u8 t, float v)
|
||||||
|
{
|
||||||
|
float w;
|
||||||
|
u8 i;
|
||||||
switch (t) {
|
switch (t) {
|
||||||
case T_DEG: return v * 180.0f / PI_F;
|
case T_DEG: return v * 180.0f / PI_F;
|
||||||
case T_RAD: return v * PI_F / 180.0f;
|
case T_RAD: return v * PI_F / 180.0f;
|
||||||
@@ -878,6 +900,8 @@ static float func2(u8 t, float v)
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static float func1(u8 t, float v);
|
||||||
|
|
||||||
static float func(u8 t)
|
static float func(u8 t)
|
||||||
{
|
{
|
||||||
char s[STRMAX];
|
char s[STRMAX];
|
||||||
@@ -917,6 +941,12 @@ static float func(u8 t)
|
|||||||
v = expr();
|
v = expr();
|
||||||
if (t >= T_ANGLE) return func2(t, v);
|
if (t >= T_ANGLE) return func2(t, v);
|
||||||
expect(')');
|
expect(')');
|
||||||
|
return func1(t, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* the one-argument functions SIN to INP, of v */
|
||||||
|
static float func1(u8 t, float v)
|
||||||
|
{
|
||||||
switch (t) {
|
switch (t) {
|
||||||
case T_SIN: return sin_cos(v, 0);
|
case T_SIN: return sin_cos(v, 0);
|
||||||
case T_COS: return sin_cos(v, 1);
|
case T_COS: return sin_cos(v, 1);
|
||||||
@@ -1543,7 +1573,7 @@ static void next_data(void)
|
|||||||
while (*datap == ' ') datap++;
|
while (*datap == ' ') datap++;
|
||||||
if (*datap == ',') { datap++; return; }
|
if (*datap == ',') { datap++; return; }
|
||||||
dataln += *dataln;
|
dataln += *dataln;
|
||||||
} else dataln = arena;
|
} else dataln = data_base ? data_base : arena;
|
||||||
for (; *dataln; dataln += *dataln) {
|
for (; *dataln; dataln += *dataln) {
|
||||||
u8 *p = dataln + 3, q = 0;
|
u8 *p = dataln + 3, q = 0;
|
||||||
for (; *p; p++) {
|
for (; *p; p++) {
|
||||||
@@ -1741,8 +1771,9 @@ static void st_select(void)
|
|||||||
static void st_for(void)
|
static void st_for(void)
|
||||||
{
|
{
|
||||||
struct forent *f;
|
struct forent *f;
|
||||||
u8 v = var_name(), i;
|
u16 v = var_name();
|
||||||
if (v == 255) error(E_SYNTAX);
|
u8 i;
|
||||||
|
if (v == NOVAR) error(E_SYNTAX);
|
||||||
expect('=');
|
expect('=');
|
||||||
vars[v] = expr();
|
vars[v] = expr();
|
||||||
for (i = 0; i < nfor; i++) /* reusing a loop variable restarts it */
|
for (i = 0; i < nfor; i++) /* reusing a loop variable restarts it */
|
||||||
@@ -1766,11 +1797,11 @@ static void st_for(void)
|
|||||||
static void st_next(void)
|
static void st_next(void)
|
||||||
{
|
{
|
||||||
struct forent *f;
|
struct forent *f;
|
||||||
u8 v;
|
u16 v;
|
||||||
do {
|
do {
|
||||||
v = var_name();
|
v = var_name();
|
||||||
if (!nfor) error(E_NEXT);
|
if (!nfor) error(E_NEXT);
|
||||||
if (v != 255) {
|
if (v != NOVAR) {
|
||||||
while (nfor && fors[nfor - 1].var != v) nfor--;
|
while (nfor && fors[nfor - 1].var != v) nfor--;
|
||||||
if (!nfor) error(E_NEXT);
|
if (!nfor) error(E_NEXT);
|
||||||
}
|
}
|
||||||
@@ -1784,7 +1815,7 @@ static void st_next(void)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
nfor--;
|
nfor--;
|
||||||
} while (v != 255 && accept(','));
|
} while (v != NOVAR && accept(','));
|
||||||
}
|
}
|
||||||
|
|
||||||
static void st_dim(void)
|
static void st_dim(void)
|
||||||
@@ -1804,14 +1835,15 @@ static void st_dim(void)
|
|||||||
|
|
||||||
static void st_def(void)
|
static void st_def(void)
|
||||||
{
|
{
|
||||||
u8 f, v;
|
u8 f;
|
||||||
|
u16 v;
|
||||||
expect(T_FN);
|
expect(T_FN);
|
||||||
f = peekc();
|
f = peekc();
|
||||||
if (!is_alpha(f)) error(E_SYNTAX);
|
if (!is_alpha(f)) error(E_SYNTAX);
|
||||||
tp++;
|
tp++;
|
||||||
expect('(');
|
expect('(');
|
||||||
v = var_name();
|
v = var_name();
|
||||||
if (v == 255) error(E_SYNTAX);
|
if (v == NOVAR) error(E_SYNTAX);
|
||||||
expect(')');
|
expect(')');
|
||||||
expect('=');
|
expect('=');
|
||||||
fns[f - 'A'].var = v;
|
fns[f - 'A'].var = v;
|
||||||
@@ -1853,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;
|
||||||
}
|
}
|
||||||
@@ -2687,6 +2726,108 @@ static void execute(void)
|
|||||||
running = 0;
|
running = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------ for compiled programs
|
||||||
|
tools/basc.py compiles BASIC to machine code, which calls these through
|
||||||
|
the jump table at 9F00h (rt_table): statements and expressions it leaves
|
||||||
|
to the interpreter go to rt_exec and rt_eval as tokens, so they behave
|
||||||
|
exactly as they would interpreted. line is a 3-byte line record (its
|
||||||
|
number in bytes 1 and 2) for error messages. The table's order and the
|
||||||
|
tokens' and errors' values only ever grow: RT_ABI counts the changes. */
|
||||||
|
#define RT_ABI 1
|
||||||
|
static u8 *rt_tp, *rt_ln; /* the CALL that started the program */
|
||||||
|
|
||||||
|
float *rt_init(u32 abi, u8 *data, u8 *end)
|
||||||
|
{
|
||||||
|
if (abi != RT_ABI) error(E_VERSION);
|
||||||
|
rt_tp = tp;
|
||||||
|
rt_ln = curln;
|
||||||
|
clear_vars(); /* as RUN does */
|
||||||
|
data_base = data;
|
||||||
|
rt_floor = end;
|
||||||
|
return vars;
|
||||||
|
}
|
||||||
|
|
||||||
|
void rt_end(void) /* END, or the last line */
|
||||||
|
{
|
||||||
|
close_all();
|
||||||
|
tp = rt_tp;
|
||||||
|
curln = rt_ln;
|
||||||
|
}
|
||||||
|
|
||||||
|
void rt_exec(u8 *s, u8 *line) /* one statement */
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
tp = s;
|
||||||
|
statement();
|
||||||
|
if (peekc()) error(E_SYNTAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
float rt_eval(u8 *s, u8 *line) /* a numeric expression */
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
tp = s;
|
||||||
|
return expr();
|
||||||
|
}
|
||||||
|
|
||||||
|
void rt_seval(u8 *s, char *out, u8 *line) /* a string expression */
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
tp = s;
|
||||||
|
sexpr(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
float rt_fn(u8 t, float v, u8 *line) /* a one-argument function; RND, TIM */
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
if (t == T_RND) return rnd();
|
||||||
|
if (t == T_TIM) return (float)millis() / 1000.0f;
|
||||||
|
return t >= T_ANGLE ? func2v(t, v) : func1(t, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
float *rt_aref(u8 a, float i, float j, u8 two, u8 *line) /* A(I) or A(I, J) */
|
||||||
|
{
|
||||||
|
i16 k;
|
||||||
|
curln = line;
|
||||||
|
k = to_int(i);
|
||||||
|
return (float *)elem_at(a, k, two ? to_int(j) : 0, two);
|
||||||
|
}
|
||||||
|
|
||||||
|
float rt_pow(float x, float y, u8 *line)
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
return ipow(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* a graphics statement (CLS COLOR PLOT LINE RECT FILL CIRCLE LOCATE INK
|
||||||
|
SCREEN) with its n numbers, between its fewest and most */
|
||||||
|
void rt_gfx(u8 t, const i16 *a, u8 n, u8 *line)
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
pre_a = t == T_CLS ? 0 : a;
|
||||||
|
pre_n = n;
|
||||||
|
graphics(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
void rt_error(u8 e, u8 *line)
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
error(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
void rt_break(u8 *line) /* Ctrl-C? */
|
||||||
|
{
|
||||||
|
curln = line;
|
||||||
|
check_break();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* at 9F00h (basic.ld), fixed for good */
|
||||||
|
__asm__(".section .rtab, \"ax\"\n"
|
||||||
|
".globl rt_table\n"
|
||||||
|
"rt_table:\n"
|
||||||
|
" j rt_init\n j rt_end\n j rt_exec\n j rt_eval\n j rt_seval\n"
|
||||||
|
" j rt_fn\n j rt_aref\n j rt_pow\n j rt_error\n j rt_break\n j rt_gfx\n"
|
||||||
|
".previous");
|
||||||
|
|
||||||
int main(void)
|
int main(void)
|
||||||
{
|
{
|
||||||
u16 n;
|
u16 n;
|
||||||
@@ -2697,6 +2838,7 @@ int main(void)
|
|||||||
new_prog();
|
new_prog();
|
||||||
g_clear(0);
|
g_clear(0);
|
||||||
newline();
|
newline();
|
||||||
|
out_c(27); out_c('['); out_c('?'); out_c('4'); out_c('7'); out_c('l'); /* off the monitor's screen */
|
||||||
puts_("DARTMOUTH-STYLE BASIC RISC-V ON A BASYS 3");
|
puts_("DARTMOUTH-STYLE BASIC RISC-V ON A BASYS 3");
|
||||||
newline();
|
newline();
|
||||||
if (setjmp(errjmp)) {
|
if (setjmp(errjmp)) {
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ SECTIONS
|
|||||||
*(.rodata .rodata.* .srodata .srodata.*)
|
*(.rodata .rodata.* .srodata .srodata.*)
|
||||||
. = ALIGN(4);
|
. = ALIGN(4);
|
||||||
} > ROM
|
} > ROM
|
||||||
|
/* the jump table for compiled programs (rt_table in basic.c): fixed */
|
||||||
|
.rtab 0x9F00 : { KEEP(*(.rtab)) } > ROM
|
||||||
.arena (NOLOAD) : { KEEP(*(.arena)) } > RAM
|
.arena (NOLOAD) : { KEEP(*(.arena)) } > RAM
|
||||||
.data : ALIGN(4) {
|
.data : ALIGN(4) {
|
||||||
__data_start = .;
|
__data_start = .;
|
||||||
|
|||||||
+3646
-3646
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -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
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
10 REM SOUND DEMO - NEEDS A PMODAMP2 ON THE TOP ROW OF PMOD JA
|
|
||||||
20 REM PITCH = 125000 / FREQUENCY. PORTS: 144-149 PITCHES, 150 NOISE,
|
|
||||||
30 REM 151 MIXER, 152-154 VOLUMES, 155-157 ENVELOPES (ATTACK*16+DECAY)
|
|
||||||
40 PRINT "A SCALE"
|
|
||||||
50 OUT 151, 1: OUT 155, 3
|
|
||||||
60 FOR I = 1 TO 8
|
|
||||||
70 READ P: GOSUB 500
|
|
||||||
80 OUT 152, 15
|
|
||||||
90 IF INP(152) > 0 THEN 90
|
|
||||||
100 NEXT I
|
|
||||||
110 PRINT "A LASER"
|
|
||||||
120 OUT 151, 4: OUT 149, 0: OUT 157, 0: OUT 154, 13
|
|
||||||
130 FOR P = 30 TO 250 STEP 6: OUT 148, P: NEXT P
|
|
||||||
140 OUT 154, 0
|
|
||||||
150 PRINT "AN EXPLOSION"
|
|
||||||
160 OUT 151, 16: OUT 150, 24: OUT 156, 8: OUT 153, 15
|
|
||||||
170 IF INP(153) > 0 THEN 170
|
|
||||||
180 PRINT "A CHORD"
|
|
||||||
190 OUT 151, 7
|
|
||||||
200 OUT 144, 221: OUT 145, 1: OUT 146, 123: OUT 147, 1: OUT 148, 63: OUT 149, 1
|
|
||||||
210 OUT 155, 69: OUT 156, 69: OUT 157, 69
|
|
||||||
220 OUT 152, 12: OUT 153, 12: OUT 154, 12
|
|
||||||
230 IF INP(152) > 0 THEN 230
|
|
||||||
240 END
|
|
||||||
500 OUT 144, P - INT(P / 256) * 256: OUT 145, INT(P / 256): RETURN
|
|
||||||
900 DATA 477, 425, 379, 358, 319, 284, 253, 239
|
|
||||||
@@ -150,6 +150,14 @@ def main():
|
|||||||
''')
|
''')
|
||||||
check("GOTO back to a DO does not fill its stack", " 40 41 END" in out, out)
|
check("GOTO back to a DO does not fill its stack", " 40 41 END" in out, out)
|
||||||
|
|
||||||
|
out = run('''
|
||||||
|
10 A7 = 5: Y = 9: X2 = 3: A = 1: B8 = 2
|
||||||
|
20 FOR Z9 = 1 TO 2: NEXT Z9
|
||||||
|
30 DEF FNQ(Y7) = Y7 * 10
|
||||||
|
40 PRINT A7; Y; X2; A; B8; Z9; FNQ(4); Y7
|
||||||
|
''')
|
||||||
|
check("X1 to Z9 are variables of their own (not A to B9)", " 5 9 3 1 2 3 40 0" in out, out)
|
||||||
|
|
||||||
b.type(b"CLS" + CR)
|
b.type(b"CLS" + CR)
|
||||||
b.type(b'I=0: DO: I=I+1: LOOP UNTIL I=7: PRINT "DIRECT"; I' + CR)
|
b.type(b'I=0: DO: I=I+1: LOOP UNTIL I=7: PRINT "DIRECT"; I' + CR)
|
||||||
check("DO ... LOOP in a direct statement", "DIRECT 7" in screen(), screen())
|
check("DO ... LOOP in a direct statement", "DIRECT 7" in screen(), screen())
|
||||||
|
|||||||
Executable
+286
@@ -0,0 +1,286 @@
|
|||||||
|
#!/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
|
||||||
|
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 == "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()
|
||||||
@@ -102,13 +102,6 @@ set_clock_groups -asynchronous -group [get_clocks sys_clk_pin] \
|
|||||||
-group [get_clocks -of_objects [get_pins pix_mmcm/CLKOUT0]]
|
-group [get_clocks -of_objects [get_pins pix_mmcm/CLKOUT0]]
|
||||||
set_false_path -to [get_ports {led[*] seg[*] dp an[*] RsTx}]
|
set_false_path -to [get_ports {led[*] seg[*] dp an[*] RsTx}]
|
||||||
|
|
||||||
## Pmod JA top row: a PmodAMP2 (AIN, GAIN, NC, SHUTDOWN)
|
|
||||||
set_property -dict { PACKAGE_PIN J1 IOSTANDARD LVCMOS33 } [get_ports {JA[0]}]
|
|
||||||
set_property -dict { PACKAGE_PIN L2 IOSTANDARD LVCMOS33 } [get_ports {JA[1]}]
|
|
||||||
set_property -dict { PACKAGE_PIN J2 IOSTANDARD LVCMOS33 } [get_ports {JA[2]}]
|
|
||||||
set_property -dict { PACKAGE_PIN G2 IOSTANDARD LVCMOS33 } [get_ports {JA[3]}]
|
|
||||||
set_false_path -to [get_ports {JA[*]}]
|
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
set_property CONFIG_VOLTAGE 3.3 [current_design]
|
set_property CONFIG_VOLTAGE 3.3 [current_design]
|
||||||
set_property CFGBVS VCCO [current_design]
|
set_property CFGBVS VCCO [current_design]
|
||||||
|
|||||||
+147
-46
@@ -23,8 +23,11 @@ READY
|
|||||||
|
|
||||||
The computer keeps running while SW15 is down. It just waits until it can print
|
The computer keeps running while SW15 is down. It just waits until it can print
|
||||||
again, so you can flip back and forth without losing your program. **BTND**
|
again, so you can flip back and forth without losing your program. **BTND**
|
||||||
(or **Ctrl-Alt-Del** on the keyboard) restarts the computer; that wipes the program
|
restarts the computer; that wipes the program but not the files in flash.
|
||||||
but not the files in flash. **BTNC** restarts the whole board.
|
**BTNC** restarts the whole board. **Ctrl-Alt-Del** on the keyboard stops the
|
||||||
|
program in the machine-code monitor, wherever it is (section 10); pressed again
|
||||||
|
within 2 seconds, or while the monitor is showing, it restarts the computer as
|
||||||
|
BTND does.
|
||||||
|
|
||||||
### Talking to BASIC
|
### Talking to BASIC
|
||||||
|
|
||||||
@@ -868,7 +871,6 @@ compare value, 10h and 14h the monitor's breakpoint addresses.
|
|||||||
| 112–120, 128–135 | sprites (section 7) | sprites (section 7) |
|
| 112–120, 128–135 | sprites (section 7) | sprites (section 7) |
|
||||||
| 136 | keys held down, for games (below) | — |
|
| 136 | keys held down, for games (below) | — |
|
||||||
| 137 | 1 if the key picked with `OUT 137` is held down, else 0 | pick a key by its scan code |
|
| 137 | 1 if the key picked with `OUT 137` is held down, else 0 | pick a key by its scan code |
|
||||||
| 144–157 | voice volumes now (152–154) | sound (below) |
|
|
||||||
|
|
||||||
```
|
```
|
||||||
10 FOR I = 0 TO 255
|
10 FOR I = 0 TO 255
|
||||||
@@ -917,45 +919,6 @@ game should throw those away now and then with `IF INP(0) AND 1 THEN K =
|
|||||||
INP(1)` in a loop. Held keys only work with the board's own keyboard, not with
|
INP(1)` in a loop. Held keys only work with the board's own keyboard, not with
|
||||||
characters sent from the PC.
|
characters sent from the PC.
|
||||||
|
|
||||||
### Sound
|
|
||||||
|
|
||||||
The board has no speaker of its own. Plug a Digilent **PmodAMP2** into the
|
|
||||||
top row of Pmod header **JA** (pin 1 at the end marked 1) and headphones or a
|
|
||||||
powered speaker into its jack. The FPGA has a little sound chip in the style
|
|
||||||
of the 8-bit computers: three voices that play square-wave tones, a noise
|
|
||||||
source they can use instead or as well, sixteen volumes and an envelope for
|
|
||||||
each voice, so a note or a bang fades away by itself.
|
|
||||||
|
|
||||||
| Port | `OUT` |
|
|
||||||
|---|---|
|
|
||||||
| 144, 145 | voice 0 pitch: low byte, then high byte (0–15) |
|
|
||||||
| 146, 147 | voice 1 pitch |
|
|
||||||
| 148, 149 | voice 2 pitch |
|
|
||||||
| 150 | noise pitch, 0–31 (higher is lower and rougher) |
|
|
||||||
| 151 | mixer: add 1, 2, 4 for the tone of voice 0, 1, 2 and 8, 16, 32 for noise on voice 0, 1, 2 |
|
|
||||||
| 152, 153, 154 | voice 0, 1, 2 volume, 0 (off) to 15, which starts its envelope; `INP` gives the volume it has got to |
|
|
||||||
| 155, 156, 157 | voice 0, 1, 2 envelope: attack × 16 + decay, each 0–15 |
|
|
||||||
|
|
||||||
- **Pitch** = 125000 ÷ frequency: 284 is the A above middle C (440 Hz),
|
|
||||||
477 middle C. Each voice goes from about 30 Hz up beyond hearing.
|
|
||||||
- **Envelope:** with an attack, the volume climbs from 0 to the volume set,
|
|
||||||
one step every attack × 4 ms; then, with a decay, it falls back to 0 one step
|
|
||||||
every decay × 4 ms. 0 means no climb, or hold the volume until it is
|
|
||||||
changed. An envelope of 3 plays a short note; 8 with noise is an explosion.
|
|
||||||
- **Waiting for a sound to end:** `IF INP(152) > 0 THEN …` loops until voice
|
|
||||||
0 has faded out.
|
|
||||||
- A voice that has neither its tone nor noise on in the mixer gives a steady
|
|
||||||
level, so changing its volume clicks; that is how the old chips played
|
|
||||||
samples.
|
|
||||||
- `CLS` silences everything (as does restarting the computer).
|
|
||||||
|
|
||||||
```
|
|
||||||
10 OUT 151, 1: OUT 155, 3 : REM TONE ON VOICE 0, A SHORT NOTE
|
|
||||||
20 OUT 144, 28: OUT 145, 1: OUT 152, 15 : REM PITCH 284 = 440 HZ
|
|
||||||
```
|
|
||||||
|
|
||||||
`basic/examples/sound.bas` plays a scale, a laser, an explosion and a chord.
|
|
||||||
|
|
||||||
### Speed
|
### Speed
|
||||||
|
|
||||||
The processor is a 32-bit RISC-V (RV32IMF: the base instructions, multiply
|
The processor is a 32-bit RISC-V (RV32IMF: the base instructions, multiply
|
||||||
@@ -988,8 +951,14 @@ any code, including BASIC itself.
|
|||||||
|
|
||||||
### Getting in and out
|
### Getting in and out
|
||||||
|
|
||||||
- Press **Pause/Break** on the keyboard at any time, even when a program has
|
- Press **Pause/Break** or **Ctrl-Alt-Del** on the keyboard at any time, even
|
||||||
hung, or type `MONITOR` in BASIC.
|
when a program has hung with its interrupts off, or type `MONITOR` in BASIC.
|
||||||
|
The monitor shows every register as the program left it, and `X` carries
|
||||||
|
on.
|
||||||
|
- **Restarting:** Ctrl-Alt-Del while the monitor is showing, or twice within
|
||||||
|
2 seconds, restarts the computer, as BTND does: the way out of a machine too
|
||||||
|
wedged even for the monitor. So does the monitor's `RESET` command. Holding
|
||||||
|
the keys down counts as one press.
|
||||||
- A breakpoint or a single step also comes back to the monitor.
|
- A breakpoint or a single step also comes back to the monitor.
|
||||||
- So does a program that goes wrong: an illegal instruction, a misaligned load,
|
- So does a program that goes wrong: an illegal instruction, a misaligned load,
|
||||||
store or jump, an `EBREAK` or `ECALL`, or an interrupt with no handler. The
|
store or jump, an `EBREAK` or `ECALL`, or an interrupt with no handler. The
|
||||||
@@ -1019,6 +988,65 @@ 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, with
|
Type a command on the bottom line and press Enter. Numbers are in hex, with
|
||||||
@@ -1035,8 +1063,8 @@ or without `0x`.
|
|||||||
| `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 (A000 or above) |
|
| `LOAD "NAME" addr` | Load it at *addr* instead (A000 or above) |
|
||||||
@@ -1045,6 +1073,7 @@ or without `0x`.
|
|||||||
| `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 |
|
||||||
| Up / Down | Scroll the disassembly by one instruction |
|
| Up / Down | Scroll the disassembly by one instruction |
|
||||||
| Page Up / Page Down | Scroll the memory window |
|
| Page Up / Page Down | Scroll the memory window |
|
||||||
|
| `RESET` | Restart the computer, as BTND does (the program in memory is lost; files in flash are not) |
|
||||||
| `?` | A short reminder of the commands |
|
| `?` | A short reminder of the commands |
|
||||||
| `:` *record* | An Intel HEX record, written into memory (`tools/send-hex.py` sends whole files this way; see section 12) |
|
| `:` *record* | An Intel HEX record, written into memory (`tools/send-hex.py` sends whole files this way; see section 12) |
|
||||||
|
|
||||||
@@ -1392,6 +1421,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,
|
||||||
|
`DATA` and `READ`, `DEF FN`, and functions such as `LEN` and `MOD`) is handed
|
||||||
|
to BASIC in the ROM as it stands, so it behaves exactly as it does
|
||||||
|
interpreted, at about the same speed. A program that spends its time
|
||||||
|
calculating, looping and drawing gains most; one that mostly prints gains
|
||||||
|
little. The graphics demo (`basic/examples/graphics-demo.bas`) runs 4.7 times
|
||||||
|
as fast.
|
||||||
|
|
||||||
|
```
|
||||||
|
tools/basc.py spiral.bas
|
||||||
|
```
|
||||||
|
|
||||||
|
writes `SPIRAL.ihx`, the program, and `SPIRAL.bas`, a two-line loader, next
|
||||||
|
to `spiral.bas` (`-o` puts them elsewhere, `--name` names them). It tells you
|
||||||
|
how much room the program takes. Then send both, and save the loader:
|
||||||
|
|
||||||
|
```
|
||||||
|
tools/send-hex.py SPIRAL.ihx --save SPIRALC --baud 3000000
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
tools/send-bas.py SPIRAL.bas --baud 3000000
|
||||||
|
```
|
||||||
|
|
||||||
|
and `SAVE "SPIRAL"`. From then on `RUN "SPIRAL"` loads the machine code
|
||||||
|
(the memory file `SPIRALC`) and runs it. It works like the games: it loads at
|
||||||
|
0xA200, in the program area, after the loader.
|
||||||
|
|
||||||
|
- **Variables** are BASIC's own: the program starts with them cleared, as
|
||||||
|
`RUN` does, and they are still there when it ends, for `PRINT`.
|
||||||
|
- **Errors** stop the program with BASIC's message and line number, as they
|
||||||
|
would interpreted. **Ctrl-C** is looked for at every 64th jump (`NEXT`,
|
||||||
|
`LOOP`, `GOTO`, `GOSUB`, `RETURN` or `ON`), so it stops any loop.
|
||||||
|
- **Room:** the program and its variables must fit between 0xA200 and
|
||||||
|
0xF0B7, about 20 KB, less what its arrays need. The graphics demo
|
||||||
|
compiles to 12 KB.
|
||||||
|
- **Not allowed:** `RUN`, `LIST`, `NEW`, `LOAD`, `SAVE` and `RENUM` make no
|
||||||
|
sense inside a compiled program, and `basc` says so.
|
||||||
|
- **Loops:** each `LOOP` goes back to the `DO` before it that it belongs to,
|
||||||
|
by position, where the interpreter keeps a list of `DO`s it has run; in a
|
||||||
|
program that jumps out of a `DO` loop with `GOTO` and back into another the
|
||||||
|
two can differ.
|
||||||
|
- **Which BASIC:** a compiled program calls BASIC through a table at 0x9F00
|
||||||
|
that later versions keep. If BASIC is too old or too new for it, the
|
||||||
|
program stops with `PROGRAM NEEDS ANOTHER BASIC`; compile it again.
|
||||||
|
|
||||||
|
`basc` needs Python 3 and a RISC-V GCC (the one that comes with Vivado will
|
||||||
|
do; the README says where).
|
||||||
|
`--fast` compiles for speed rather than size, though it makes little
|
||||||
|
difference. `--keep-c` keeps the C it makes on the way, for the curious.
|
||||||
|
|
||||||
When you're done, flip SW14 back down, and bring the getty back with
|
When you're done, flip SW14 back down, and bring the getty back with
|
||||||
`sudo systemctl unmask --runtime serial-getty@ttyUSB1` (a reboot does it too).
|
`sudo systemctl unmask --runtime serial-getty@ttyUSB1` (a reboot does it too).
|
||||||
Don't do that with SW14 up.
|
Don't do that with SW14 up.
|
||||||
@@ -1422,6 +1522,7 @@ An error stops the program and reports the line, for example
|
|||||||
| `LOOP WITHOUT DO` | `LOOP` or `EXIT DO` with no `DO` loop open |
|
| `LOOP WITHOUT DO` | `LOOP` or `EXIT DO` with no `DO` loop open |
|
||||||
| `IF WITHOUT END IF` | A block `IF` (or its `ELSE`) with no `END IF` after it |
|
| `IF WITHOUT END IF` | A block `IF` (or its `ELSE`) with no `END IF` after it |
|
||||||
| `SELECT WITHOUT END SELECT` | A `SELECT CASE` (or its `CASE`) with no `END SELECT` after it |
|
| `SELECT WITHOUT END SELECT` | A `SELECT CASE` (or its `CASE`) with no `END SELECT` after it |
|
||||||
|
| `PROGRAM NEEDS ANOTHER BASIC` | A compiled program (section 12) made for a different version of BASIC |
|
||||||
| `GOSUB NESTED TOO DEEPLY` | More than 32 subroutines in progress |
|
| `GOSUB NESTED TOO DEEPLY` | More than 32 subroutines in progress |
|
||||||
| `FILE NOT FOUND` | `LOAD`, `RUN` or `DEL` of a name not in `DIR` |
|
| `FILE NOT FOUND` | `LOAD`, `RUN` or `DEL` of a name not in `DIR` |
|
||||||
| `BAD FILE NAME` | A name that is empty, longer than 8 or not just letters and digits |
|
| `BAD FILE NAME` | A name that is empty, longer than 8 or not just letters and digits |
|
||||||
|
|||||||
Binary file not shown.
+20
-25
@@ -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
@@ -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])
|
||||||
+2
-2
@@ -463,7 +463,7 @@ enum {
|
|||||||
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_FR, P_FS
|
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 },
|
||||||
@@ -740,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;
|
||||||
|
|||||||
Binary file not shown.
+206
-53
@@ -411,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 */
|
||||||
@@ -454,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++) {
|
||||||
@@ -479,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();
|
||||||
@@ -492,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -511,10 +642,9 @@ static void draw_fregs(void)
|
|||||||
if (!u.fs) { if (r == 0) s_str(" THE FPU IS OFF (MSTATUS.FS = 0)"); }
|
if (!u.fs) { if (r == 0) s_str(" THE FPU IS OFF (MSTATUS.FS = 0)"); }
|
||||||
else for (i = 0; i < 6; i++) {
|
else for (i = 0; i < 6; i++) {
|
||||||
u8 k = r * 6 + i;
|
u8 k = r * 6 + i;
|
||||||
char n[4];
|
char n[6], *o = lp;
|
||||||
if (k < 32) {
|
if (k < 32) {
|
||||||
n[0] = 'F'; n[1] = k < 10 ? '0' + k : '0' + k / 10;
|
lp = n; s_freg(k); *lp = 0; lp = o; /* FT0 ... by ABI name */
|
||||||
n[2] = k < 10 ? 0 : '0' + k % 10; n[3] = 0;
|
|
||||||
s_rv(n, u.f[k]);
|
s_rv(n, u.f[k]);
|
||||||
} else if (k == 32) s_rv("FCSR", u.fcsr);
|
} else if (k == 32) s_rv("FCSR", u.fcsr);
|
||||||
}
|
}
|
||||||
@@ -526,7 +656,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;
|
||||||
@@ -539,51 +669,62 @@ 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";
|
||||||
case 3: return "STEP";
|
case 3: return "STEP";
|
||||||
case 4: return "BREAKPOINT";
|
case 4: return "BREAKPOINT";
|
||||||
case 5: return "STEP OVER";
|
case 5: return "STEP OVER";
|
||||||
|
case 6: return "CTRL-ALT-DEL";
|
||||||
default: return "";
|
default: return "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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");
|
||||||
}
|
}
|
||||||
@@ -609,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"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -619,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();
|
||||||
@@ -1053,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;
|
||||||
@@ -1129,6 +1272,11 @@ static u8 command(void)
|
|||||||
skip_sp();
|
skip_sp();
|
||||||
msg = 0; msg_err = 0;
|
msg = 0; msg_err = 0;
|
||||||
if (*cp == ':') { hex_record(); return 0; }
|
if (*cp == ':') { hex_record(); return 0; }
|
||||||
|
if (!memcmp(cp, "RESET", 5)) { /* restart the computer, as BTND does */
|
||||||
|
puts_("\033[?47l");
|
||||||
|
IO8(0x62) = 0;
|
||||||
|
for (;;);
|
||||||
|
}
|
||||||
if (!memcmp(cp, "ASM", 3)) {
|
if (!memcmp(cp, "ASM", 3)) {
|
||||||
cp += 3;
|
cp += 3;
|
||||||
if (setjmp(fs_jmp)) { msg = fs_msg; msg_err = 1; return 0; }
|
if (setjmp(fs_jmp)) { msg = fs_msg; msg_err = 1; return 0; }
|
||||||
@@ -1203,12 +1351,13 @@ 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";
|
||||||
return 0;
|
return 0;
|
||||||
case 'R':
|
case 'R':
|
||||||
if (!set_reg()) { msg = "R PC|X1-X31|RA|SP|A0...|F0-F31|FCSR = VALUE"; msg_err = 1; return 0; }
|
if (!set_reg()) { msg = "R REG=HEX: PC A0 X10 FA0 F10 FCSR ..."; msg_err = 1; return 0; }
|
||||||
draw_regs(); draw_dis(); draw_stack(); draw_mem();
|
draw_regs(); draw_dis(); draw_stack(); draw_mem();
|
||||||
return 0;
|
return 0;
|
||||||
case '?':
|
case '?':
|
||||||
@@ -1243,6 +1392,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 */
|
||||||
@@ -1260,6 +1410,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
|
||||||
+3319
-3319
File diff suppressed because it is too large.
Load diff
+32
-10
@@ -56,8 +56,7 @@ module basys3_terminal #(
|
|||||||
input PS2Clk,
|
input PS2Clk,
|
||||||
input PS2Data,
|
input PS2Data,
|
||||||
output QspiCSn,
|
output QspiCSn,
|
||||||
inout [3:0] QspiDB,
|
inout [3:0] QspiDB
|
||||||
output [3:0] JA // PmodAMP2: audio in, gain, -, shutdown (low)
|
|
||||||
);
|
);
|
||||||
localparam [7:0] XON = 8'h11, XOFF = 8'h13;
|
localparam [7:0] XON = 8'h11, XOFF = 8'h13;
|
||||||
|
|
||||||
@@ -127,9 +126,34 @@ module basys3_terminal #(
|
|||||||
.clk(clk), .rst(rst | ~rv_mode), .code(scan), .code_valid(scan_valid), .down(keys_down)
|
.clk(clk), .rst(rst | ~rv_mode), .code(scan), .code_valid(scan_valid), .down(keys_down)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Ctrl-Alt-Del in computer mode restarts the computer, like BTND (held 1 us)
|
// Ctrl-Alt-Del in computer mode enters the monitor (an NMI, like Pause).
|
||||||
|
// It restarts the computer instead, like BTND (held 1 us), when the monitor
|
||||||
|
// is already running or an NMI is still waiting to be taken (the CPU is
|
||||||
|
// wedged), or when it comes again within 2 s. A press counts only after
|
||||||
|
// Delete has been up for 5 ms, so holding the keys (which repeats Delete)
|
||||||
|
// is one press. Port 62 (the monitor's RESET) restarts the computer too.
|
||||||
|
wire mon_busy, reset_t;
|
||||||
|
(* ASYNC_REG = "TRUE" *) reg [1:0] busy_s = 2'd0;
|
||||||
|
(* ASYNC_REG = "TRUE" *) reg [2:0] rreq_s = 3'd0;
|
||||||
|
always @(posedge clk) begin
|
||||||
|
busy_s <= {busy_s[0], mon_busy};
|
||||||
|
rreq_s <= {rreq_s[1:0], reset_t};
|
||||||
|
end
|
||||||
|
reg [19:0] del_up = 20'd0; // how long Delete has been up
|
||||||
|
reg [27:0] cad_win = 28'd0; // counts down 2 s after a press
|
||||||
|
reg cad_nmi_t = 1'b0; // toggles: enter the monitor
|
||||||
|
wire del_held = keys_down[8'h71] | keys_down[8'hF1];
|
||||||
|
wire cad_new = cad && rv_mode && del_up[19];
|
||||||
|
wire cad_rst = cad_new && (busy_s[1] || cad_win != 0);
|
||||||
reg [6:0] cad_t = 7'd0;
|
reg [6:0] cad_t = 7'd0;
|
||||||
always @(posedge clk) cad_t <= cad && rv_mode ? 7'd100 : cad_t - (cad_t != 0);
|
always @(posedge clk) begin
|
||||||
|
if (rst || del_held || (cad && rv_mode)) del_up <= 20'd0;
|
||||||
|
else del_up <= del_up + {19'd0, !del_up[19]};
|
||||||
|
if (rst) cad_win <= 28'd0;
|
||||||
|
else cad_win <= cad_new ? CLK_HZ * 2 : cad_win - (cad_win != 0);
|
||||||
|
if (cad_new && !cad_rst) cad_nmi_t <= ~cad_nmi_t;
|
||||||
|
cad_t <= cad_rst || (rreq_s[2] ^ rreq_s[1]) ? 7'd100 : cad_t - (cad_t != 0);
|
||||||
|
end
|
||||||
|
|
||||||
// ----------------------------------------------------------- host input
|
// ----------------------------------------------------------- host input
|
||||||
// Keyboard bytes and terminal replies go to the host: the PC's UART, or in
|
// Keyboard bytes and terminal replies go to the host: the PC's UART, or in
|
||||||
@@ -345,6 +369,8 @@ module basys3_terminal #(
|
|||||||
always @(posedge clk) if (scan_valid && scan == 8'hE1 && rv_mode) brk_t <= ~brk_t;
|
always @(posedge clk) if (scan_valid && scan == 8'hE1 && rv_mode) brk_t <= ~brk_t;
|
||||||
(* ASYNC_REG = "TRUE" *) reg [2:0] brk_s = 3'd0;
|
(* ASYNC_REG = "TRUE" *) reg [2:0] brk_s = 3'd0;
|
||||||
always @(posedge cpu_clk) brk_s <= {brk_s[1:0], brk_t};
|
always @(posedge cpu_clk) brk_s <= {brk_s[1:0], brk_t};
|
||||||
|
(* ASYNC_REG = "TRUE" *) reg [2:0] cad_s = 3'd0;
|
||||||
|
always @(posedge cpu_clk) cad_s <= {cad_s[1:0], cad_nmi_t};
|
||||||
|
|
||||||
wire wide; // DECCOLM from the terminal (term_ctrl below)
|
wire wide; // DECCOLM from the terminal (term_ctrl below)
|
||||||
rv32_system #(.MEM_FILE(MEM_FILE), .MEM_HI_FILE(MEM_HI_FILE), .MON_FILE(MON_FILE), .CPU_HZ(CPU_HZ), .ROM_TOP(ROM_TOP)) sys (
|
rv32_system #(.MEM_FILE(MEM_FILE), .MEM_HI_FILE(MEM_HI_FILE), .MON_FILE(MON_FILE), .CPU_HZ(CPU_HZ), .ROM_TOP(ROM_TOP)) sys (
|
||||||
@@ -352,19 +378,15 @@ module basys3_terminal #(
|
|||||||
.rx_req(zrx_req), .rx_data(zrx_data), .rx_ack(zrx_ack),
|
.rx_req(zrx_req), .rx_data(zrx_data), .rx_ack(zrx_ack),
|
||||||
.tx_req(ztx_req), .tx_data(ztx_data), .tx_ack(ztx_ack), .wide(wide),
|
.tx_req(ztx_req), .tx_data(ztx_data), .tx_ack(ztx_ack), .wide(wide),
|
||||||
.seg_val(rv_seg), .halted(), .brk_key(brk_s[2] ^ brk_s[1]),
|
.seg_val(rv_seg), .halted(), .brk_key(brk_s[2] ^ brk_s[1]),
|
||||||
|
.cad_key(cad_s[2] ^ cad_s[1]), .mon_busy(mon_busy), .reset_t(reset_t),
|
||||||
.vclk(pix_clk), .gfx_vaddr(gfx_addr), .gfx_vpix(gfx_pix),
|
.vclk(pix_clk), .gfx_vaddr(gfx_addr), .gfx_vpix(gfx_pix),
|
||||||
.scroll_x(scroll_x), .scroll_y(scroll_y), .g_border(g_border),
|
.scroll_x(scroll_x), .scroll_y(scroll_y), .g_border(g_border),
|
||||||
.g_hires(g_hires), .g_cols(g_cols),
|
.g_hires(g_hires), .g_cols(g_cols),
|
||||||
.sp_go(sp_go), .sp_line(sp_line), .sp_buf(sp_buf), .sp_x(sp_x), .sp_on(sp_on),
|
.sp_go(sp_go), .sp_line(sp_line), .sp_buf(sp_buf), .sp_x(sp_x), .sp_on(sp_on),
|
||||||
.sp_pix(sp_pix), .sp_ftick(pix_frame), .keys(keys_down),
|
.sp_pix(sp_pix), .sp_ftick(pix_frame), .keys(keys_down),
|
||||||
.fl_cs_n(QspiCSn), .fl_sck(fl_sck), .fl_mosi(QspiDB[0]), .fl_miso(QspiDB[1]),
|
.fl_cs_n(QspiCSn), .fl_sck(fl_sck), .fl_mosi(QspiDB[0]), .fl_miso(QspiDB[1])
|
||||||
.audio(JA[0])
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// PmodAMP2 on JA's top row: gain high is 6 dB (low would be 12 dB), and
|
|
||||||
// the amplifier is on unless its shutdown pin is low.
|
|
||||||
assign JA[3:1] = 3'b101;
|
|
||||||
|
|
||||||
// The flash clock is the configuration clock pin, reached through STARTUPE2.
|
// The flash clock is the configuration clock pin, reached through STARTUPE2.
|
||||||
// DQ2/DQ3 (write protect, hold) stay high.
|
// DQ2/DQ3 (write protect, hold) stay high.
|
||||||
assign QspiDB[1] = 1'bz;
|
assign QspiDB[1] = 1'bz;
|
||||||
|
|||||||
+4
-2
@@ -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;
|
||||||
|
|||||||
+11
-14
@@ -42,8 +42,9 @@
|
|||||||
// 40 SPI flash control, 41 SPI flash data (see flash_spi.v)
|
// 40 SPI flash control, 41 SPI flash data (see flash_spi.v)
|
||||||
// 60 out bit 1 = stop again (NMI) after one instruction of the program
|
// 60 out bit 1 = stop again (NMI) after one instruction of the program
|
||||||
// in why the last NMI came: 1 Pause key, 2 port 61, 3 step,
|
// in why the last NMI came: 1 Pause key, 2 port 61, 3 step,
|
||||||
// 4 breakpoint 0, 5 breakpoint 1
|
// 4 breakpoint 0, 5 breakpoint 1, 6 Ctrl-Alt-Del
|
||||||
// 61 out enter the monitor (NMI)
|
// 61 out enter the monitor (NMI)
|
||||||
|
// 62 out restart the computer (as BTND does; the monitor's RESET)
|
||||||
// 67 out bit 0 = breakpoint 0 on, bit 1 = breakpoint 1 on
|
// 67 out bit 0 = breakpoint 0 on, bit 1 = breakpoint 1 on
|
||||||
// 70-78, 80-87 sprites (see sprites.v)
|
// 70-78, 80-87 sprites (see sprites.v)
|
||||||
// 88 in keys held: bit 0 up (W, cursor or keypad 8), 1 down (S, 2), 2 left
|
// 88 in keys held: bit 0 up (W, cursor or keypad 8), 1 down (S, 2), 2 left
|
||||||
@@ -51,7 +52,6 @@
|
|||||||
// 7 Esc
|
// 7 Esc
|
||||||
// 89 out pick a scan code (set 2; add 128 for an E0 code)
|
// 89 out pick a scan code (set 2; add 128 for an E0 code)
|
||||||
// in 1 if that key is held, else 0
|
// in 1 if that key is held, else 0
|
||||||
// 90-9D sound (see sound.v)
|
|
||||||
// The Z-80's debug-read ports (62-64) are gone: the monitor runs in the same
|
// The Z-80's debug-read ports (62-64) are gone: the monitor runs in the same
|
||||||
// address space as the program. Its breakpoint addresses are 32 bits, below.
|
// address space as the program. Its breakpoint addresses are 32 bits, below.
|
||||||
//
|
//
|
||||||
@@ -88,6 +88,9 @@ module rv32_system #(
|
|||||||
output reg [15:0] seg_val,
|
output reg [15:0] seg_val,
|
||||||
output halted,
|
output halted,
|
||||||
input brk_key, // pulse: the Pause key, enter the monitor
|
input brk_key, // pulse: the Pause key, enter the monitor
|
||||||
|
input cad_key, // pulse: Ctrl-Alt-Del, enter the monitor too
|
||||||
|
output mon_busy, // the monitor runs, or an NMI waits to be taken
|
||||||
|
output reg reset_t = 1'b0, // toggles: port 62, restart the computer
|
||||||
// graphics layer read port, on the video clock
|
// graphics layer read port, on the video clock
|
||||||
input vclk,
|
input vclk,
|
||||||
input [16:0] gfx_vaddr,
|
input [16:0] gfx_vaddr,
|
||||||
@@ -111,9 +114,7 @@ module rv32_system #(
|
|||||||
output fl_cs_n,
|
output fl_cs_n,
|
||||||
output fl_sck,
|
output fl_sck,
|
||||||
output fl_mosi,
|
output fl_mosi,
|
||||||
input fl_miso,
|
input fl_miso
|
||||||
// sound, for a PmodAMP2
|
|
||||||
output audio
|
|
||||||
);
|
);
|
||||||
localparam [31:0] MON_BASE = 32'h0002_0000;
|
localparam [31:0] MON_BASE = 32'h0002_0000;
|
||||||
assign halted = 1'b0;
|
assign halted = 1'b0;
|
||||||
@@ -366,13 +367,6 @@ module rv32_system #(
|
|||||||
.rd_on(sp_on), .pix(sp_pix), .gfx_pix(gfx_vpix), .ftick(sp_ftick)
|
.rd_on(sp_on), .pix(sp_pix), .gfx_pix(gfx_vpix), .ftick(sp_ftick)
|
||||||
);
|
);
|
||||||
|
|
||||||
// ---------------------------------------------------------------- sound
|
|
||||||
wire [7:0] snd_q;
|
|
||||||
sound #(.CPU_HZ(CPU_HZ)) snd (
|
|
||||||
.clk(clk), .rst(rst), .hush(io_wr && io_addr == 8'h34 && !io_wd[7]),
|
|
||||||
.io_wr(io_wr), .io_port(io_addr), .io_wd(io_wd), .io_q(snd_q), .audio(audio)
|
|
||||||
);
|
|
||||||
|
|
||||||
// ---------------------------------------------------------- held keys
|
// ---------------------------------------------------------- held keys
|
||||||
// The keyboard's clock writes these; a bit that changes while it is read
|
// The keyboard's clock writes these; a bit that changes while it is read
|
||||||
// just reads as before or after.
|
// just reads as before or after.
|
||||||
@@ -447,6 +441,8 @@ module rv32_system #(
|
|||||||
if (!nmi_r && !in_mon) begin
|
if (!nmi_r && !in_mon) begin
|
||||||
if (brk_key) begin
|
if (brk_key) begin
|
||||||
nmi_r <= 1'b1; why_r <= 3'd1;
|
nmi_r <= 1'b1; why_r <= 3'd1;
|
||||||
|
end else if (cad_key) begin
|
||||||
|
nmi_r <= 1'b1; why_r <= 3'd6;
|
||||||
end else if (io_wr && io_addr == 8'h61) begin
|
end else if (io_wr && io_addr == 8'h61) begin
|
||||||
nmi_r <= 1'b1; why_r <= 3'd2;
|
nmi_r <= 1'b1; why_r <= 3'd2;
|
||||||
end
|
end
|
||||||
@@ -459,6 +455,9 @@ module rv32_system #(
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
assign mon_busy = nmi_r || in_mon;
|
||||||
|
always @(posedge clk) if (io_wr && io_addr == 8'h62) reset_t <= ~reset_t;
|
||||||
|
|
||||||
(* ASYNC_REG = "TRUE" *) reg [1:0] wide_s = 2'b00;
|
(* ASYNC_REG = "TRUE" *) reg [1:0] wide_s = 2'b00;
|
||||||
always @(posedge clk) wide_s <= {wide_s[0], wide};
|
always @(posedge clk) wide_s <= {wide_s[0], wide};
|
||||||
|
|
||||||
@@ -480,8 +479,6 @@ module rv32_system #(
|
|||||||
io_din = spr_q;
|
io_din = spr_q;
|
||||||
8'h88: io_din = joy;
|
8'h88: io_din = joy;
|
||||||
8'h89: io_din = {7'd0, keys[key_sel]};
|
8'h89: io_din = {7'd0, keys[key_sel]};
|
||||||
8'h98, 8'h99, 8'h9A:
|
|
||||||
io_din = snd_q;
|
|
||||||
default: io_din = 8'hFF;
|
default: io_din = 8'hFF;
|
||||||
endcase
|
endcase
|
||||||
always @* case (io_a[7:0])
|
always @* case (io_a[7:0])
|
||||||
|
|||||||
-173
@@ -1,173 +0,0 @@
|
|||||||
`timescale 1ns / 1ps
|
|
||||||
// A small sound chip for the Z-80, in the style of the 8-bit era's
|
|
||||||
// programmable sound generators, played through a Digilent PmodAMP2.
|
|
||||||
//
|
|
||||||
// Three square-wave voices and a noise source. Each voice plays its tone,
|
|
||||||
// the noise, or both (the mixer), at one of 16 volumes on a log scale (about
|
|
||||||
// 3 dB a step). A volume write starts an envelope: an optional rise from 0 at
|
|
||||||
// the attack rate, then an optional fall to 0 at the decay rate, so a game
|
|
||||||
// can fire off a shot or an explosion with a few OUTs and leave it.
|
|
||||||
//
|
|
||||||
// 90h/91h voice 0 pitch, low byte / high 4 bits frequency = 125000 / pitch Hz
|
|
||||||
// 92h/93h voice 1 pitch (pitch 0 counts as 1)
|
|
||||||
// 94h/95h voice 2 pitch
|
|
||||||
// 96h noise pitch, 0-31: higher is lower and rougher
|
|
||||||
// 97h mixer: bits 0-2 tone on for voices 0-2, bits 3-5 noise on for them
|
|
||||||
// 98h-9Ah voice 0-2 volume 0-15, which (re)starts its envelope; reading
|
|
||||||
// gives the volume it is at now, so 0 means the sound has ended
|
|
||||||
// 9Bh-9Dh voice 0-2 envelope: high nibble attack, low nibble decay, each
|
|
||||||
// n x 4 ms a volume step (0 = jump straight up / hold)
|
|
||||||
//
|
|
||||||
// A voice with neither its tone nor the noise on outputs a steady level, as
|
|
||||||
// on the old chips. `hush` (CLS) and reset silence everything.
|
|
||||||
//
|
|
||||||
// The three voices are added up and turned into a single bit by a first-order
|
|
||||||
// sigma-delta modulator at the full clock rate; the PmodAMP2 filters it and
|
|
||||||
// drives headphones or a speaker.
|
|
||||||
module sound #(
|
|
||||||
parameter CPU_HZ = 100_000_000
|
|
||||||
) (
|
|
||||||
input clk,
|
|
||||||
input rst,
|
|
||||||
input hush,
|
|
||||||
input io_wr,
|
|
||||||
input [7:0] io_port,
|
|
||||||
input [7:0] io_wd,
|
|
||||||
output reg [7:0] io_q, // for reads of 98h-9Ah
|
|
||||||
output reg audio = 1'b0
|
|
||||||
);
|
|
||||||
localparam TICK_DIV = CPU_HZ / 250_000; // tone counters run at 250 kHz
|
|
||||||
localparam MS4_DIV = CPU_HZ / 250; // envelope steps in 4 ms units
|
|
||||||
|
|
||||||
reg [11:0] pitch [0:2];
|
|
||||||
reg [4:0] npitch;
|
|
||||||
reg [5:0] mixer;
|
|
||||||
reg [3:0] vol [0:2]; // the volume asked for
|
|
||||||
reg [3:0] cur [0:2]; // the volume now
|
|
||||||
reg [3:0] att [0:2], dec [0:2];
|
|
||||||
reg rising [0:2];
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- ticks
|
|
||||||
reg [9:0] tdiv = 10'd0;
|
|
||||||
reg tick = 1'b0;
|
|
||||||
reg [19:0] ediv = 20'd0;
|
|
||||||
reg etick = 1'b0;
|
|
||||||
always @(posedge clk) begin
|
|
||||||
tick <= tdiv == 0;
|
|
||||||
tdiv <= tdiv == 0 ? TICK_DIV - 1 : tdiv - 1'b1;
|
|
||||||
etick <= ediv == 0;
|
|
||||||
ediv <= ediv == 0 ? MS4_DIV - 1 : ediv - 1'b1;
|
|
||||||
end
|
|
||||||
|
|
||||||
// --------------------------------------------------------------- voices
|
|
||||||
reg [11:0] tcnt [0:2];
|
|
||||||
reg [2:0] tone = 3'd0;
|
|
||||||
reg [4:0] ncnt = 5'd0;
|
|
||||||
reg [16:0] lfsr = 17'd1;
|
|
||||||
reg [3:0] ecnt [0:2];
|
|
||||||
integer i;
|
|
||||||
initial for (i = 0; i < 3; i = i + 1) begin
|
|
||||||
tcnt[i] = 12'd0; ecnt[i] = 4'd0; cur[i] = 4'd0; vol[i] = 4'd0;
|
|
||||||
end
|
|
||||||
|
|
||||||
always @(posedge clk) begin
|
|
||||||
if (rst || hush) begin
|
|
||||||
for (i = 0; i < 3; i = i + 1) begin
|
|
||||||
vol[i] <= 4'd0; cur[i] <= 4'd0; rising[i] <= 1'b0;
|
|
||||||
if (rst) begin pitch[i] <= 12'd0; att[i] <= 4'd0; dec[i] <= 4'd0; end
|
|
||||||
end
|
|
||||||
mixer <= 6'd0;
|
|
||||||
if (rst) begin npitch <= 5'd0; lfsr <= 17'd1; tone <= 3'd0; end
|
|
||||||
end else begin
|
|
||||||
if (io_wr) case (io_port)
|
|
||||||
8'h90: pitch[0][7:0] <= io_wd;
|
|
||||||
8'h91: pitch[0][11:8] <= io_wd[3:0];
|
|
||||||
8'h92: pitch[1][7:0] <= io_wd;
|
|
||||||
8'h93: pitch[1][11:8] <= io_wd[3:0];
|
|
||||||
8'h94: pitch[2][7:0] <= io_wd;
|
|
||||||
8'h95: pitch[2][11:8] <= io_wd[3:0];
|
|
||||||
8'h96: npitch <= io_wd[4:0];
|
|
||||||
8'h97: mixer <= io_wd[5:0];
|
|
||||||
8'h9B: {att[0], dec[0]} <= io_wd;
|
|
||||||
8'h9C: {att[1], dec[1]} <= io_wd;
|
|
||||||
8'h9D: {att[2], dec[2]} <= io_wd;
|
|
||||||
default: ;
|
|
||||||
endcase
|
|
||||||
|
|
||||||
// tones: each output flips every `pitch` ticks
|
|
||||||
if (tick) begin
|
|
||||||
for (i = 0; i < 3; i = i + 1)
|
|
||||||
if (tcnt[i] <= 12'd1) begin
|
|
||||||
tcnt[i] <= pitch[i];
|
|
||||||
tone[i] <= ~tone[i];
|
|
||||||
end else
|
|
||||||
tcnt[i] <= tcnt[i] - 1'b1;
|
|
||||||
if (ncnt == 0) begin
|
|
||||||
ncnt <= npitch;
|
|
||||||
lfsr <= {lfsr[0] ^ lfsr[3], lfsr[16:1]};
|
|
||||||
end else
|
|
||||||
ncnt <= ncnt - 1'b1;
|
|
||||||
end
|
|
||||||
|
|
||||||
// envelopes
|
|
||||||
for (i = 0; i < 3; i = i + 1) begin
|
|
||||||
if (io_wr && io_port == 8'h98 + i) begin
|
|
||||||
vol[i] <= io_wd[3:0];
|
|
||||||
ecnt[i] <= 4'd0;
|
|
||||||
if (att[i] != 0 && io_wd[3:0] != 0) begin
|
|
||||||
cur[i] <= 4'd0; rising[i] <= 1'b1;
|
|
||||||
end else begin
|
|
||||||
cur[i] <= io_wd[3:0]; rising[i] <= 1'b0;
|
|
||||||
end
|
|
||||||
end else if (etick) begin
|
|
||||||
if (rising[i]) begin
|
|
||||||
if (ecnt[i] + 1'b1 >= att[i]) begin
|
|
||||||
ecnt[i] <= 4'd0;
|
|
||||||
cur[i] <= cur[i] + 1'b1;
|
|
||||||
if (cur[i] + 1'b1 >= vol[i]) rising[i] <= 1'b0;
|
|
||||||
end else
|
|
||||||
ecnt[i] <= ecnt[i] + 1'b1;
|
|
||||||
end else if (dec[i] != 0 && cur[i] != 0) begin
|
|
||||||
if (ecnt[i] + 1'b1 >= dec[i]) begin
|
|
||||||
ecnt[i] <= 4'd0;
|
|
||||||
cur[i] <= cur[i] - 1'b1;
|
|
||||||
end else
|
|
||||||
ecnt[i] <= ecnt[i] + 1'b1;
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
always @* case (io_port)
|
|
||||||
8'h98: io_q = {4'd0, cur[0]};
|
|
||||||
8'h99: io_q = {4'd0, cur[1]};
|
|
||||||
8'h9A: io_q = {4'd0, cur[2]};
|
|
||||||
default: io_q = 8'hFF;
|
|
||||||
endcase
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- mixing
|
|
||||||
function [7:0] level(input [3:0] v); // about 3 dB a step
|
|
||||||
case (v)
|
|
||||||
4'd0: level = 8'd0; 4'd1: level = 8'd2; 4'd2: level = 8'd3; 4'd3: level = 8'd4;
|
|
||||||
4'd4: level = 8'd6; 4'd5: level = 8'd8; 4'd6: level = 8'd11; 4'd7: level = 8'd16;
|
|
||||||
4'd8: level = 8'd23; 4'd9: level = 8'd32; 4'd10: level = 8'd45; 4'd11: level = 8'd64;
|
|
||||||
4'd12: level = 8'd90; 4'd13: level = 8'd128; 4'd14: level = 8'd181; default: level = 8'd255;
|
|
||||||
endcase
|
|
||||||
endfunction
|
|
||||||
|
|
||||||
wire [2:0] on;
|
|
||||||
genvar g;
|
|
||||||
generate for (g = 0; g < 3; g = g + 1) begin : mix
|
|
||||||
assign on[g] = (tone[g] | ~mixer[g]) & (lfsr[0] | ~mixer[g + 3]);
|
|
||||||
end endgenerate
|
|
||||||
|
|
||||||
reg [9:0] sum = 10'd0;
|
|
||||||
reg [10:0] acc = 11'd0;
|
|
||||||
always @(posedge clk) begin
|
|
||||||
sum <= (on[0] ? level(cur[0]) : 10'd0) + (on[1] ? level(cur[1]) : 10'd0) +
|
|
||||||
(on[2] ? level(cur[2]) : 10'd0);
|
|
||||||
acc <= rst ? 11'd0 : {1'b0, acc[9:0]} + {1'b0, sum}; // carry out = the output bit
|
|
||||||
audio <= acc[10];
|
|
||||||
end
|
|
||||||
endmodule
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
# Run the sound chip's testbench (sim/tb_sound.v) in Vivado's simulator.
|
|
||||||
set -e
|
|
||||||
cd "$(dirname "$0")/.."
|
|
||||||
ROOT=$(pwd)
|
|
||||||
source scripts/vivado_env.sh
|
|
||||||
mkdir -p sim/work-sound
|
|
||||||
cd sim/work-sound
|
|
||||||
xvlog "$ROOT"/rtl/sound.v "$ROOT"/sim/tb_sound.v
|
|
||||||
xelab -debug typical tb_sound -s tb_sound
|
|
||||||
xsim tb_sound -R
|
|
||||||
-142
@@ -1,142 +0,0 @@
|
|||||||
`timescale 1ns / 1ps
|
|
||||||
// Testbench for rtl/sound.v at the Z-80's 90 MHz clock: pitch, mixer, noise,
|
|
||||||
// volume levels, the attack and decay envelopes, reading back and hushing.
|
|
||||||
// scripts/sim-sound.sh
|
|
||||||
module tb_sound;
|
|
||||||
reg clk = 0, rst = 1, hush = 0, io_wr = 0;
|
|
||||||
reg [7:0] port = 0, wd = 0;
|
|
||||||
wire [7:0] q;
|
|
||||||
wire audio;
|
|
||||||
integer errors = 0;
|
|
||||||
|
|
||||||
sound #(.CPU_HZ(90_000_000)) dut (
|
|
||||||
.clk(clk), .rst(rst), .hush(hush), .io_wr(io_wr), .io_port(port), .io_wd(wd),
|
|
||||||
.io_q(q), .audio(audio)
|
|
||||||
);
|
|
||||||
always #5.556 clk = ~clk;
|
|
||||||
|
|
||||||
task out(input [7:0] p, input [7:0] v);
|
|
||||||
begin
|
|
||||||
@(posedge clk) begin port <= p; wd <= v; io_wr <= 1; end
|
|
||||||
@(posedge clk) io_wr <= 0;
|
|
||||||
end
|
|
||||||
endtask
|
|
||||||
|
|
||||||
task rd(input [7:0] p); // q then holds the port's value
|
|
||||||
begin port = p; #1; end
|
|
||||||
endtask
|
|
||||||
|
|
||||||
task check(input [8*48-1:0] what, input ok);
|
|
||||||
begin
|
|
||||||
if (ok) $display("PASS %0s", what);
|
|
||||||
else begin $display("FAIL %0s", what); errors = errors + 1; end
|
|
||||||
end
|
|
||||||
endtask
|
|
||||||
|
|
||||||
// count rising edges of voice 0's tone over a time, and the output's duty
|
|
||||||
integer edges, ones, total;
|
|
||||||
real t0, duty;
|
|
||||||
task measure(input real ms);
|
|
||||||
begin
|
|
||||||
edges = 0; ones = 0; total = 0;
|
|
||||||
t0 = $realtime;
|
|
||||||
while ($realtime - t0 < ms * 1e6) begin
|
|
||||||
@(posedge clk);
|
|
||||||
total = total + 1;
|
|
||||||
ones = ones + audio;
|
|
||||||
end
|
|
||||||
duty = 1.0 * ones / total;
|
|
||||||
end
|
|
||||||
endtask
|
|
||||||
reg t_prev = 0;
|
|
||||||
integer tone_edges = 0;
|
|
||||||
always @(posedge clk) begin
|
|
||||||
t_prev <= dut.tone[0];
|
|
||||||
if (dut.tone[0] && !t_prev) tone_edges = tone_edges + 1;
|
|
||||||
end
|
|
||||||
|
|
||||||
real d15, d7;
|
|
||||||
integer n0, v, k, rose_at, fell_at;
|
|
||||||
initial begin
|
|
||||||
repeat (10) @(posedge clk);
|
|
||||||
rst = 0;
|
|
||||||
repeat (10) @(posedge clk);
|
|
||||||
measure(1.0);
|
|
||||||
check("no output after reset", ones == 0);
|
|
||||||
|
|
||||||
// voice 0 at 440 Hz: 125000 / 284 = 440.1
|
|
||||||
out(8'h90, 284 % 256); out(8'h91, 284 / 256);
|
|
||||||
out(8'h97, 8'b000_001);
|
|
||||||
out(8'h98, 8'd15);
|
|
||||||
n0 = tone_edges;
|
|
||||||
measure(50.0);
|
|
||||||
$display(" voice 0: %0d cycles in 50 ms (%.1f Hz), duty %.3f", tone_edges - n0,
|
|
||||||
(tone_edges - n0) / 0.05, duty);
|
|
||||||
check("pitch 284 plays about 440 Hz", tone_edges - n0 >= 21 && tone_edges - n0 <= 23);
|
|
||||||
d15 = duty;
|
|
||||||
check("one voice at full volume: high 1/8 of the time", d15 > 0.11 && d15 < 0.13);
|
|
||||||
out(8'h98, 8'd7);
|
|
||||||
measure(50.0);
|
|
||||||
d7 = duty;
|
|
||||||
$display(" volume 15 duty %.4f, volume 7 duty %.4f (ratio %.1f)", d15, d7, d15 / d7);
|
|
||||||
check("volume 7 is about 24 dB quieter", d15 / d7 > 12 && d15 / d7 < 20);
|
|
||||||
rd(8'h98);
|
|
||||||
check("volume reads back", q == 8'd7);
|
|
||||||
|
|
||||||
// decay: 15 steps of 2 x 4 ms from 15 = 120 ms
|
|
||||||
out(8'h9B, 8'h02);
|
|
||||||
out(8'h98, 8'd15);
|
|
||||||
t0 = $realtime;
|
|
||||||
wait (dut.cur[0] == 0);
|
|
||||||
$display(" decay from 15 took %.1f ms", ($realtime - t0) / 1e6);
|
|
||||||
check("decay 2 fades 15 steps in 120 ms", ($realtime - t0) / 1e6 > 115 && ($realtime - t0) / 1e6 < 125);
|
|
||||||
rd(8'h98);
|
|
||||||
check("a finished sound reads back 0", q == 8'd0);
|
|
||||||
|
|
||||||
// attack then decay: up 12 steps of 1 x 4 ms, then down
|
|
||||||
out(8'h9B, 8'h13);
|
|
||||||
out(8'h98, 8'd12);
|
|
||||||
t0 = $realtime;
|
|
||||||
check("attack starts from 0", dut.cur[0] == 0);
|
|
||||||
wait (dut.cur[0] == 12);
|
|
||||||
rose_at = ($realtime - t0) / 1e6;
|
|
||||||
wait (dut.cur[0] == 0);
|
|
||||||
fell_at = ($realtime - t0) / 1e6;
|
|
||||||
$display(" attack reached 12 at %0d ms, faded out at %0d ms", rose_at, fell_at);
|
|
||||||
check("attack 1 rises 12 steps in 48 ms", rose_at >= 46 && rose_at <= 50);
|
|
||||||
check("decay 3 then falls 12 steps in 144 ms", fell_at - rose_at >= 140 && fell_at - rose_at <= 150);
|
|
||||||
|
|
||||||
// noise on voice 1, no tone
|
|
||||||
out(8'h96, 8'd4);
|
|
||||||
out(8'h97, 8'b010_000);
|
|
||||||
out(8'h9C, 8'h00);
|
|
||||||
out(8'h99, 8'd15);
|
|
||||||
n0 = 0;
|
|
||||||
for (k = 0; k < 2000; k = k + 1) begin
|
|
||||||
repeat (360) @(posedge clk);
|
|
||||||
n0 = n0 + dut.lfsr[0];
|
|
||||||
end
|
|
||||||
$display(" noise was high %0d of 2000 samples", n0);
|
|
||||||
check("noise is about half high, half low", n0 > 800 && n0 < 1200);
|
|
||||||
|
|
||||||
// all three voices and CLS
|
|
||||||
out(8'h92, 8'd142); out(8'h94, 8'd71);
|
|
||||||
out(8'h97, 8'b000_111);
|
|
||||||
out(8'h98, 8'd15); out(8'h99, 8'd15); out(8'h9A, 8'd15);
|
|
||||||
measure(20.0);
|
|
||||||
check("three voices make sound", duty > 0.2);
|
|
||||||
@(posedge clk) hush <= 1;
|
|
||||||
@(posedge clk) hush <= 0;
|
|
||||||
repeat (4) @(posedge clk); // what was already in the mixer
|
|
||||||
measure(2.0);
|
|
||||||
$display(" after CLS: output high %0d times in 2 ms", ones);
|
|
||||||
rd(8'h99);
|
|
||||||
check("CLS silences everything", ones == 0 && q == 0);
|
|
||||||
rd(8'h97);
|
|
||||||
check("other ports read FFh", q == 8'hFF);
|
|
||||||
|
|
||||||
if (errors == 0) $display("ALL SOUND TESTS PASSED");
|
|
||||||
else $display("%0d SOUND TESTS FAILED", errors);
|
|
||||||
$finish;
|
|
||||||
end
|
|
||||||
endmodule
|
|
||||||
+125
-13
@@ -52,6 +52,16 @@ module tb_terminal;
|
|||||||
end
|
end
|
||||||
endtask
|
endtask
|
||||||
|
|
||||||
|
// Ctrl-Alt-Del pressed and let go (Delete as E0 71), then 10 ms
|
||||||
|
task cad_press;
|
||||||
|
begin
|
||||||
|
ps2_send(8'h14); ps2_send(8'h11); ps2_send(8'hE0); ps2_send(8'h71);
|
||||||
|
ps2_send(8'hE0); ps2_send(8'hF0); ps2_send(8'h71); ps2_send(8'hF0); ps2_send(8'h11);
|
||||||
|
ps2_send(8'hF0); ps2_send(8'h14);
|
||||||
|
#10_000_000;
|
||||||
|
end
|
||||||
|
endtask
|
||||||
|
|
||||||
task ps2_send(input [7:0] d);
|
task ps2_send(input [7:0] d);
|
||||||
integer i;
|
integer i;
|
||||||
reg [10:0] f;
|
reg [10:0] f;
|
||||||
@@ -113,6 +123,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
|
||||||
@@ -193,6 +211,34 @@ module tb_terminal;
|
|||||||
end
|
end
|
||||||
endtask
|
endtask
|
||||||
|
|
||||||
|
// the restarted BASIC's banner, on whichever row it lands, on the main
|
||||||
|
// screen (BASIC leaves the monitor's alternate screen as it starts)
|
||||||
|
task wait_banner(input [8*48-1:0] what);
|
||||||
|
realtime t0;
|
||||||
|
integer br, seen;
|
||||||
|
reg [7:0] b0, b1, b2;
|
||||||
|
begin
|
||||||
|
t0 = $realtime;
|
||||||
|
seen = 0;
|
||||||
|
while (!seen && $realtime - t0 < 500_000_000) begin
|
||||||
|
#100_000;
|
||||||
|
// one cellraw() at a time: several in one expression read wrong
|
||||||
|
for (br = 0; br < 32; br = br + 1) begin
|
||||||
|
b0 = cellraw(br, 0); b1 = cellraw(br, 1); b2 = cellraw(br, 2);
|
||||||
|
if ({b0, b1, b2} == "DAR") seen = 1;
|
||||||
|
end
|
||||||
|
end
|
||||||
|
if (seen && !dut.alt_scr) $display("PASS %0s", what);
|
||||||
|
else begin
|
||||||
|
$display("FAIL %0s: banner %0s, alternate screen %b", what,
|
||||||
|
seen ? "seen" : "not seen", dut.alt_scr);
|
||||||
|
errors = errors + 1;
|
||||||
|
dump_screen;
|
||||||
|
end
|
||||||
|
#5_000_000;
|
||||||
|
end
|
||||||
|
endtask
|
||||||
|
|
||||||
reg [31:0] pc_a, pc_b, jp_to;
|
reg [31:0] pc_a, pc_b, jp_to;
|
||||||
reg [15:0] jp_txt;
|
reg [15:0] jp_txt;
|
||||||
integer i;
|
integer i;
|
||||||
@@ -381,6 +427,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;
|
||||||
@@ -429,7 +525,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");
|
||||||
@@ -565,9 +661,9 @@ module tb_terminal;
|
|||||||
// 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");
|
||||||
wait_at(21, 0, " FLOAT REGISTERS");
|
wait_at(21, 0, " FLOAT REGISTERS");
|
||||||
wait_at(22, 0, " F0 ");
|
wait_at(22, 0, "FT0 ");
|
||||||
uart_str("R F1=3FC00000\015");
|
uart_str("R F1=3FC00000\015");
|
||||||
wait_at(22, 13, " F1 3FC00000");
|
wait_at(22, 13, "FT1 3FC00000");
|
||||||
uart_str("M\015");
|
uart_str("M\015");
|
||||||
wait_at(21, 0, " MEMORY");
|
wait_at(21, 0, " MEMORY");
|
||||||
uart_str("\015"); // Enter: one step
|
uart_str("\015"); // Enter: one step
|
||||||
@@ -658,16 +754,32 @@ module tb_terminal;
|
|||||||
uart_str("CLS:CALL 73728\015");
|
uart_str("CLS:CALL 73728\015");
|
||||||
wait_row(0, "ASM OK");
|
wait_row(0, "ASM OK");
|
||||||
|
|
||||||
// ---- Ctrl-Alt-Del restarts the computer
|
// ---- Ctrl-Alt-Del: into the monitor, even with interrupts off in a
|
||||||
ps2_send(8'h14); ps2_send(8'h11); ps2_send(8'hE0); ps2_send(8'h71);
|
// tight loop; again (within 2 s, or in the monitor) restarts the computer
|
||||||
ps2_send(8'hE0); ps2_send(8'hF0); ps2_send(8'h71); ps2_send(8'hF0); ps2_send(8'h11);
|
// csrci mstatus,8 (interrupts off) at 12000, then j . at 12004
|
||||||
ps2_send(8'hF0); ps2_send(8'h14);
|
uart_str("CLS:POKE 73728,115:POKE 73729,112:POKE 73730,4:POKE 73731,48\015");
|
||||||
// the restarted BASIC's banner, on whichever row it lands
|
uart_str("POKE 73732,111:POKE 73733,0:POKE 73734,0:POKE 73735,0\015");
|
||||||
t_cmd = $realtime;
|
#5_000_000;
|
||||||
while ({cellraw(2, 0), cellraw(2, 1)} != "DA" && {cellraw(3, 0), cellraw(3, 1)} != "DA" &&
|
uart_str("CALL 73728\015"); // hangs at 12004, interrupts off
|
||||||
{cellraw(4, 0), cellraw(4, 1)} != "DA" && $realtime - t_cmd < 50_000_000) #100_000;
|
#5_000_000;
|
||||||
if ($realtime - t_cmd < 50_000_000) $display("PASS Ctrl-Alt-Del restarted BASIC");
|
cad_press;
|
||||||
else begin $display("FAIL Ctrl-Alt-Del: no banner"); errors = errors + 1; end
|
wait_at(0, 50, "STOPPED BY CTRL-ALT-DEL");
|
||||||
|
if (screen_pc(0) == 32'h12004) $display("PASS Ctrl-Alt-Del stopped the loop at 12004");
|
||||||
|
else begin $display("FAIL Ctrl-Alt-Del: PC %h", screen_pc(0)); errors = errors + 1; end
|
||||||
|
uart_str("X\015"); // back into the loop
|
||||||
|
#10_000_000;
|
||||||
|
cad_press; // within 2 s: restart
|
||||||
|
wait_banner("Ctrl-Alt-Del twice restarted BASIC");
|
||||||
|
// a trap goes to the monitor; Ctrl-Alt-Del there restarts
|
||||||
|
uart_str("CLS:POKE 73728,0:POKE 73729,0:POKE 73730,0:POKE 73731,0:CALL 73728\015");
|
||||||
|
wait_at(0, 50, "STOPPED BY ILLEGAL INSTRUCTI");
|
||||||
|
cad_press;
|
||||||
|
wait_banner("Ctrl-Alt-Del in the monitor restarted BASIC");
|
||||||
|
// the monitor's RESET
|
||||||
|
uart_str("CLS:MONITOR\015");
|
||||||
|
wait_at(29, 0, "> ");
|
||||||
|
uart_str("RESET\015");
|
||||||
|
wait_banner("the monitor's RESET restarted BASIC");
|
||||||
dump_screen;
|
dump_screen;
|
||||||
`endif
|
`endif
|
||||||
if (errors == 0) $display("ALL TESTS PASSED");
|
if (errors == 0) $display("ALL TESTS PASSED");
|
||||||
|
|||||||
Executable
+1510
File diff suppressed because it is too large.
Load diff
+4
-3
@@ -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
|
||||||
|
|||||||
Reference in new issue
Block a user