/* * 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. * * 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 #include #include #include 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); } #else #include #include #include 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 bye(void) { 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); } #endif /* ----------------------------------------------------------------- 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_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_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, 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", "AND", "OR", "NOT", "SIN", "COS", "TAN", "ATN", "EXP", "LOG", "ABS", "SQR", "INT", "RND", "SGN", "FN", "TAB", "PEEK", "INP", "LEN", "VAL", "ASC", "CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "TIM", "POINT", "<=", ">=", "<>" }; /* ----------------------------------------------------------------- memory */ #define ARENA 23000 /* 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 void putch(char c) { if (c == '\n') { out_c('\r'); out_c('\n'); col = 0; return; } if (c == '\b') { if (col) col--; } else if ((u8)c >= ' ') col++; 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_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", "BREAK", "STOP" }; static u16 line_no(u8 *ln) { return ln[1] | (u16)ln[2] << 8; } static void error(u8 e) { if (col) newline(); if (e < E_BREAK) putch('?'); puts_(errmsg[e]); if (curln) { puts_(" IN "); put_u16(line_no(curln)); } newline(); longjmp(errjmp, 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; } static void list_line(u8 *ln) { u8 *p = ln + 3; put_u16(line_no(ln)); putch(' '); for (; *p; p++) { if (*p >= T_LET && *p < T_LAST) puts_(kw[*p - T_LET]); else putch(*p); } 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) 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_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++; 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 st_print(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; } static void st_input(void) { u8 *p; 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; } } 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: 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_RUN: 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: new_prog(); running = 0; curln = 0; tp = (u8 *)""; break; case T_BYE: bye(); break; case T_CLS: case T_COLOR: case T_PLOT: case T_LINE: 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) 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; } }