Files
brad ArantandClaude Opus 5.5 bda9bb67b6 Add a 640x480 two-colour graphics mode; start in white
The graphics memory doubles as 640x480 at a bit a pixel (port 38), four
pixels to an entry, plotted by read-modify-write, in two colours from
port 39 (0 transparent). BASIC gets SCREEN 0 / SCREEN 1 [,set[,clear]];
a plain fill (as every game does) returns to 320x240 and BASIC follows.
The text now starts in white (SW5:4 = 00; 10 is green). The README is
rewritten to stand on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:06:30 -08:00

2408 lines
67 KiB
C

/*
* Dartmouth-style BASIC for the Basys 3 RISC-V computer.
*
* Numbered program lines, LET PRINT INPUT IF..THEN GOTO GOSUB RETURN
* FOR..TO..STEP NEXT DIM DEF FN READ DATA RESTORE ON..GOTO/GOSUB END STOP REM
* RANDOMIZE, the classic functions SIN COS TAN ATN EXP LOG ABS SQR INT RND SGN
* TAB, plus string variables A$..Z$ with LEN VAL ASC CHR$ STR$ LEFT$ RIGHT$
* MID$, PEEK/POKE, INP/OUT and TIM. Commands: RUN LIST NEW (SCRATCH) and any
* statement typed without a line number runs at once. Ctrl-C stops a program.
*
* Graphics: 320x240 in 16 colours over the text, origin top left, colour 0
* transparent, or (SCREEN 1) 640x480 in two. CLS COLOR PLOT LINE RECT FILL
* CIRCLE and POINT(x,y); LOCATE and INK place and colour text.
*
* Files: SAVE "NAME", LOAD "NAME", RUN "NAME", DIR, DEL "NAME" keep programs
* in the spare part of the configuration flash (see the file system below).
*
* Builds with GCC for RV32IM (console on I/O ports 0/1, memory-mapped) or with
* a host C compiler for testing (stdin/stdout).
*/
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <setjmp.h>
typedef uint8_t u8;
typedef uint16_t u16;
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef uint32_t u32;
/* ------------------------------------------------------------- platform */
#ifdef __riscv
#include "basys3.h"
#define con_stat IO8(0x00) /* bit 0: key waiting, bit 1: can send, bit 2: 132 columns */
#define con_data IO8(0x01)
static void out_c(u8 c) { while (!(con_stat & 2)); con_data = c; }
static int poll_c(void) { return con_stat & 1 ? con_data : -1; }
static u8 wait_c(void) { while (!(con_stat & 1)); return con_data; }
static i32 millis(void) { return (i32)IO_MS; }
/* PEEK and POKE take any address: RAM is 0-65535, port N is -256 + N */
static u8 peek(u32 a) { return *(volatile u8 *)a; }
static void poke(u32 a, u8 v) { *(volatile u8 *)a = v; }
static u8 io_in(u8 p) { return IO8(p); }
static void io_out(u8 p, u8 v) { IO8(p) = v; }
static void bye(void) { }
static u8 scr_width(void) { return con_stat & 4 ? 132 : 80; }
#define gx_lo IO8(0x30)
#define gx_hi IO8(0x31)
#define gy_p IO8(0x32)
#define gpix IO8(0x33) /* write plots and moves right; read gives the colour */
#define gfill IO8(0x34)
#define gmode IO8(0x38) /* bit 0: 640x480 in two colours (a game's fill ends it) */
#define gcols IO8(0x39) /* its colours: set pixels 3:0, clear ones 7:4 */
static void g_at(u16 x, u16 y) { gx_lo = x; gx_hi = x >> 8 | (y >> 8) << 2; gy_p = y; }
static void g_put(u8 c) { gpix = c; }
static u8 g_get(void) { return gpix; }
/* clear to colour 0, sprites off, scroll to 0; the fill also ends 640x480 mode */
static void g_clear(u8 hi) { gfill = 0; while (gfill & 1); gmode = hi; }
static void g_colours(u8 set, u8 clr) { gcols = set | clr << 4; }
static u8 g_hires(void) { return gmode & 1; }
/* SPI flash: port 40h opens/ends a command (bit 1 reads back "refused"),
41h shifts a byte. The hardware refuses to write below the file area. */
#define fl_ctl IO8(0x40)
#define fl_dat IO8(0x41)
static u8 spi(u8 b) { fl_dat = b; while (fl_ctl & 1); return fl_dat; }
static void fl_open(u8 cmd) { fl_ctl = 1; spi(cmd); }
static void fl_close(void) { fl_ctl = 0; }
static void fl_addr(u32 a) { spi(a >> 16); spi(a >> 8); spi(a); }
static u8 fl_busy(void)
{
u8 st;
fl_open(0x05); st = spi(0); fl_close();
return st & 1;
}
static u8 fl_present(void) /* Macronix MX25L3273F, 4 KB sectors */
{
u8 a, b, c;
fl_open(0x9F); a = spi(0); b = spi(0); c = spi(0); fl_close();
return a == 0xC2 && b == 0x20 && c == 0x16;
}
static void fl_read(u32 a, u8 *p, u16 n)
{
fl_open(0x03); fl_addr(a);
while (n--) *p++ = spi(0);
fl_close();
}
/* page program (02) or sector erase (20); returns 0 if the hardware refused */
static u8 fl_write_op(u8 cmd, u32 a, const u8 *p, u16 n)
{
u8 ok;
fl_open(0x06); fl_close();
fl_open(cmd); fl_addr(a);
while (n--) spi(*p++);
ok = !(fl_ctl & 2);
fl_close();
return ok;
}
#else
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static void out_c(u8 c) { if (c != '\r') putchar(c); }
static int poll_c(void) { return -1; }
static u8 wait_c(void)
{
int c;
fflush(stdout);
c = getchar();
if (c == EOF) exit(0);
return c == '\n' ? '\r' : c;
}
static i32 millis(void) { return (i32)(clock() / (CLOCKS_PER_SEC / 1000)); }
static u8 fake_mem[65536];
static u8 peek(u32 a) { return fake_mem[a & 0xFFFF]; }
static void poke(u32 a, u8 v) { fake_mem[a & 0xFFFF] = v; }
static u8 io_in(u8 p) { (void)p; return 0xFF; }
static void io_out(u8 p, u8 v) { (void)p; (void)v; }
static void close_all(void);
static void bye(void) { close_all(); exit(0); }
static u8 scr_width(void) { return 80; }
static u8 gmem[480][640];
static u16 hgx, hgy, hgw = 320, hgh = 240;
static void g_at(u16 x, u16 y) { hgx = x; hgy = y; }
static void g_put(u8 c) { if (hgx < hgw && hgy < hgh) gmem[hgy][hgx] = hgw > 320 ? c != 0 : c; hgx++; }
static u8 g_get(void) { return hgx < hgw && hgy < hgh ? gmem[hgy][hgx] : 0; }
static void g_clear(u8 hi) { memset(gmem, 0, sizeof gmem); hgw = hi ? 640 : 320; hgh = hi ? 480 : 240; }
static void g_colours(u8 set, u8 clr) { (void)set; (void)clr; }
static u8 g_hires(void) { return hgw > 320; }
/* flash file area kept in basic-flash.img */
#define HOST_BASE 0x240000UL
static u8 hflash[0x1C0000];
static u8 hflash_loaded;
static void hflash_load(void)
{
FILE *f;
if (hflash_loaded) return;
hflash_loaded = 1;
memset(hflash, 0xFF, sizeof hflash);
if ((f = fopen("basic-flash.img", "rb"))) { fread(hflash, 1, sizeof hflash, f); fclose(f); }
}
static void hflash_store(void)
{
FILE *f = fopen("basic-flash.img", "wb");
if (f) { fwrite(hflash, 1, sizeof hflash, f); fclose(f); }
}
static u8 fl_busy(void) { return 0; }
static u8 fl_present(void) { hflash_load(); return 1; }
static void fl_read(u32 a, u8 *p, u16 n) { hflash_load(); memcpy(p, hflash + a - HOST_BASE, n); }
static u8 fl_write_op(u8 cmd, u32 a, const u8 *p, u16 n)
{
u8 *d;
hflash_load();
if (a < HOST_BASE || a >= HOST_BASE + sizeof hflash) return 0;
d = hflash + a - HOST_BASE;
if (cmd == 0x20) memset(hflash + ((a - HOST_BASE) & ~4095UL), 0xFF, 4096);
else while (n--) *d++ &= *p++;
hflash_store();
return 1;
}
#endif
/* ---------------------------------------------------------- file channels */
#define FBLK 8 /* blocks per file: 32 KB */
#define NCHAN 4 /* 0 is SAVE and LOAD's, 1-3 are for OPEN */
struct chan {
u8 mode; /* 0 closed, 'I' reading, 'O' writing */
char name[8];
u16 len, pos, pg; /* reading: length, position, page held in buf */
u16 blk[FBLK];
u8 col; /* PRINT # column */
u8 buf[256];
};
static struct chan ch[NCHAN];
static struct chan *chan_arg(u8 mode);
static u8 chan_line(struct chan *c);
static u8 ghi; /* 640x480 (SCREEN 1) */
static u16 gw = 320, gh = 240; /* the graphics' size */
/* follow the hardware's mode: a game run with CALL may have ended SCREEN 1 */
static void g_sync(void) { ghi = g_hires(); gw = ghi ? 640 : 320; gh = ghi ? 480 : 240; }
/* ----------------------------------------------------------------- tokens */
enum {
T_LET = 0x80, T_PRINT, T_INPUT, T_IF, T_THEN, T_GOTO, T_GOSUB, T_RETURN, T_FOR,
T_TO, T_STEP, T_NEXT, T_DIM, T_DEF, T_END, T_STOP, T_REM, T_READ, T_DATA,
T_RESTORE, T_ON, T_RANDOMIZE, T_POKE, T_OUT, T_RUN, T_LIST, T_NEW, T_SCRATCH,
T_BYE, T_CLS, T_COLOR, T_PLOT, T_LINE, T_RECT, T_FILL, T_CIRCLE, T_LOCATE, T_INK, T_SCREEN,
T_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, T_MONITOR, T_CALL, T_BSAVE, T_BLOAD, T_OUTPUT, T_APPEND, T_AND, T_OR, T_NOT, T_SIN, T_COS, T_TAN, T_ATN, T_EXP, T_LOG, T_ABS,
T_SQR, T_INT, T_RND, T_SGN, T_FN, T_TAB, T_PEEK, T_INP, T_LEN, T_VAL, T_ASC, T_EOF,
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM, T_LAST
};
static const char *const kw[] = {
"LET", "PRINT", "INPUT", "IF", "THEN", "GOTO", "GOSUB", "RETURN", "FOR",
"TO", "STEP", "NEXT", "DIM", "DEF", "END", "STOP", "REM", "READ", "DATA",
"RESTORE", "ON", "RANDOMIZE", "POKE", "OUT", "RUN", "LIST", "NEW", "SCRATCH",
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK", "SCREEN",
"SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "MONITOR", "CALL", "BSAVE", "BLOAD", "OUTPUT", "APPEND", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS",
"SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "EOF",
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM"
};
/* ----------------------------------------------------------------- memory */
#define ARENA 20664 /* program text grows up, arrays grow down */
#define STRMAX 80
#define NVARS (26 * 11)
#define FORMAX 16
#define GOSUBMAX 32
#ifdef __riscv
/* at 8000h (basic.ld), where machine-code programs know to load into it */
static u8 arena[ARENA] __attribute__((section(".arena")));
#else
static u8 arena[ARENA];
#endif
static char ed_last[256]; /* the last line typed, for Up */
static u8 *prog_end; /* end-of-program marker (a zero length byte) */
static u8 *arr_low; /* lowest byte used by arrays */
static float vars[NVARS];
static char svars[26][STRMAX];
struct array { u8 *p; u16 d1, d2; };
static struct array arrays[52]; /* A()-Z(), then A$()-Z$() */
struct fn { u8 *body; u8 var; };
static struct fn fns[26];
struct forent { u8 var; float limit, step; u8 *tp, *ln; };
static struct forent fors[FORMAX];
static u8 nfor;
struct subent { u8 *tp, *ln; };
static struct subent subs[GOSUBMAX];
static u8 nsub;
static u8 *tp; /* text pointer */
static u8 *curln; /* line being run, 0 in direct mode */
static u8 *datap; /* next DATA item, 0 = search from the start */
static u8 *dataln;
static jmp_buf errjmp;
static u8 col; /* print column */
static u32 seed = 12345;
static char linebuf[256];
static u8 tokbuf[256];
static u8 running;
static u8 jumped; /* tp was moved to another statement */
/* ----------------------------------------------------------------- output */
static u8 out_ch; /* PRINT # channel, 0 = the screen */
static u8 scr_col; /* the screen's column while out_ch is set */
static void file_putc(u8 c);
static void putch(char c)
{
if (c == '\n') {
col = 0;
if (out_ch) file_putc('\n');
else { out_c('\r'); out_c('\n'); }
return;
}
if (c == '\b') { if (col) col--; }
else if ((u8)c >= ' ') col++;
if (out_ch) file_putc(c);
else out_c(c);
}
static void puts_(const char *s) { while (*s) putch(*s++); }
static void newline(void) { putch('\n'); }
static void put_u16(u16 v)
{
char b[6], *p = b + 5;
*p = 0;
do { *--p = '0' + v % 10; v /= 10; } while (v);
puts_(p);
}
/* ----------------------------------------------------------------- errors */
enum {
E_SYNTAX, E_LINE, E_RETURN, E_NEXT, E_DATA, E_SUBSCRIPT, E_DIV0, E_MEMORY,
E_TYPE, E_STRING, E_FUNC, E_UNDEF_FN, E_FOR, E_GOSUB, E_NOFILE, E_DISKFULL,
E_DIRFULL, E_NAME, E_FLASH, E_TOOBIG, E_OPEN, E_NOTOPEN, E_EOF, E_BREAK, E_STOP
};
static const char *const errmsg[] = {
"SYNTAX ERROR", "UNDEFINED LINE NUMBER", "RETURN WITHOUT GOSUB",
"NEXT WITHOUT FOR", "OUT OF DATA", "SUBSCRIPT OUT OF RANGE", "DIVISION BY ZERO",
"OUT OF MEMORY", "TYPE MISMATCH", "STRING TOO LONG", "ILLEGAL FUNCTION CALL",
"UNDEFINED FUNCTION", "FOR NESTED TOO DEEPLY", "GOSUB NESTED TOO DEEPLY",
"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",
"BREAK", "STOP"
};
static u16 line_no(u8 *ln) { return ln[1] | (u16)ln[2] << 8; }
static void error(u8 e)
{
if (out_ch) { out_ch = 0; col = scr_col; }
if (col) newline();
if (e < E_BREAK) putch('?');
puts_(errmsg[e]);
if (curln) { puts_(" IN "); put_u16(line_no(curln)); }
newline();
longjmp(errjmp, 1);
}
/* ------------------------------------------------------------------ clock */
/* The date and time, set by DATE (the PC tools set it when they connect) and
kept from the millisecond counter until the power goes off. Held as seconds
since 2000-01-01 00:00; 0 means not set. */
#ifdef __riscv
/* at a fixed address (above the stack) so the monitor can read the clock too */
#define clk_sec CLK_SEC
#define clk_ms CLK_MS
#else
static u32 clk_sec;
static i32 clk_ms;
#endif
static u32 now(void)
{
i32 m;
u32 d;
if (!clk_sec) return 0;
m = millis();
d = (u32)(m - clk_ms) / 1000;
clk_sec += d;
clk_ms += (i32)(d * 1000);
return clk_sec;
}
static const u8 mdays[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static u8 leap(u16 y) { return !(y & 3) && (y % 100 || !(y % 400)); }
static u8 month_len(u16 y, u8 m) { return mdays[m - 1] + (m == 2 && leap(y)); }
/* "YYYY-MM-DD HH:MM" (or with ":SS" when sec is set) for t; "" when t is 0. */
static void fmt_date(u32 t, char *out, u8 sec)
{
static const char sep[] = "-- ::";
u16 y = 2000, days, mins;
u8 m = 1, i, v[6];
if (!t) { *out = 0; return; }
days = t / 86400UL;
mins = (u16)(t % 86400UL / 60);
while (days >= 365 + leap(y)) days -= 365 + leap(y++);
while (days >= month_len(y, m)) days -= month_len(y, m++);
v[0] = y - 2000; v[1] = m; v[2] = days + 1;
v[3] = mins / 60; v[4] = mins % 60; v[5] = t % 60;
*out++ = '2'; *out++ = '0';
for (i = 0; i < 5 + sec; i++) {
if (i) *out++ = sep[i - 1];
*out++ = '0' + v[i] / 10;
*out++ = '0' + v[i] % 10;
}
*out = 0;
}
static u16 date_field(const char **p, u8 n, u16 lo, u16 hi)
{
u16 v = 0;
while (n--) {
if (**p < '0' || **p > '9') error(E_FUNC);
v = v * 10 + (*(*p)++ - '0');
}
if (v < lo || v > hi) error(E_FUNC);
return v;
}
/* Set the clock from "YYYY-MM-DD[ HH:MM[:SS]]". */
static void set_date(const char *s)
{
static const char sep[] = "-- ::";
static const u8 hi[] = { 99, 12, 31, 23, 59, 59 };
u8 v[6], i;
u32 days;
memset(v, 0, sizeof v);
if (*s++ != '2' || *s++ != '0') error(E_FUNC);
for (i = 0; i < 6; i++) {
if (i) {
if (!*s && (i == 3 || i == 5)) break;
if (*s++ != sep[i - 1]) error(E_FUNC);
}
v[i] = date_field(&s, 2, i == 1 || i == 2,
i == 2 ? month_len(2000 + v[0], v[1]) : hi[i]);
}
if (*s) error(E_FUNC);
days = v[2] - 1;
for (i = 0; i < v[0]; i++) days += 365 + leap(2000 + i);
for (i = 1; i < v[1]; i++) days += month_len(2000 + v[0], i);
clk_ms = millis();
clk_sec = days * 86400UL + (u16)(v[3] * 60 + v[4]) * 60UL + v[5];
if (!clk_sec) clk_sec = 1;
}
/* ---------------------------------------------------------------- numbers */
static const float p10[] = { 1e1f, 1e2f, 1e4f, 1e8f, 1e16f, 1e32f };
static const float m10[] = { 1e-1f, 1e-2f, 1e-4f, 1e-8f, 1e-16f, 1e-32f };
static float scale10(float v, i16 e)
{
u8 i;
u8 neg = e < 0;
if (neg) e = -e;
if (e > 63) e = 63;
for (i = 0; i < 6; i++, e >>= 1)
if (e & 1) v = neg ? v / p10[i] : v * p10[i];
return v;
}
/* Parse a number at *pp (digits, point, exponent); moves *pp past it. */
static float parse_num(u8 **pp)
{
u8 *p = *pp;
i32 m = 0;
i16 e = 0, ex = 0;
u8 nd = 0, any = 0, eneg = 0, dot = 0;
for (;; p++) { /* up to 9 significant digits, and a point */
if (*p == '.' && !dot) { dot = 1; continue; }
if (*p < '0' || *p > '9') break;
any = 1;
if (nd < 9) { m = m * 10 + (*p - '0'); if (m) nd++; e -= dot; }
else if (!dot) e++;
}
if (any && *p == 'E') {
u8 *q = p + 1;
if (*q == '+' || *q == '-') { eneg = *q == '-'; q++; }
if (*q >= '0' && *q <= '9') {
for (p = q; *p >= '0' && *p <= '9'; p++)
if (ex < 100) ex = ex * 10 + (*p - '0');
e += eneg ? -ex : ex;
}
}
if (!any) error(E_SYNTAX);
*pp = p;
return scale10((float)m, e);
}
/* v in decimal into b; returns the end of it (the zero byte). */
static char *fmt_ul(u32 v, char *b)
{
char t[10], *q = t;
do { *q++ = '0' + v % 10; v /= 10; } while (v);
while (q > t) *b++ = *--q;
*b = 0;
return b;
}
/* Format like Dartmouth BASIC: up to 6 significant digits, E notation outside
0.001 .. 999999, no leading zero before the point. */
static void fmt_num(float v, char *out)
{
char d[8];
i32 n;
i8 e = 0, i, last, pt;
u8 k;
if (v < 0) { *out++ = '-'; v = -v; }
if (v < 999999.5f) { /* whole numbers: no floating point needed */
n = (i32)v;
if ((float)n == v) { fmt_ul(n, out); return; }
}
if (v >= 10)
for (k = 6; k-- > 0;)
if (v >= p10[k]) { v *= m10[k]; e += 1 << k; }
if (v < 1)
for (k = 6; k-- > 0;)
if (v * p10[k] < 10) { v *= p10[k]; e -= 1 << k; }
n = (i32)(v * 100000.0f + 0.5f);
if (n >= 1000000L) { n /= 10; e++; }
if (n < 100000L) n = 100000L;
fmt_ul(n, d); /* six digits */
for (last = 5; last > 0 && d[last] == '0'; last--);
/* pt digits before the point; outside 1E-4..999999 use E notation */
pt = e + 1;
if (e < -3 || e > 5) pt = 1;
if (pt <= 0) {
*out++ = '.';
for (k = -pt; k; k--) *out++ = '0'; /* not i = pt..-1: SDCC 4.5 makes that a djnz
that runs 256 times when pt is 0 */
}
for (i = 0; i <= last || i < pt; i++) {
if (i == pt && i) *out++ = '.';
*out++ = d[i];
}
if (e < -3 || e > 5) {
*out++ = 'E';
*out++ = e < 0 ? '-' : '+';
if (e < 0) e = -e;
*out++ = '0' + e / 10;
*out++ = '0' + e % 10;
}
*out = 0;
}
/* ------------------------------------------------------------ tokenizing */
static u8 is_alpha(u8 c) { return c >= 'A' && c <= 'Z'; }
static u8 is_digit(u8 c) { return c >= '0' && c <= '9'; }
/* Turn a typed line into tokens: keywords become single bytes, letters are
upper-cased outside quotes, REM and DATA text is kept as typed. */
static void tokenize(const char *s, u8 *out)
{
u8 i, best, blen, len, quote = 0, raw = 0;
const char *k;
while (*s) {
u8 c = *s;
if (raw) { *out++ = c; s++; continue; }
if (c == '"') quote = !quote;
if (quote) { *out++ = c; s++; continue; }
if (c >= 'a' && c <= 'z') c -= 32;
best = 0; blen = 0;
for (i = 0; i < T_LAST - T_LET; i++) {
k = kw[i];
if ((u8)k[0] != c) continue;
for (len = 1; k[len]; len++) {
u8 t = s[len];
if (t >= 'a' && t <= 'z') t -= 32;
if (t != (u8)k[len]) break;
}
if (!k[len] && len > blen) { blen = len; best = T_LET + i; }
}
if (blen) {
*out++ = best;
s += blen;
if (best == T_REM || best == T_DATA) raw = 1;
} else {
*out++ = c;
s++;
}
}
*out = 0;
}
/* Write a program line as text, keywords spelled out, without a line end. */
static void list_to(u8 *ln, void (*out)(char))
{
char b[6], *q = b;
const char *k;
u8 *p = ln + 3;
fmt_ul(line_no(ln), b);
while (*q) out(*q++);
out(' ');
for (; *p; p++) {
if (*p >= T_LET && *p < T_LAST)
for (k = kw[*p - T_LET]; *k; k++) out(*k);
else out(*p);
}
}
static void list_line(u8 *ln)
{
list_to(ln, putch);
newline();
}
/* -------------------------------------------------------- program storage */
static u8 *find_line(u16 n)
{
u8 *p = arena;
while (*p && line_no(p) < n) p += *p;
return p;
}
static void clear_vars(void)
{
memset(vars, 0, sizeof vars);
memset(svars, 0, sizeof svars);
memset(arrays, 0, sizeof arrays);
memset(fns, 0, sizeof fns);
arr_low = arena + ARENA;
nfor = nsub = 0;
datap = 0;
}
static void new_prog(void)
{
arena[0] = 0;
prog_end = arena;
clear_vars();
}
static void store_line(u16 n, u8 *toks)
{
u8 *p = find_line(n);
u16 len = strlen((char *)toks);
u16 sz;
while (len && toks[len - 1] == ' ') toks[--len] = 0;
clear_vars(); /* arrays may move */
if (*p && line_no(p) == n) { /* delete the old copy */
sz = *p;
memmove(p, p + sz, prog_end + 1 - (p + sz));
prog_end -= sz;
}
if (!len) return;
sz = len + 4;
if (sz > 255) error(E_STRING);
if (prog_end + 1 + sz >= arr_low) error(E_MEMORY);
memmove(p + sz, p, prog_end + 1 - p);
p[0] = sz;
p[1] = n & 0xFF;
p[2] = n >> 8;
memcpy(p + 3, toks, len + 1);
prog_end += sz;
}
/* -------------------------------------------------------------- scanning */
static u8 peekc(void)
{
while (*tp == ' ') tp++;
return *tp;
}
static u8 accept(u8 c)
{
if (peekc() == c) { tp++; return 1; }
return 0;
}
static void expect(u8 c)
{
if (!accept(c)) error(E_SYNTAX);
}
static u8 at_end(void)
{
u8 c = peekc();
return c == 0 || c == ':';
}
static u16 get_lineno(void)
{
u16 n = 0;
if (!is_digit(peekc())) error(E_SYNTAX);
while (is_digit(*tp)) n = n * 10 + (*tp++ - '0');
return n;
}
/* Numeric variable name: letter with an optional digit. Returns its index, or
255 if the text is not a numeric variable (does not move tp then). */
static u8 var_name(void)
{
u8 c = peekc(), d;
if (!is_alpha(c)) return 255;
d = tp[1];
if (d == '$') return 255;
if (is_digit(d)) {
if (tp[2] == '$') return 255;
tp += 2;
return (c - 'A') * 11 + 1 + d - '0';
}
tp++;
return (c - 'A') * 11;
}
static u8 is_str_start(void)
{
u8 c = peekc();
if (c == '"' || c == T_CHRS || c == T_STRS || c == T_LEFTS || c == T_RIGHTS || c == T_MIDS ||
c == T_DATES)
return 1;
return is_alpha(c) && tp[1] == '$';
}
/* ------------------------------------------------------------- expressions */
static float expr(void);
static void sexpr(char *out);
static i16 to_int(float v)
{
if (v > 32767.0f || v < -32768.0f) error(E_FUNC);
return (i16)v;
}
/* Give array a (26 and up for strings) room for subscripts 0..d1, 0..d2. */
static void arr_alloc(u8 a, u16 d1, u16 d2)
{
struct array *ar = &arrays[a];
u16 n = (d1 + 1) * (d2 + 1), sz;
u8 *np;
if ((i16)d1 < 0 || (i16)d2 < 0 || n > (a < 26 ? 6000 : 255)) error(E_SUBSCRIPT);
sz = n * (a < 26 ? sizeof(float) : STRMAX);
np = arr_low - sz;
if (np <= prog_end + 1) error(E_MEMORY);
arr_low = np;
memset(np, 0, sz);
ar->p = np;
ar->d1 = d1;
ar->d2 = d2;
}
static u8 *array_elem(u8 a)
{
struct array *ar = &arrays[a];
i16 i, j = 0;
u8 two;
expect('(');
i = to_int(expr());
two = accept(',');
if (two) j = to_int(expr());
expect(')');
if (!ar->p) arr_alloc(a, 10, two ? 10 : 0); /* undeclared: 0..10 */
if (i < 0 || i > (i16)ar->d1 || j < 0 || j > (i16)ar->d2) error(E_SUBSCRIPT);
return ar->p + ((u16)i * (ar->d2 + 1) + j) * (a < 26 ? sizeof(float) : STRMAX);
}
/* A string variable or string array element (tp on its letter). */
static char *str_ref(void)
{
u8 a = peekc() - 'A';
tp += 2;
if (peekc() == '(') return (char *)array_elem(26 + a);
return svars[a];
}
/* A numeric variable or array element as an lvalue. */
static float *num_ref(void)
{
u8 v;
if (is_alpha(peekc()) && tp[1] == '(') {
v = *tp - 'A';
tp++;
return (float *)array_elem(v);
}
v = var_name();
if (v == 255) error(E_SYNTAX);
return &vars[v];
}
static float ipow(float x, float y)
{
i16 n;
float r = 1;
u8 neg;
if (y == (float)(i16)y && y >= -64 && y <= 64) {
n = (i16)y;
neg = n < 0;
if (neg) n = -n;
for (; n; n >>= 1, x *= x)
if (n & 1) r *= x;
return neg ? 1 / r : r;
}
if (x < 0) error(E_FUNC);
if (x == 0) return 0;
return expf(y * logf(x));
}
static float rnd(void)
{
seed = seed * 1103515245UL + 12345UL;
return (float)((seed >> 8) & 0xFFFFFF) / 16777216.0f;
}
static float func(u8 t)
{
char s[STRMAX];
float v;
if (t == T_RND) { /* RND or RND(x): argument ignored */
if (accept('(')) { expr(); expect(')'); }
return rnd();
}
if (t == T_TIM) return (float)millis() / 1000.0f;
expect('(');
if (t == T_POINT) {
i16 x = to_int(expr()), y;
expect(',');
y = to_int(expr());
expect(')');
g_sync();
if ((u16)x >= gw || (u16)y >= gh) return 0;
g_at(x, y);
return g_get();
}
if (t == T_EOF) {
struct chan *c = chan_arg('I');
expect(')');
return c->pos >= c->len ? -1 : 0;
}
if (t == T_LEN || t == T_VAL || t == T_ASC) {
u8 *p = (u8 *)s;
sexpr(s);
expect(')');
if (t == T_LEN) return strlen(s);
if (t == T_ASC) return (u8)s[0];
while (*p == ' ') p++;
if (*p == '-') { p++; return -parse_num(&p); }
if (*p == '+') p++;
return *p ? parse_num(&p) : 0;
}
v = expr();
expect(')');
switch (t) {
case T_SIN: return sinf(v);
case T_COS: return cosf(v);
case T_TAN: return tanf(v);
case T_ATN: return atanf(v);
case T_EXP: return expf(v);
case T_LOG: if (v <= 0) error(E_FUNC); return logf(v);
case T_ABS: return v < 0 ? -v : v;
case T_SQR: if (v < 0) error(E_FUNC); return sqrtf(v);
case T_INT: return floorf(v);
case T_SGN: return v > 0 ? 1 : v < 0 ? -1 : 0;
case T_PEEK: return peek((u32)(i32)v);
case T_INP: return io_in((u8)to_int(v));
}
error(E_SYNTAX);
return 0;
}
static float call_fn(void)
{
u8 f, *save_tp;
float arg, old, r;
struct fn *d;
f = peekc();
if (!is_alpha(f)) error(E_SYNTAX);
tp++;
d = &fns[f - 'A'];
if (!d->body) error(E_UNDEF_FN);
expect('(');
arg = expr();
expect(')');
old = vars[d->var];
vars[d->var] = arg;
save_tp = tp;
tp = d->body;
r = expr();
tp = save_tp;
vars[d->var] = old;
return r;
}
static float primary(void)
{
u8 c = peekc();
float v;
if (is_digit(c) || c == '.') return parse_num(&tp);
if (c == '(') {
tp++;
v = expr();
expect(')');
return v;
}
if (is_str_start()) error(E_TYPE);
if (c == T_FN) { tp++; return call_fn(); }
if (c >= T_SIN && c <= T_POINT && c != T_FN && c != T_TAB) { tp++; return func(c); }
if (is_alpha(c)) return *num_ref();
error(E_SYNTAX);
return 0;
}
static float unary(void);
static float power(void)
{
float v = primary();
while (accept('^')) v = ipow(v, unary());
return v;
}
static float unary(void)
{
if (accept('-')) return -unary();
if (accept('+')) return unary();
return power();
}
static float term(void)
{
float v = unary(), d;
for (;;) {
if (accept('*')) v *= unary();
else if (accept('/')) {
d = unary();
if (d == 0) error(E_DIV0);
v /= d;
} else return v;
}
}
static float sum(void)
{
float v = term();
for (;;) {
if (accept('+')) v += term();
else if (accept('-')) v -= term();
else return v;
}
}
/* relational operator: bit 0 '<', bit 1 '=', bit 2 '>' */
static u8 relop(void)
{
u8 c = peekc();
if (c == '=') { tp++; return 2; }
if (c == T_NE) { tp++; return 5; }
if (c == T_LE) { tp++; return 3; }
if (c == T_GE) { tp++; return 6; }
if (c == '<') { tp++; if (accept('>')) return 5; if (accept('=')) return 3; return 1; }
if (c == '>') { tp++; if (accept('=')) return 6; return 4; }
return 0;
}
static float relation(void)
{
u8 op;
i16 c;
if (is_str_start()) {
char a[STRMAX], b[STRMAX];
sexpr(a);
op = relop();
if (!op) error(E_TYPE);
sexpr(b);
c = strcmp(a, b);
} else {
float x = sum(), y;
op = relop();
if (!op) return x;
y = sum();
c = x < y ? -1 : x > y ? 1 : 0;
}
return ((c < 0 && (op & 1)) || (c == 0 && (op & 2)) || (c > 0 && (op & 4))) ? -1 : 0;
}
static float notx(void)
{
if (accept(T_NOT)) return (float)~to_int(notx());
return relation();
}
static float andx(void)
{
float v = notx();
while (accept(T_AND)) v = (float)(to_int(v) & to_int(notx()));
return v;
}
static float expr(void)
{
float v = andx();
while (accept(T_OR)) v = (float)(to_int(v) | to_int(andx()));
return v;
}
/* ------------------------------------------------------------ strings */
static void str_prim(char *out)
{
u8 c = peekc(), n;
char s[STRMAX];
i16 a, b;
if (c == '"') {
tp++;
n = 0;
while (*tp && *tp != '"') {
if (n >= STRMAX - 1) error(E_STRING);
out[n++] = *tp++;
}
out[n] = 0;
if (*tp) tp++;
return;
}
if (is_alpha(c) && tp[1] == '$') {
strcpy(out, str_ref());
return;
}
tp++;
if (c == T_DATES) { fmt_date(now(), out, 1); return; }
expect('(');
switch (c) {
case T_CHRS:
out[0] = to_int(expr());
out[1] = 0;
break;
case T_STRS: {
float v = expr();
out[0] = ' ';
fmt_num(v, v < 0 ? out : out + 1);
break;
}
case T_LEFTS:
case T_RIGHTS:
case T_MIDS:
sexpr(s);
expect(',');
a = to_int(expr());
n = strlen(s);
if (c == T_MIDS) {
b = accept(',') ? to_int(expr()) : 255;
if (a < 1 || b < 0) error(E_FUNC);
if (a > n) a = n + 1;
if (b > n - a + 1) b = n - a + 1;
memcpy(out, s + a - 1, b);
out[b] = 0;
} else {
if (a < 0) error(E_FUNC);
if (a > n) a = n;
if (c == T_LEFTS) { memcpy(out, s, a); out[a] = 0; }
else strcpy(out, s + n - a);
}
break;
default:
error(E_SYNTAX);
}
expect(')');
}
static void sexpr(char *out)
{
char s[STRMAX];
if (!is_str_start()) error(E_TYPE);
str_prim(out);
while (accept('+')) {
if (!is_str_start()) error(E_TYPE);
str_prim(s);
if (strlen(out) + strlen(s) >= STRMAX) error(E_STRING);
strcat(out, s);
}
}
/* ------------------------------------------------------------ console in */
static int held = -1; /* a key read while checking for Ctrl-C */
static u8 getkey(void)
{
int c = held;
if (c >= 0) { held = -1; return c; }
return wait_c();
}
static void check_break(void)
{
int c;
if (held >= 0) return;
c = poll_c();
if (c == 3) error(E_BREAK);
if (c >= 0) held = c;
}
/* ------------------------------------------------------------ line editor
The line being typed is linebuf[0..ed_n) with the cursor at ed_cur. Left
and Right move, Home and End (or Ctrl-A, Ctrl-E) jump, typing inserts,
Backspace and Delete take out, Ctrl-U clears, Up brings back the last line.
At the end of a line that is only a line number, Right copies that program
line one character at a time and End copies the rest of it; Delete there
skips a character of it. The screen is kept up to date with cursor moves
only, so a line may wrap: ed_sc is the column it starts in, ed_w the
screen width (80 or 132, read when the line starts), ed_row the screen row (from the line's first) the
terminal's cursor is on and ed_at the place it is at. */
static u8 ed_w = 80;
static void esc_num(u8 n);
static u8 ed_sc, ed_row, ed_at, ed_pend, ed_n, ed_cur;
static u8 *ed_src; /* the program line being copied, or 0 */
static const char *ed_kw; /* the keyword being copied out of it */
static void ed_csi(u8 n, char f)
{
out_c(27); out_c('['); esc_num(n); out_c(f);
}
/* Put the terminal's cursor at place i of the line. */
static void ed_go(u8 i)
{
u16 p = ed_sc + i;
u8 r = p / ed_w, c = p % ed_w;
if (i == ed_at && !ed_pend) return;
out_c('\r');
if (r < ed_row) ed_csi(ed_row - r, 'A');
for (; ed_row < r; ed_row++) out_c('\n');
if (c) ed_csi(c, 'C');
ed_row = r; ed_at = i; ed_pend = 0;
}
/* Write the line from place i on, blank `gone` cells after it, then put the
cursor back. */
static void ed_show(u8 i, u8 gone)
{
u8 k = i;
ed_go(i);
for (; k < ed_n; k++) out_c(linebuf[k]);
for (; gone; gone--, k++) out_c(' ');
if (k > i) {
ed_row = (ed_sc + k - 1) / ed_w;
ed_at = k;
ed_pend = (ed_sc + k) % ed_w == 0;
}
ed_go(ed_cur);
}
/* Start copying the program line whose number is all that has been typed. */
static void ed_start(void)
{
u8 i = 0;
u16 v = 0;
u8 *p;
if (ed_src || ed_cur < ed_n) return;
while (i < ed_n && linebuf[i] == ' ') i++;
if (i == ed_n) return;
for (; i < ed_n; i++) {
if (!is_digit(linebuf[i])) return;
v = v * 10 + linebuf[i] - '0';
}
p = find_line(v);
if (*p && line_no(p) == v) { ed_src = p + 3; ed_kw = " "; }
}
/* The next character of the line being copied, or 0. */
static char ed_next(void)
{
u8 c;
if (!ed_src) return 0;
if (*ed_kw) return *ed_kw++;
c = *ed_src;
if (!c) return 0;
ed_src++;
if (c >= T_LET && c < T_LAST) { ed_kw = kw[c - T_LET]; return *ed_kw++; }
return c;
}
/* Copy up to n characters of it to the end of the line. */
static void ed_copy(u8 n)
{
u8 i = ed_n;
char c;
ed_start();
for (; n && ed_n < 250 && (c = ed_next()); n--) linebuf[ed_n++] = c;
ed_cur = ed_n;
ed_show(i, 0);
}
/* Take out the character at the cursor. */
static void ed_del(void)
{
memmove(linebuf + ed_cur, linebuf + ed_cur + 1, ed_n - ed_cur - 1);
ed_n--;
ed_show(ed_cur, 1);
}
/* Read a line with echo and editing; returns 0 on Ctrl-C. */
static u8 read_line(void)
{
u8 c, k;
ed_w = scr_width();
ed_sc = col % ed_w;
ed_row = ed_at = ed_pend = ed_n = ed_cur = 0;
ed_src = 0;
for (;;) {
c = getkey();
if (c == '\r' || c == '\n') {
ed_cur = ed_n; ed_go(ed_n);
newline(); linebuf[ed_n] = 0;
if (ed_n) strcpy(ed_last, linebuf);
return 1;
}
if (c == 3) { ed_cur = ed_n; ed_go(ed_n); puts_("^C"); newline(); return 0; }
if (c == 27) { /* cursor and editing keys */
c = getkey();
k = 0;
if (c == '[' || c == 'O')
do { c = getkey(); if (is_digit(c)) k = c; } while (c < 0x40 || c > 0x7E);
if (c == '~') c = k == '1' ? 'H' : k == '4' ? 'F' : k == '3' ? 'P' : 0;
} else if (c == 1) c = 'H';
else if (c == 5) c = 'F';
else if (c == 21) { /* Ctrl-U */
k = ed_n;
ed_n = ed_cur = 0;
ed_src = 0;
ed_show(0, k);
continue;
} else if (c == 8 || c == 127) {
if (ed_cur) { ed_cur--; ed_del(); }
continue;
} else {
if (c >= ' ' && c < 127 && ed_n < 250) {
memmove(linebuf + ed_cur + 1, linebuf + ed_cur, ed_n - ed_cur);
linebuf[ed_cur++] = c;
ed_n++;
ed_show(ed_cur - 1, 0);
}
continue;
}
if (c == 'A') { /* Up: the last line again */
k = ed_n;
strcpy(linebuf, ed_last);
ed_n = ed_cur = strlen(linebuf);
ed_src = 0;
ed_show(0, k > ed_n ? k - ed_n : 0);
} else if (c == 'C') {
if (ed_cur < ed_n) ed_cur++;
else ed_copy(1);
} else if (c == 'D') { if (ed_cur) ed_cur--; }
else if (c == 'H') ed_cur = 0;
else if (c == 'F') {
if (ed_cur < ed_n) ed_cur = ed_n;
else ed_copy(250);
} else if (c == 'P') {
if (ed_cur < ed_n) ed_del();
else { ed_start(); ed_next(); }
}
ed_go(ed_cur);
}
}
/* ------------------------------------------------------------ statements */
static void goto_line(u16 n)
{
u8 *p = find_line(n);
if (!*p || line_no(p) != n) error(E_LINE);
curln = p;
tp = p + 3;
jumped = 1;
}
static void skip_statement(void)
{
u8 q = 0;
while (*tp && (q || *tp != ':')) {
if (*tp == '"') q = !q;
tp++;
}
}
static void skip_line(void)
{
while (*tp) tp++;
}
static void print_items(void);
static void st_print(void)
{
struct chan *c;
if (!accept('#')) { print_items(); return; }
c = chan_arg('O');
if (!at_end()) expect(',');
scr_col = col;
col = c->col;
out_ch = c - ch;
print_items();
out_ch = 0;
c->col = col;
col = scr_col;
}
static void print_items(void)
{
char buf[STRMAX + 2];
u8 sep = 0;
i16 n;
while (!at_end()) {
sep = 0;
if (accept(',')) {
do putch(' '); while (col % 15);
sep = 1;
} else if (accept(';')) {
sep = 1;
} else if (accept(T_TAB)) {
expect('(');
n = to_int(expr());
expect(')');
while (col < n) putch(' ');
} else if (is_str_start()) {
sexpr(buf);
puts_(buf);
} else {
float v = expr();
if (v >= 0) putch(' ');
fmt_num(v, buf);
puts_(buf);
putch(' ');
}
}
if (!sep) newline();
}
static void st_let(void)
{
u8 c = peekc();
if (is_alpha(c) && tp[1] == '$') {
char *dst = str_ref();
expect('=');
sexpr(dst);
} else {
float *ref = num_ref();
expect('=');
*ref = expr();
}
}
/* Read one number or string item from *pp into the variable at tp. */
static u8 assign_item(u8 **pp)
{
u8 *p = *pp, c = peekc(), n = 0;
while (*p == ' ') p++;
if (is_alpha(c) && tp[1] == '$') {
char *dst = str_ref();
if (*p == '"') {
for (p++; *p && *p != '"'; p++) if (n < STRMAX - 1) dst[n++] = *p;
if (*p) p++;
} else {
for (; *p && *p != ','; p++) if (n < STRMAX - 1) dst[n++] = *p;
while (n && dst[n - 1] == ' ') n--;
}
dst[n] = 0;
} else {
float *ref = num_ref(), v;
u8 neg = 0;
if (*p == '-') { neg = 1; p++; }
else if (*p == '+') p++;
if (!is_digit(*p) && *p != '.') return 0;
v = parse_num(&p);
*ref = neg ? -v : v;
}
while (*p == ' ') p++;
*pp = p;
return 1;
}
/* INPUT #n, items: values separated by commas, over as many lines as needed */
static void input_file(void)
{
struct chan *c = chan_arg('I');
u8 *p;
expect(',');
if (!chan_line(c)) error(E_EOF);
p = (u8 *)linebuf;
for (;;) {
if (!assign_item(&p)) error(E_TYPE);
if (!accept(',')) break;
if (*p == ',') p++;
else if (!*p) {
if (!chan_line(c)) error(E_EOF);
p = (u8 *)linebuf;
}
}
}
/* LINE INPUT [#n,] ["prompt";] A$: a whole line, commas and quotes included */
static void st_line_input(void)
{
u8 v;
if (accept('#')) {
struct chan *c = chan_arg('I');
expect(',');
if (!chan_line(c)) error(E_EOF);
} else {
if (peekc() == '"') {
char prompt[STRMAX];
str_prim(prompt);
puts_(prompt);
if (!accept(';')) expect(',');
}
if (!read_line()) error(E_BREAK);
}
v = peekc();
if (!is_alpha(v) || tp[1] != '$') error(E_TYPE);
if (strlen(linebuf) >= STRMAX) linebuf[STRMAX - 1] = 0;
strcpy(str_ref(), linebuf);
}
static void st_input(void)
{
u8 *p;
if (accept('#')) { input_file(); return; }
if (peekc() == '"') {
char prompt[STRMAX];
str_prim(prompt);
puts_(prompt);
if (!accept(';')) expect(',');
}
puts_("? ");
if (!read_line()) error(E_BREAK);
p = (u8 *)linebuf;
for (;;) {
u8 *save = tp;
if (!assign_item(&p)) {
puts_("?REDO");
newline();
puts_("? ");
if (!read_line()) error(E_BREAK);
p = (u8 *)linebuf;
tp = save;
continue;
}
if (!accept(',')) break;
if (*p == ',') p++;
else if (!*p) {
puts_("?? ");
if (!read_line()) error(E_BREAK);
p = (u8 *)linebuf;
}
}
}
/* Move datap to the next DATA item. datap is 0 before the first READ,
otherwise it points just past the last item read. */
static void next_data(void)
{
if (datap) {
while (*datap == ' ') datap++;
if (*datap == ',') { datap++; return; }
dataln += *dataln;
} else dataln = arena;
for (; *dataln; dataln += *dataln) {
u8 *p = dataln + 3, q = 0;
for (; *p; p++) {
if (*p == '"') q = !q;
else if (!q && *p == T_DATA) { datap = p + 1; return; }
}
}
error(E_DATA);
}
static void st_read(void)
{
do {
next_data();
if (!assign_item(&datap)) error(E_SYNTAX);
if (*datap && *datap != ',') error(E_SYNTAX);
} while (accept(','));
}
static void st_for(void)
{
struct forent *f;
u8 v = var_name(), i;
if (v == 255) error(E_SYNTAX);
expect('=');
vars[v] = expr();
for (i = 0; i < nfor; i++) /* reusing a loop variable restarts it */
if (fors[i].var == v) { nfor = i; break; }
if (nfor >= FORMAX) error(E_FOR);
f = &fors[nfor];
f->var = v;
expect(T_TO);
f->limit = expr();
f->step = accept(T_STEP) ? expr() : 1;
f->tp = tp;
f->ln = curln;
nfor++;
/* skip the body when the loop runs zero times */
if ((f->step >= 0 && vars[v] > f->limit) || (f->step < 0 && vars[v] < f->limit)) {
u8 depth = 0;
nfor--;
for (;;) {
u8 c;
skip_statement();
if (!*tp) {
if (!curln || !*(curln + *curln)) error(E_FOR);
curln += *curln;
tp = curln + 3;
} else tp++;
c = peekc();
if (c == T_FOR) depth++;
else if (c == T_NEXT) {
if (!depth) {
tp++;
while (!at_end()) { var_name(); if (!accept(',')) break; }
return;
}
depth--;
}
}
}
}
static void st_next(void)
{
struct forent *f;
u8 v;
do {
v = var_name();
if (!nfor) error(E_NEXT);
if (v != 255) {
while (nfor && fors[nfor - 1].var != v) nfor--;
if (!nfor) error(E_NEXT);
}
f = &fors[nfor - 1];
vars[f->var] += f->step;
if ((f->step >= 0 && vars[f->var] <= f->limit) ||
(f->step < 0 && vars[f->var] >= f->limit)) {
tp = f->tp;
curln = f->ln;
jumped = 1;
return;
}
nfor--;
} while (v != 255 && accept(','));
}
static void st_dim(void)
{
do {
u8 a = peekc() - 'A';
u16 d1, d2 = 0;
if (a >= 26) error(E_SYNTAX);
if (*++tp == '$') { tp++; a += 26; }
expect('(');
d1 = to_int(expr());
if (accept(',')) d2 = to_int(expr());
expect(')');
arr_alloc(a, d1, d2);
} while (accept(','));
}
static void st_def(void)
{
u8 f, v;
expect(T_FN);
f = peekc();
if (!is_alpha(f)) error(E_SYNTAX);
tp++;
expect('(');
v = var_name();
if (v == 255) error(E_SYNTAX);
expect(')');
expect('=');
fns[f - 'A'].var = v;
fns[f - 'A'].body = tp;
skip_statement();
}
static void do_gosub(u16 n)
{
if (nsub >= GOSUBMAX) error(E_GOSUB);
subs[nsub].tp = tp;
subs[nsub].ln = curln;
nsub++;
goto_line(n);
}
static void st_list(void)
{
u16 a = 0, b = 65535;
u8 *p;
if (is_digit(peekc())) { a = b = get_lineno(); }
if (accept('-')) b = is_digit(peekc()) ? get_lineno() : 65535;
for (p = find_line(a); *p && line_no(p) <= b; p += *p) {
list_line(p);
check_break();
}
}
static void run_prog(void)
{
clear_vars();
curln = arena;
tp = arena + 3;
jumped = 1;
if (!arena[0]) { curln = 0; tp = (u8 *)""; }
}
/* ------------------------------------------------------------- graphics */
static u8 gcolor = 15;
/* Up to n comma-separated integer arguments; returns how many were given. */
static u8 int_args(i16 *a, u8 min, u8 n)
{
u8 i = 0;
do a[i++] = to_int(expr()); while (i < n && accept(','));
if (i < min) error(E_SYNTAX);
return i;
}
static u8 colour_arg(i16 *a, u8 given, u8 need)
{
if (given > need) {
if ((u16)a[need] > 15) error(E_FUNC);
return a[need];
}
return gcolor;
}
static void hline(i16 x1, i16 x2, i16 y, u8 c)
{
i16 t;
if (x1 > x2) { t = x1; x1 = x2; x2 = t; }
if ((u16)y >= gh || x2 < 0 || x1 >= (i16)gw) return;
if (x1 < 0) x1 = 0;
if (x2 >= (i16)gw) x2 = gw - 1;
g_at(x1, y);
for (; x1 <= x2; x1++) g_put(c);
}
static void pset(i16 x, i16 y, u8 c)
{
if ((u16)x < gw && (u16)y < gh) { g_at(x, y); g_put(c); }
}
static void line(i16 x1, i16 y1, i16 x2, i16 y2, u8 c)
{
i16 dx = x2 > x1 ? x2 - x1 : x1 - x2, sx = x1 < x2 ? 1 : -1;
i16 dy = y2 > y1 ? y1 - y2 : y2 - y1, sy = y1 < y2 ? 1 : -1;
i16 err = dx + dy, e2;
if (y1 == y2) { hline(x1, x2, y1, c); return; }
for (;;) {
pset(x1, y1, c);
if (x1 == x2 && y1 == y2) return;
e2 = 2 * err;
if (e2 >= dy) { err += dy; x1 += sx; }
if (e2 <= dx) { err += dx; y1 += sy; }
}
}
static void circle(i16 cx, i16 cy, i16 r, u8 c)
{
i16 x = r, y = 0, err = 1 - r;
if (r < 0) error(E_FUNC);
while (x >= y) {
pset(cx + x, cy + y, c); pset(cx - x, cy + y, c);
pset(cx + x, cy - y, c); pset(cx - x, cy - y, c);
pset(cx + y, cy + x, c); pset(cx - y, cy + x, c);
pset(cx + y, cy - x, c); pset(cx - y, cy - x, c);
y++;
if (err < 0) err += 2 * y + 1;
else { x--; err += 2 * (y - x) + 1; }
}
}
static void esc_num(u8 n)
{
if (n >= 100) out_c('0' + n / 100);
if (n >= 10) out_c('0' + n / 10 % 10);
out_c('0' + n % 10);
}
static void graphics(u8 t)
{
i16 a[5];
u8 n, c;
g_sync();
switch (t) {
case T_CLS:
out_c(27); out_c('['); out_c('2'); out_c('J');
out_c(27); out_c('['); out_c('H');
col = 0;
g_clear(ghi);
break;
case T_SCREEN: /* SCREEN 0 | SCREEN 1 [, set [, clear]] */
n = int_args(a, 1, 3);
if ((u16)a[0] > 1 || (n > 1 && (u16)a[1] > 15) || (n > 2 && (u16)a[2] > 15))
error(E_FUNC);
ghi = a[0];
gw = ghi ? 640 : 320;
gh = ghi ? 480 : 240;
g_colours(n > 1 ? a[1] : 15, n > 2 ? a[2] : 0);
g_clear(ghi);
break;
case T_COLOR:
int_args(a, 1, 1);
if ((u16)a[0] > 15) error(E_FUNC);
gcolor = a[0];
break;
case T_PLOT:
n = int_args(a, 2, 3);
pset(a[0], a[1], colour_arg(a, n, 2));
break;
case T_LINE:
n = int_args(a, 4, 5);
line(a[0], a[1], a[2], a[3], colour_arg(a, n, 4));
break;
case T_RECT:
n = int_args(a, 4, 5);
c = colour_arg(a, n, 4);
hline(a[0], a[2], a[1], c);
hline(a[0], a[2], a[3], c);
line(a[0], a[1], a[0], a[3], c);
line(a[2], a[1], a[2], a[3], c);
break;
case T_FILL: {
i16 y, y2;
n = int_args(a, 4, 5);
c = colour_arg(a, n, 4);
y = a[1] < a[3] ? a[1] : a[3];
y2 = a[1] < a[3] ? a[3] : a[1];
if (y < 0) y = 0;
if (y2 >= (i16)gh) y2 = gh - 1;
for (; y <= y2; y++) hline(a[0], a[2], y, c);
break;
}
case T_CIRCLE:
n = int_args(a, 3, 4);
circle(a[0], a[1], a[2], colour_arg(a, n, 3));
break;
case T_LOCATE: /* LOCATE row, column (from 1) */
int_args(a, 2, 2);
if (a[0] < 1 || a[0] > 64 || a[1] < 1 || a[1] > 132) error(E_FUNC);
out_c(27); out_c('['); esc_num(a[0]); out_c(';'); esc_num(a[1]); out_c('H');
col = a[1] - 1;
break;
case T_INK: /* INK foreground [, background] */
n = int_args(a, 1, 2);
if ((u16)a[0] > 15 || (n > 1 && (u16)a[1] > 15)) error(E_FUNC);
out_c(27); out_c('[');
esc_num(a[0] < 8 ? 30 + a[0] : 82 + a[0]);
if (n > 1) { out_c(';'); esc_num(a[1] < 8 ? 40 + a[1] : 92 + a[1]); }
out_c('m');
break;
}
}
/* ---------------------------------------------------------- file system
Programs are kept as plain text in the configuration flash from 2.25 MB to
the end (448 blocks of 4 KB). Blocks 0 and 1 hold the directory, written
alternately with a rising sequence number and a checksum, so a power cut
during SAVE or DEL leaves the previous directory intact. A file is saved
into free blocks before the directory names it. */
#define FS_BASE 0x240000UL
#define FS_BLOCKS 448
#define MAXFILES 64
struct dirent { char name[8]; u16 len; u16 blk[FBLK]; u16 date[2]; };
#define OLD_DIRENT 26 /* BFS1 entries had no date */
static struct {
char magic[4];
u16 seq, next;
struct dirent e[MAXFILES];
u16 sum;
} dir;
static u8 dir_cur; /* block holding the current directory */
static u8 bmap[FS_BLOCKS / 8]; /* blocks in use */
static u32 blk_addr(u16 b) { return FS_BASE + ((u32)b << 12); }
static u8 nblk(u16 len) { return (len + 4095) >> 12; }
static u16 sum_of(u16 n)
{
u8 *p = (u8 *)&dir;
u16 s = 0x5AA5;
while (n--) s = (s << 1 | s >> 15) + *p++;
return s;
}
static u16 dir_sum(void) { return sum_of(sizeof dir - 2); }
static u32 e_date(u8 i) { return dir.e[i].date[0] | (u32)dir.e[i].date[1] << 16; }
static void fl_wait(void)
{
i32 t = millis();
while (fl_busy())
if (millis() - t > 3000) error(E_FLASH);
}
static void fl_erase(u16 b)
{
if (!fl_write_op(0x20, blk_addr(b), 0, 0)) error(E_FLASH);
fl_wait();
}
/* program up to 256 bytes within one flash page, then check them */
static void fl_prog(u32 a, const u8 *p, u16 n)
{
u8 chk[32];
u16 i, k;
if (!fl_write_op(0x02, a, p, n)) error(E_FLASH);
fl_wait();
for (i = 0; i < n; i += k) {
k = n - i < 32 ? n - i : 32;
fl_read(a + i, chk, k);
if (memcmp(chk, p + i, k)) error(E_FLASH);
}
}
/* Read directory block b; a BFS1 directory is widened in memory, with no dates. */
static u8 load_dir(u8 b)
{
u8 *p = (u8 *)&dir, i;
u16 old = 8 + MAXFILES * OLD_DIRENT;
fl_read(blk_addr(b), p, sizeof dir);
if (!memcmp(dir.magic, "BFS2", 4)) return dir.sum == dir_sum();
if (memcmp(dir.magic, "BFS1", 4) || (p[old] | p[old + 1] << 8) != sum_of(old)) return 0;
for (i = MAXFILES; i--; ) {
memmove(&dir.e[i], p + 8 + i * OLD_DIRENT, OLD_DIRENT);
dir.e[i].date[0] = dir.e[i].date[1] = 0;
}
memcpy(dir.magic, "BFS2", 4);
return 1;
}
/* Read the newest valid directory, or start an empty one. */
static void fs_mount(void)
{
u8 va, vb;
u16 sa;
if (!fl_present()) error(E_FLASH);
va = load_dir(0);
sa = dir.seq;
vb = load_dir(1);
if (va && (!vb || (i16)(sa - dir.seq) > 0)) { load_dir(0); dir_cur = 0; }
else if (vb) dir_cur = 1;
else {
memset(&dir, 0, sizeof dir);
memcpy(dir.magic, "BFS2", 4);
dir.next = 2;
dir_cur = 1; /* the first directory goes in block 0 */
}
}
static void fs_commit(void)
{
u8 b = dir_cur ^ 1, *p = (u8 *)&dir;
u16 i, n;
dir.seq++;
dir.sum = dir_sum();
fl_erase(b);
for (i = 0; i < sizeof dir; i += 256) {
n = sizeof dir - i < 256 ? sizeof dir - i : 256;
fl_prog(blk_addr(b) + i, p + i, n);
}
dir_cur = b;
}
static void build_bmap(void)
{
u8 i, j, n;
memset(bmap, 0, sizeof bmap);
bmap[0] = 3; /* the two directory blocks */
for (i = 0; i < MAXFILES; i++)
if (dir.e[i].name[0])
for (j = 0, n = nblk(dir.e[i].len); j < n; j++)
bmap[dir.e[i].blk[j] >> 3] |= 1 << (dir.e[i].blk[j] & 7);
for (i = 0; i < NCHAN; i++)
if (ch[i].mode)
for (j = 0, n = nblk(ch[i].mode == 'O' ? ch[i].pos : ch[i].len); j < n; j++)
bmap[ch[i].blk[j] >> 3] |= 1 << (ch[i].blk[j] & 7);
}
/* next free block after the last one handed out, spreading the wear */
static u16 alloc_blk(void)
{
u16 b = dir.next, k;
for (k = 0; k < FS_BLOCKS; k++, b++) {
if (b >= FS_BLOCKS) b = 2;
if (!(bmap[b >> 3] & (1 << (b & 7)))) {
bmap[b >> 3] |= 1 << (b & 7);
dir.next = b + 1;
return b;
}
}
error(E_DISKFULL);
return 0;
}
/* File name: 1-8 letters and digits, from any string expression. */
static void get_name(char *nm)
{
char s[STRMAX];
u8 i, c;
sexpr(s);
memset(nm, 0, 8);
for (i = 0; s[i]; i++) {
c = s[i];
if (c >= 'a' && c <= 'z') c -= 32;
if (i >= 8 || !(is_alpha(c) || is_digit(c))) error(E_NAME);
nm[i] = c;
}
if (!i) error(E_NAME);
}
static i16 find_file(const char *nm)
{
u8 i;
for (i = 0; i < MAXFILES; i++)
if (!memcmp(dir.e[i].name, nm, 8)) return i;
return -1;
}
static void put_name(const char *nm)
{
u8 i;
for (i = 0; i < 8; i++) putch(nm[i] ? nm[i] : ' ');
}
/* ------------------------------------------------------------- channels */
static void chan_putc(struct chan *c, u8 b)
{
if (!(c->pos & 4095)) {
u8 k = c->pos >> 12;
if (k >= FBLK) error(E_TOOBIG);
c->blk[k] = alloc_blk();
fl_erase(c->blk[k]);
}
c->buf[c->pos & 255] = b;
c->pos++;
if (!(c->pos & 255))
fl_prog(blk_addr(c->blk[(c->pos - 1) >> 12]) + ((c->pos - 256) & 4095), c->buf, 256);
}
static void file_putc(u8 b) { chan_putc(&ch[out_ch], b); }
static void save_putc(char b) { chan_putc(&ch[0], b); }
/* next byte of an input channel, -1 at the end */
static int chan_getc(struct chan *c)
{
if (c->pos >= c->len) return -1;
if ((c->pos >> 8) != c->pg) {
c->pg = c->pos >> 8;
fl_read(blk_addr(c->blk[c->pos >> 12]) + (c->pos & 0xF00), c->buf, 256);
}
return c->buf[c->pos++ & 255];
}
/* Read a line into linebuf (up to 250 characters); 0 if already at the end. */
static u8 chan_line(struct chan *c)
{
u8 n = 0;
int b = chan_getc(c);
if (b < 0) return 0;
while (b >= 0 && b != '\n') {
if (n < 250) linebuf[n++] = b;
b = chan_getc(c);
}
linebuf[n] = 0;
return 1;
}
static void chan_open_in(struct chan *c, const char *nm)
{
i16 i;
fs_mount();
i = find_file(nm);
if (i < 0) error(E_NOFILE);
memcpy(c->name, nm, 8);
c->len = dir.e[i].len;
memcpy(c->blk, dir.e[i].blk, sizeof c->blk);
c->pos = 0;
c->pg = 0xFFFF;
c->mode = 'I';
}
/* Start writing a new copy of file nm; with append, it starts as the old one.
The directory only changes at chan_close, so until then the old file stays. */
static void chan_open_out(struct chan *c, const char *nm, u8 append)
{
i16 i;
u16 j, len;
u8 b;
fs_mount();
build_bmap();
i = find_file(nm);
if (i < 0) {
for (j = 0; j < MAXFILES && dir.e[j].name[0]; j++);
if (j == MAXFILES) error(E_DIRFULL);
}
memcpy(c->name, nm, 8);
c->pos = 0;
c->col = 0;
c->mode = 'O';
if (append && i >= 0) {
struct dirent e = dir.e[i];
len = e.len;
b = len >> 12; /* whole blocks are shared as they are */
memcpy(c->blk, e.blk, b * 2);
c->pos = (u16)b << 12;
for (j = c->pos; j < len; j++) { /* the part block is copied */
u8 v;
fl_read(blk_addr(e.blk[b]) + (j & 4095), &v, 1);
chan_putc(c, v);
}
}
}
static void chan_close(struct chan *c)
{
u16 n;
i16 i;
u8 m = c->mode;
c->mode = 0;
if (m != 'O') return;
n = c->pos & 255;
if (n) fl_prog(blk_addr(c->blk[(c->pos - 1) >> 12]) + ((c->pos - n) & 4095), c->buf, n);
fs_mount();
i = find_file(c->name);
if (i < 0) {
for (i = 0; i < MAXFILES && dir.e[i].name[0]; i++);
if (i == MAXFILES) error(E_DIRFULL);
}
if (!dir.e[i].name[0] || !e_date(i)) { /* keep the creation date */
u32 t = now();
dir.e[i].date[0] = (u16)t;
dir.e[i].date[1] = t >> 16;
}
memcpy(dir.e[i].name, c->name, 8);
dir.e[i].len = c->pos;
memcpy(dir.e[i].blk, c->blk, sizeof c->blk);
fs_commit();
}
static void close_all(void)
{
u8 i;
for (i = 1; i < NCHAN; i++) chan_close(&ch[i]);
}
/* [#]n of an open channel in the given mode */
static struct chan *chan_arg(u8 mode)
{
i16 n;
accept('#');
n = to_int(expr());
if (n < 1 || n >= NCHAN) error(E_FUNC);
if (ch[n].mode != mode) error(E_NOTOPEN);
return &ch[n];
}
/* OPEN "NAME" FOR INPUT|OUTPUT|APPEND AS #n */
static void st_open(void)
{
char nm[8];
u8 m;
i16 n;
get_name(nm);
expect(T_FOR);
m = peekc();
if (m != T_INPUT && m != T_OUTPUT && m != T_APPEND) error(E_SYNTAX);
tp++;
if (peekc() != 'A' || tp[1] != 'S') error(E_SYNTAX);
tp += 2;
accept('#');
n = to_int(expr());
if (n < 1 || n >= NCHAN) error(E_FUNC);
if (ch[n].mode) error(E_OPEN);
if (m == T_INPUT) chan_open_in(&ch[n], nm);
else chan_open_out(&ch[n], nm, m == T_APPEND);
}
/* CLOSE [#n [, #n ...]], or every file */
static void st_close(void)
{
i16 n;
if (at_end()) { close_all(); return; }
do {
accept('#');
n = to_int(expr());
if (n < 1 || n >= NCHAN) error(E_FUNC);
chan_close(&ch[n]);
} while (accept(','));
}
/* BSAVE "NAME", start, length / BLOAD "NAME" [, address]: memory files,
the load address (4 bytes, low first) and then the bytes, as the monitor
writes them */
static void st_bfile(u8 t)
{
char nm[8];
u32 a, n;
int b;
u8 i;
struct chan *c = &ch[0];
c->mode = 0;
get_name(nm);
if (t == T_BSAVE) {
expect(','); a = (u32)(i32)expr();
expect(','); n = (u32)(i32)expr();
chan_open_out(c, nm, 0);
for (i = 0; i < 32; i += 8) chan_putc(c, a >> i);
while (n--) chan_putc(c, peek(a++));
chan_close(c);
} else {
chan_open_in(c, nm);
for (a = 0, i = 0; i < 32; i += 8) a |= (u32)chan_getc(c) << i;
if (accept(',')) a = (u32)(i32)expr();
while ((b = chan_getc(c)) >= 0) poke(a++, b);
c->mode = 0;
}
}
static void st_save(void)
{
char nm[8];
u8 *p;
struct chan *c = &ch[0];
c->mode = 0;
get_name(nm);
chan_open_out(c, nm, 0);
for (p = arena; *p; p += *p) {
list_to(p, save_putc);
save_putc('\n');
}
chan_close(c);
}
/* Store a typed or loaded line "<number> <text>"; ignores lines without a number. */
static void enter_line(char *s)
{
u16 n = 0;
while (*s == ' ') s++;
if (!is_digit(*s)) return;
while (is_digit(*s)) n = n * 10 + (*s++ - '0');
while (*s == ' ') s++;
tokenize(s, tokbuf);
store_line(n, tokbuf);
}
static void fs_load(void)
{
char nm[8];
struct chan *c = &ch[0];
c->mode = 0;
get_name(nm);
chan_open_in(c, nm);
new_prog();
while (chan_line(c)) enter_line(linebuf);
c->mode = 0;
}
static void st_dir(void)
{
u8 i, n = 0;
u16 used = 2;
fs_mount();
for (i = 0; i < MAXFILES; i++) {
if (!dir.e[i].name[0]) continue;
put_name(dir.e[i].name);
do putch(' '); while (col < 10);
put_u16(dir.e[i].len);
if (e_date(i)) {
char d[20];
fmt_date(e_date(i), d, 0);
do putch(' '); while (col < 17);
puts_(d);
}
newline();
used += nblk(dir.e[i].len);
n++;
check_break();
}
put_u16(n);
puts_(n == 1 ? " FILE, " : " FILES, ");
put_u16((FS_BLOCKS - used) * 4);
puts_("K FREE");
newline();
}
static void st_del(void)
{
char nm[8];
i16 i;
get_name(nm);
fs_mount();
i = find_file(nm);
if (i < 0) error(E_NOFILE);
memset(&dir.e[i], 0, sizeof dir.e[i]);
fs_commit();
}
/* RENUM [start [, step]]: number the lines start, start+step, ... and change
the line numbers after GOTO, GOSUB, THEN, RUN and ON ... GOTO/GOSUB to
match. The new program is built in the free memory above the old one and
only copied down at the end, so an error leaves the program as it was. */
static u16 rn_start, rn_step;
static u8 *rn_o;
static void rn_put(u8 c)
{
if (rn_o >= arr_low) error(E_MEMORY);
*rn_o++ = c;
}
static u16 rn_new(u16 v)
{
u8 *r = arena;
u16 n = rn_start;
for (; *r; r += *r, n += rn_step)
if (line_no(r) == v) return n;
return v;
}
static void st_renum(void)
{
u8 *p, *q, *h, t, want, i;
u16 n, v;
char b[6];
rn_start = rn_step = 10;
if (!at_end()) {
rn_start = get_lineno();
if (accept(',')) rn_step = get_lineno();
}
if (!rn_step) error(E_FUNC);
clear_vars();
rn_o = prog_end + 1;
for (p = arena, n = rn_start; *p; p += *p, n += rn_step) {
if (n < rn_start) error(E_FUNC); /* past 65535 */
h = rn_o;
rn_put(0); rn_put(n); rn_put(n >> 8);
for (q = p + 3; (t = *q++) != 0; ) {
rn_put(t);
if ((t < T_THEN || t > T_GOSUB) && t != T_RUN) continue; /* THEN GOTO GOSUB */
for (want = 1;;) {
while (*q == ' ') rn_put(*q++);
if (want && is_digit(*q)) {
v = 0;
while (is_digit(*q)) v = v * 10 + (*q++ - '0');
fmt_ul(rn_new(v), b);
for (i = 0; b[i]; i++) rn_put(b[i]);
want = 0;
} else if (!want && *q == ',') {
rn_put(*q++);
want = 1;
} else break;
}
}
rn_put(0);
if (rn_o - h > 255) error(E_STRING);
*h = rn_o - h;
}
rn_put(0);
n = rn_o - (prog_end + 1);
memmove(arena, prog_end + 1, n);
prog_end = arena + n - 1;
}
/* Stop running and go back to READY after this statement. */
static void to_ready(void)
{
running = 0;
curln = 0;
tp = (u8 *)"";
}
static void statement(void);
static void st_if(void)
{
float c = expr();
if (!accept(T_THEN) && peekc() != T_GOTO) error(E_SYNTAX);
if (!c) { skip_line(); return; }
if (is_digit(peekc())) goto_line(get_lineno());
else statement();
}
static void statement(void)
{
u8 t = peekc(), n;
u16 ln;
if (t == 0 || t == ':') return;
tp++;
switch (t) {
case T_LET: st_let(); break;
case T_PRINT: st_print(); break;
case T_INPUT: st_input(); break;
case T_IF: st_if(); break;
case T_GOTO: goto_line(get_lineno()); break;
case T_GOSUB: ln = get_lineno(); do_gosub(ln); break;
case T_RETURN:
if (!nsub) error(E_RETURN);
nsub--;
tp = subs[nsub].tp;
curln = subs[nsub].ln;
jumped = 1;
break;
case T_FOR: st_for(); break;
case T_NEXT: st_next(); break;
case T_DIM: st_dim(); break;
case T_DEF: st_def(); break;
case T_END: close_all(); running = 0; break;
case T_STOP: error(E_STOP); break;
case T_REM: skip_line(); break;
case T_DATA: skip_line(); break;
case T_READ: st_read(); break;
case T_RESTORE: datap = 0; break;
case T_ON:
n = to_int(expr());
t = peekc();
if (t != T_GOTO && t != T_GOSUB) error(E_SYNTAX);
tp++;
for (;;) {
ln = get_lineno();
if (--n == 0) {
if (t == T_GOSUB) { skip_statement(); do_gosub(ln); }
else goto_line(ln);
return;
}
if (!accept(',')) break;
}
skip_statement();
break;
case T_RANDOMIZE: seed ^= (u32)millis() * 2654435761UL; break;
case T_POKE: {
u32 a = (u32)(i32)expr();
expect(',');
poke(a, (u8)to_int(expr()));
break;
}
case T_OUT: {
u8 p = (u8)to_int(expr());
expect(',');
io_out(p, (u8)to_int(expr()));
break;
}
case T_LOAD:
close_all();
fs_load();
to_ready();
break;
case T_SAVE: st_save(); break;
case T_DIR: st_dir(); break;
case T_DEL: st_del(); break;
case T_OPEN: st_open(); break;
case T_CLOSE: st_close(); break;
case T_BSAVE: case T_BLOAD: st_bfile(t); break;
#ifdef __riscv
case T_MONITOR: io_out(0x61, 0); break; /* NMI into the monitor */
case T_CALL: ((void (*)(void))(u32)(i32)expr())(); break;
#endif
case T_DATE: {
char d[STRMAX];
if (is_str_start()) { sexpr(d); set_date(d); break; }
fmt_date(now(), d, 1);
puts_(*d ? d : "DATE NOT SET");
newline();
break;
}
case T_RUN:
close_all();
if (is_str_start()) fs_load();
run_prog();
running = 1;
if (is_digit(peekc())) goto_line(get_lineno());
break;
case T_LIST: st_list(); break;
case T_NEW:
case T_SCRATCH: close_all(); new_prog(); to_ready(); break;
case T_RENUM: st_renum(); to_ready(); break;
case T_BYE: bye(); break;
case T_LINE:
if (accept(T_INPUT)) { st_line_input(); break; }
graphics(t);
break;
case T_CLS: case T_COLOR: case T_PLOT: case T_RECT:
case T_FILL: case T_CIRCLE: case T_LOCATE: case T_INK: case T_SCREEN:
graphics(t);
break;
default:
tp--;
st_let();
}
}
/* Run statements from tp until the program ends or stops. */
static void execute(void)
{
running = 1;
while (running) {
check_break();
jumped = 0;
statement();
if (!running) break;
if (jumped) continue;
if (accept(':')) continue;
if (peekc()) error(E_SYNTAX);
if (!curln) break; /* end of a direct statement */
curln += *curln;
if (!*curln) { close_all(); break; } /* end of program */
tp = curln + 3;
}
running = 0;
}
int main(void)
{
u16 n;
u8 *p;
#ifdef __riscv
clk_sec = 0;
#endif
new_prog();
g_clear(0);
newline();
puts_("DARTMOUTH-STYLE BASIC RISC-V ON A BASYS 3");
newline();
if (setjmp(errjmp)) {
running = 0;
nfor = nsub = 0;
curln = 0;
}
for (;;) {
if (!running) { newline(); puts_("READY"); newline(); }
for (;;) {
if (!read_line()) continue;
p = (u8 *)linebuf;
while (*p == ' ') p++;
if (!*p) continue;
if (is_digit(*p)) {
n = 0;
while (is_digit(*p)) n = n * 10 + (*p++ - '0');
while (*p == ' ') p++;
tokenize((char *)p, tokbuf);
store_line(n, tokbuf);
continue;
}
break;
}
tokenize((char *)p, tokbuf);
curln = 0;
tp = tokbuf;
execute();
curln = 0;
}
}