BASIC: RENUM [start[,step]] renumbers lines and their references

Fixes the numbers after GOTO, GOSUB, THEN, RUN and ON ... GOTO/GOSUB;
missing targets, quotes, REM and DATA are left alone. The new program is
built above the old one and copied down at the end, so a step of 0,
numbers past 65535, an over-long line or lack of memory change nothing.

To make room without giving up --opt-code-speed: one decimal formatter
(fmt_ul) shared by LIST, RENUM and number printing; fmt_num's output
branches merged (same text for ~2M test values); parse_num reads the
whole part and decimals in one loop. Works around an SDCC 4.5 bug that
turned a 0-trip loop into a 256-trip djnz. Adds basic/test-renum.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
brad ArantandClaude Opus 5.5 committed 2026-11-30 13:24:56 -08:00
1 parent c553824df0
commit 8f098b5502
7 files changed
+10302 -10089

No files matched your search

BIN
View File
Binary file not shown.
+116 -39
View File
@@ -25,6 +25,7 @@
typedef uint8_t u8;
typedef uint16_t u16;
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef uint32_t u32;
@@ -207,7 +208,7 @@ enum {
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_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_LAST
T_CHRS, T_STRS, T_LEFTS, T_RIGHTS, T_MIDS, T_DATES, T_TIM, T_POINT, T_LE, T_GE, T_NE, T_RENUM, T_LAST
};
static const char *const kw[] = {
@@ -217,7 +218,7 @@ static const char *const kw[] = {
"BYE", "CLS", "COLOR", "PLOT", "LINE", "RECT", "FILL", "CIRCLE", "LOCATE", "INK",
"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", "<=", ">=", "<>"
"CHR$", "STR$", "LEFT$", "RIGHT$", "MID$", "DATE$", "TIM", "POINT", "<=", ">=", "<>", "RENUM"
};
/* ----------------------------------------------------------------- memory */
@@ -430,13 +431,15 @@ static float parse_num(u8 **pp)
u8 *p = *pp;
i32 m = 0;
i16 e = 0, ex = 0;
u8 nd = 0, any = 0, eneg = 0;
u8 nd = 0, any = 0, eneg = 0, dot = 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--; }
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++; }
@@ -451,25 +454,29 @@ static float parse_num(u8 **pp)
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[7];
char d[8];
i32 n;
i16 e = 0;
i16 i, last;
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) {
for (i = 0; n || !i; i++, n /= 10) d[i] = '0' + n % 10;
while (i) *out++ = d[--i];
*out = 0;
return;
}
if ((float)n == v) { fmt_ul(n, out); return; }
}
if (v >= 10)
for (k = 6; k-- > 0;)
@@ -480,25 +487,22 @@ static void fmt_num(float v, char *out)
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; }
fmt_ul(n, d); /* six digits */
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) {
/* 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 (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];
}
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;
@@ -550,12 +554,10 @@ static void tokenize(const char *s, u8 *out)
/* 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;
char b[6], *q = b;
const char *k;
u8 *p = ln + 3;
u16 v = line_no(ln);
*q = 0;
do { *--q = '0' + v % 10; v /= 10; } while (v);
fmt_ul(line_no(ln), b);
while (*q) out(*q++);
out(' ');
for (; *p; p++) {
@@ -2145,6 +2147,80 @@ static void st_del(void)
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)
@@ -2218,7 +2294,7 @@ static void statement(void)
case T_LOAD:
close_all();
fs_load();
running = 0; curln = 0; tp = (u8 *)"";
to_ready();
break;
case T_SAVE: st_save(); break;
case T_DIR: st_dir(); break;
@@ -2247,7 +2323,8 @@ static void statement(void)
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_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; }
+10047 -10047
View File
File diff suppressed because it is too large. Load diff
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Try BASIC's RENUM in tools/z80emu.py, with the screen kept by pyte.
python3 test-renum.py
Also checks number printing and reading, which were rewritten to make room.
"""
import importlib.util
import os
import sys
import functools
print = functools.partial(print, flush=True)
HERE = os.path.dirname(os.path.abspath(__file__))
spec = importlib.util.spec_from_file_location("te", os.path.join(HERE, "test-edit.py"))
te = importlib.util.module_from_spec(spec)
spec.loader.exec_module(te)
CR = te.CR
def main():
b = te.Basic()
errors = 0
def check(what, ok, got=None):
nonlocal errors
print(("PASS " if ok else "FAIL ") + what)
if not ok and got is not None:
print(" got: " + repr(got))
errors += not ok
def screen():
return "\n".join(l.rstrip() for l in b.screen_text().display)
def cmd(text):
"""Type a command and return what it printed."""
b.type(b"CLS" + CR)
b.type(text.encode() + CR)
out = screen().split(text, 1)[-1]
return out.replace("\nREADY", "").strip()
def load(prog):
b.type(b"NEW" + CR)
for line in prog.strip().splitlines():
b.type(line.strip().encode() + CR)
def listing():
return [l for l in cmd("LIST").splitlines() if l]
b.type(b"")
load('''
5 REM GOTO 5 STAYS AS TYPED
7 GOSUB 200
12 IF X < 3 THEN 7
13 IF X = 3 GOTO 40
40 ON X - 2 GOTO 41, 13, 999
41 PRINT "GOTO 12"; X: END
200 X = X + 1: RETURN
300 END
''')
before = cmd("RUN")
cmd("RENUM")
check("RENUM numbers from 10 in steps of 10, fixing GOTO, GOSUB, THEN and ON",
listing() == ['10 REM GOTO 5 STAYS AS TYPED',
'20 GOSUB 70',
'30 IF X < 3 THEN 20',
'40 IF X = 3 GOTO 50',
'50 ON X - 2 GOTO 60, 40, 999',
'60 PRINT "GOTO 12"; X: END',
'70 X = X + 1: RETURN',
'80 END'], listing())
check("a reference to a missing line is left alone", "GOTO 60, 40, 999" in "\n".join(listing()))
check("the program runs the same afterwards", cmd("RUN") == before and before == "GOTO 12 3", before)
cmd("RENUM 1000, 5")
l = listing()
check("RENUM start, step", l[0].startswith("1000 ") and l[-1] == "1035 END" and
"1010 IF X < 3 THEN 1005" in l and "1020 ON X - 2 GOTO 1025, 1015, 999" in l, l)
cmd("RENUM 1, 1")
l = listing()
check("line numbers can get shorter", "3 IF X < 3 THEN 2" in l and "5 ON X - 2 GOTO 6, 4, 999" in l, l)
check("still runs", cmd("RUN") == "GOTO 12 3")
load('''
1 GOTO 2
2 RUN 3
3 GOSUB 1
''')
cmd("RENUM 10000, 10000")
check("RUN n is renumbered too", listing() == ["10000 GOTO 20000", "20000 RUN 30000", "30000 GOSUB 10000"], listing())
out = cmd("RENUM 60000, 3000")
check("numbers past 65535 are refused", "ERROR" in out.upper() or "ILLEGAL" in out.upper(), out)
check("and the program is unchanged", listing() == ["10000 GOTO 20000", "20000 RUN 30000", "30000 GOSUB 10000"], listing())
out = cmd("RENUM 10, 0")
check("step 0 is refused", listing()[0].startswith("10000"), out)
load("10 PRINT 1\n20 GOTO 10")
load("")
check("RENUM on an empty program is fine", cmd("RENUM") == "" and listing() == [])
# a line that would grow past 255 bytes
refs = ",".join(["1"] * 115) # typed lines stop at 250 characters
load("1 ON X GOTO " + refs)
out = cmd("RENUM 10000")
check("a line that would grow too long is refused", "LONG" in out.upper(), out)
check("and is left as it was", ("1 ON X GOTO " + refs) in cmd("LIST").replace("\n", ""))
# number printing and reading (rewritten to make room); the screen wraps
# at 80 columns, so compare the words only
def nums(text):
b.type(b"CLS" + CR)
b.type(text.encode() + CR)
return " ".join("".join(b.screen_text().display).split()).split(text, 1)[-1].replace("READY", "").strip()
out = nums('PRINT 0; 1; -1; .5; 1/3; .001; .0001; 123.456; 999999; 1000000; 1E30; -2.5E-12; 65535; 12345678')
check("numbers print as before",
out == "0 1 -1 .5 .333333 .001 1E-04 123.456 999999 1E+06 1E+30 -2.5E-12 65535 1.23457E+07", out)
out = nums("PRINT 1.5E3; 12.5E-1; 1234567890123; .000123; 3.; 00042.50")
check("numbers are read as before", out == "1500 1.25 1.23457E+12 1.23E-04 3 42.5", out)
sys.exit(1 if errors else 0)
if __name__ == "__main__":
main()