Files
Basys3Terminal/basic/basic.c
T
brad ArantandClaude Opus 5.5 767377f38d BASIC: file dates and data files
DATE "YYYY-MM-DD[ HH:MM[:SS]]" sets a clock kept from the millisecond
counter, DATE prints it and DATE$ returns it. Directory entries now
record each file's creation date (format BFS2; a BFS1 directory is
widened when read), and DIR shows it. send-bas.py and get-bas.py set
the date from the PC when they connect (--no-date to skip).

Data files: OPEN "NAME" FOR INPUT|OUTPUT|APPEND AS #n (n = 1-3),
PRINT #n, INPUT #n, LINE INPUT [#n,], EOF(n), CLOSE [#n]. SAVE and LOAD
now use the same channel code. A written file replaces the old one only
at CLOSE; APPEND shares the old file's full blocks and copies the last
part block. New errors FILE ALREADY OPEN, FILE NOT OPEN, INPUT PAST END;
PROGRAM TOO BIG TO SAVE becomes FILE TOO BIG.

The program area shrinks from 23000 to 22100 bytes to keep the stack
at about 3 KB beside the file buffers. Code now ends at 7EBFh.

The simulation sets the date, checks it in DIR and round-trips a data
file, waiting for expected rows instead of fixed delays. Tested on the
board: dates, write/append/read, EOF, the BFS1 conversion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 08:50:15 -08:00

2153 lines
58 KiB
C

/*
* Dartmouth-style BASIC for the Basys 3 Z-80.
*
* 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. 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 SDCC for the Z-80 (console on I/O ports 0/1) 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 int16_t i16;
typedef int32_t i32;
typedef uint32_t u32;
/* ------------------------------------------------------------- platform */
#ifdef __SDCC
__sfr __at 0x00 con_stat; /* bit 0: key waiting, bit 1: can send */
__sfr __at 0x01 con_data;
__sfr __at 0x10 tim0; /* reading tim0 latches the millisecond counter */
__sfr __at 0x11 tim1;
__sfr __at 0x12 tim2;
__sfr __at 0x13 tim3;
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)
{
u8 a = tim0;
return (i32)a | (i32)tim1 << 8 | (i32)tim2 << 16 | (i32)tim3 << 24;
}
static u8 peek(u16 a) { return *(volatile u8 *)a; }
static void poke(u16 a, u8 v) { *(volatile u8 *)a = v; }
static u8 port_a;
static u8 io_in(u8 p)
{
port_a = p;
__asm
ld a, (_port_a)
ld c, a
in a, (c)
ld (_port_a), a
__endasm;
return port_a;
}
static u8 port_v;
static void io_out(u8 p, u8 v)
{
port_a = p; port_v = v;
__asm
ld a, (_port_a)
ld c, a
ld a, (_port_v)
out (c), a
__endasm;
}
static void bye(void) { }
__sfr __at 0x30 gx_lo;
__sfr __at 0x31 gx_hi;
__sfr __at 0x32 gy_p;
__sfr __at 0x33 gpix; /* write plots and moves right; read gives the colour */
__sfr __at 0x34 gfill;
static void g_at(u16 x, u8 y) { gx_lo = x; gx_hi = x >> 8; gy_p = y; }
static void g_put(u8 c) { gpix = c; }
static u8 g_get(void) { return gpix; }
static void g_clear(u8 c) { gfill = c; while (gfill & 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. */
__sfr __at 0x40 fl_ctl;
__sfr __at 0x41 fl_dat;
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(u16 a) { return fake_mem[a]; }
static void poke(u16 a, u8 v) { fake_mem[a] = 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 gmem[240][320];
static u16 hgx;
static u8 hgy;
static void g_at(u16 x, u8 y) { hgx = x; hgy = y; }
static void g_put(u8 c) { if (hgx < 320 && hgy < 240) gmem[hgy][hgx] = c; hgx++; }
static u8 g_get(void) { return hgx < 320 && hgy < 240 ? gmem[hgy][hgx] : 0; }
static void g_clear(u8 c) { memset(gmem, c, sizeof gmem); }
/* 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);
/* ----------------------------------------------------------------- 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_SAVE, T_LOAD, T_DIR, T_DEL, T_DATE, T_OPEN, T_CLOSE, 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_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",
"SAVE", "LOAD", "DIR", "DEL", "DATE", "OPEN", "CLOSE", "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", "<=", ">=", "<>"
};
/* ----------------------------------------------------------------- memory */
#define ARENA 22100 /* program text grows up, arrays grow down */
#define STRMAX 80
#define NVARS (26 * 11)
#define FORMAX 16
#define GOSUBMAX 32
static u8 arena[ARENA];
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 { float *p; u16 d1, d2; };
static struct array arrays[26];
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. */
static u32 clk_sec;
static i32 clk_ms; /* millis() at clk_sec */
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)
{
u16 y = 2000, days = t / 86400UL;
u8 m = 1, i;
u32 r = t % 86400UL;
u16 v[6];
if (!t) { *out = 0; return; }
while (days >= 365 + leap(y)) days -= 365 + leap(y++);
while (days >= month_len(y, m)) days -= month_len(y, m++);
v[0] = y; v[1] = m; v[2] = days + 1;
v[3] = r / 3600; v[4] = r / 60 % 60; v[5] = r % 60;
for (i = 0; i < (sec ? 6 : 5); i++) {
if (i == 0) {
*out++ = '0' + y / 1000; *out++ = '0' + y / 100 % 10;
}
*out++ = '0' + v[i] / 10 % 10;
*out++ = '0' + v[i] % 10;
if (i < 2) *out++ = '-';
else if (i == 2) *out++ = ' ';
else if (i < (sec ? 5 : 4)) *out++ = ':';
}
*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)
{
u16 y, m, d, hh = 0, mm = 0, ss = 0, i;
u32 days;
y = date_field(&s, 4, 2000, 2099);
if (*s++ != '-') error(E_FUNC);
m = date_field(&s, 2, 1, 12);
if (*s++ != '-') error(E_FUNC);
d = date_field(&s, 2, 1, month_len(y, m));
if (*s) {
if (*s++ != ' ') error(E_FUNC);
hh = date_field(&s, 2, 0, 23);
if (*s++ != ':') error(E_FUNC);
mm = date_field(&s, 2, 0, 59);
if (*s) {
if (*s++ != ':') error(E_FUNC);
ss = date_field(&s, 2, 0, 59);
}
if (*s) error(E_FUNC);
}
days = d - 1;
for (i = 2000; i < y; i++) days += 365 + leap(i);
for (i = 1; i < m; i++) days += month_len(y, i);
clk_ms = millis();
clk_sec = days * 86400UL + hh * 3600UL + mm * 60 + ss;
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;
for (; *p >= '0' && *p <= '9'; p++, any = 1)
if (nd < 9) { m = m * 10 + (*p - '0'); if (m) nd++; } else e++;
if (*p == '.')
for (p++; *p >= '0' && *p <= '9'; p++, any = 1)
if (nd < 9) { m = m * 10 + (*p - '0'); if (m) nd++; 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);
}
/* 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[7];
i32 n;
i16 e = 0;
i16 i, last;
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) {
for (i = 0; n || !i; i++, n /= 10) d[i] = '0' + n % 10;
while (i) *out++ = d[--i];
*out = 0;
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;
for (i = 5; i >= 0; i--) { d[i] = '0' + n % 10; n /= 10; }
for (last = 5; last > 0 && d[last] == '0'; last--);
if (e >= 0 && e < 6) {
for (i = 0; i <= e; i++) *out++ = d[i];
if (last > e) {
*out++ = '.';
for (; i <= last; i++) *out++ = d[i];
}
} else if (e < 0 && e >= -3) {
*out++ = '.';
for (i = -1; i > e; i--) *out++ = '0';
for (i = 0; i <= last; i++) *out++ = d[i];
} else {
*out++ = d[0];
if (last > 0) {
*out++ = '.';
for (i = 1; i <= last; i++) *out++ = d[i];
}
*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 + 5;
const char *k;
u8 *p = ln + 3;
u16 v = line_no(ln);
*q = 0;
do { *--q = '0' + v % 10; v /= 10; } while (v);
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;
}
static float *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) { /* undeclared: dimension 10 (0..10) */
u16 n = two ? 11 * 11 : 11;
u8 *np = arr_low - n * sizeof(float);
if (np <= prog_end + 1) error(E_MEMORY);
arr_low = np;
ar->p = (float *)np;
ar->d1 = 10;
ar->d2 = two ? 10 : 0;
memset(np, 0, n * sizeof(float));
}
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 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 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(')');
if ((u16)x >= 320 || (u16)y >= 240) 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((u16)(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, svars[c - 'A']);
tp += 2;
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;
}
/* Read a line with echo and simple editing; returns 0 on Ctrl-C. */
static u8 read_line(void)
{
u8 n = 0, c;
for (;;) {
c = getkey();
if (c == '\r' || c == '\n') { newline(); linebuf[n] = 0; return 1; }
if (c == 3) { puts_("^C"); newline(); return 0; }
if (c == 27) { /* drop cursor-key escape sequences */
c = getkey();
if (c == '[' || c == 'O')
do c = getkey(); while (c < 0x40 || c > 0x7E);
continue;
}
if (c == 8 || c == 127) {
if (n) { n--; putch('\b'); putch(' '); putch('\b'); }
} else if (c == 21) { /* Ctrl-U */
while (n) { n--; putch('\b'); putch(' '); putch('\b'); }
} else if (c >= ' ' && c < 127 && n < 250) {
linebuf[n++] = c;
putch(c);
}
}
}
/* ------------------------------------------------------------ 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 = svars[c - 'A'];
tp += 2;
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 = svars[c - 'A'];
tp += 2;
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);
tp += 2;
if (strlen(linebuf) >= STRMAX) linebuf[STRMAX - 1] = 0;
strcpy(svars[v - 'A'], 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, n;
u8 *np;
if (a >= 26) error(E_SYNTAX);
tp++;
expect('(');
d1 = to_int(expr());
if (accept(',')) d2 = to_int(expr());
expect(')');
n = (d1 + 1) * (d2 + 1);
if ((i16)d1 < 0 || (i16)d2 < 0 || n > 6000) error(E_SUBSCRIPT);
np = arr_low - n * sizeof(float);
if (np <= prog_end + 1) error(E_MEMORY);
arr_low = np;
memset(np, 0, n * sizeof(float));
arrays[a].p = (float *)np;
arrays[a].d1 = d1;
arrays[a].d2 = 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 >= 240 || x2 < 0 || x1 > 319) return;
if (x1 < 0) x1 = 0;
if (x2 > 319) x2 = 319;
g_at(x1, y);
for (; x1 <= x2; x1++) g_put(c);
}
static void pset(i16 x, i16 y, u8 c)
{
if ((u16)x < 320 && (u16)y < 240) { 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;
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(0);
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 > 239) y2 = 239;
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] > 30 || a[1] < 1 || a[1] > 80) 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(','));
}
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();
}
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: {
u16 a = (u16)(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();
running = 0; curln = 0; tp = (u8 *)"";
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_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(); running = 0; curln = 0; tp = (u8 *)""; 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:
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;
}
#ifdef __SDCC
void main(void)
#else
int main(void)
#endif
{
u16 n;
u8 *p;
new_prog();
g_clear(0);
newline();
puts_("DARTMOUTH-STYLE BASIC Z-80 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;
}
}