-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbasic.c
More file actions
10780 lines (10311 loc) · 350 KB
/
basic.c
File metadata and controls
10780 lines (10311 loc) · 350 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* _____ ____ __ __ ____ _____ _____ _____
* / ____| _ \| \/ | | _ \ /\ / ____|_ _/ ____|
* | | | |_) | \ / |______| |_) | / \ | (___ | || |
* | | | _ <| |\/| |______| _ < / /\ \ \___ \ | || |
* | |____| |_) | | | | | |_) / ____ \ ____) |_| || |____
* \_____|____/|_| |_| |____/_/ \_\_____/|_____\_____|
* .............................................................
*
* [Version 0.1.0]
*
* BASIC interpreter targeting CBM BASIC v2 style programs.
* Copyright (C) 2024 Davepl with various AI assists
*
* Based on the original by David Plummer:
* https://github.com/davepl/pdpsrc/tree/main/bsd/basic
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* BASIC banner: implements a minimal 6502 Microsoft/CBM BASIC v2 compatible
* interpreter (PRINT, INPUT, IF/THEN, FOR/NEXT, GOTO, GOSUB, DIM, etc.).
*/
#if (defined(__unix__) || defined(__linux__) || defined(__APPLE__) || defined(__MACH__)) && !defined(_POSIX_C_SOURCE) && !defined(_GNU_SOURCE)
#define _POSIX_C_SOURCE 200809L
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <stdint.h>
#include "petscii.h"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/em_js.h>
#endif
/* Last HTTP response status from HTTP$ (set on Emscripten; 0 otherwise). */
static int http_last_status;
#ifdef __EMSCRIPTEN__
/*
* Async fetch for HTTP$ (EM_ASYNC_JS → Asyncify.handleAsync; no manual ASYNCIFY_IMPORTS).
* Writes response body into out; sets *status_out to HTTP status (0 on network error).
*/
EM_ASYNC_JS(int, wasm_js_http_fetch_async, (const char *url, const char *method, const char *body, int body_len, char *out, int out_cap, int *status_out), {
var urlJs = UTF8ToString(url);
var methodJs = method ? UTF8ToString(method) : "GET";
var init = { method: methodJs };
if (body && body_len > 0) {
init.body = HEAPU8.subarray(body, body + body_len >>> 0);
}
try {
const resp = await fetch(urlJs, init);
HEAP32[status_out >> 2] = resp.status;
const text = await resp.text();
stringToUTF8(text, out, out_cap);
} catch (e) {
HEAP32[status_out >> 2] = 0;
if (out_cap > 0) HEAPU8[out] = 0;
}
return 0;
});
static void wasm_http_fetch_emscripten(const char *url, const char *method, const char *body, int body_len,
char *out, size_t out_size, int *status_out)
{
const char *m = (method && method[0]) ? method : "GET";
if (out_size == 0) {
return;
}
out[0] = '\0';
if (status_out) {
*status_out = 0;
}
if (!url || !url[0] || !status_out) {
return;
}
wasm_js_http_fetch_async(url, m, body, body_len, out, (int)out_size, status_out);
}
#endif
#ifdef GFX_VIDEO
#include "gfx_video.h"
#include "gfx_charrom.h"
#include "gfx_gamepad.h"
#include "basic_api.h"
#if defined(__EMSCRIPTEN__)
#include "gfx_canvas.h"
#include "gfx_software_sprites.h"
#endif
/* Video state pointer; must precede __EMSCRIPTEN__ key helpers that reference gfx_vs. */
static GfxVideoState *gfx_vs = NULL;
/* Virtual POKE/PEEK bases for gfx builds (defaults: C64-style). #OPTION memory / screen / … */
static uint16_t gfx_mem_base_text = GFX_TEXT_BASE;
static uint16_t gfx_mem_base_color = GFX_COLOR_BASE;
static uint16_t gfx_mem_base_char = GFX_CHAR_BASE;
static uint16_t gfx_mem_base_key = GFX_KEY_BASE;
static uint16_t gfx_mem_base_bitmap = GFX_BITMAP_BASE;
/* Baseline after CLI parsing; restored at each load so #OPTION starts from CLI layout. */
static uint16_t gfx_mem_init_text = GFX_TEXT_BASE;
static uint16_t gfx_mem_init_color = GFX_COLOR_BASE;
static uint16_t gfx_mem_init_char = GFX_CHAR_BASE;
static uint16_t gfx_mem_init_key = GFX_KEY_BASE;
static uint16_t gfx_mem_init_bitmap = GFX_BITMAP_BASE;
static void gfx_mem_bases_restore_from_init(void)
{
gfx_mem_base_text = gfx_mem_init_text;
gfx_mem_base_color = gfx_mem_init_color;
gfx_mem_base_char = gfx_mem_init_char;
gfx_mem_base_key = gfx_mem_init_key;
gfx_mem_base_bitmap = gfx_mem_init_bitmap;
}
static int gfx_mem_bases_apply_to_video(void)
{
if (!gfx_vs) {
return 0;
}
return gfx_video_set_memory_bases(gfx_vs,
gfx_mem_base_text, gfx_mem_base_color, gfx_mem_base_char,
gfx_mem_base_key, gfx_mem_base_bitmap);
}
static void gfx_mem_bases_copy_to_state(GfxVideoState *s)
{
s->mem_text = gfx_mem_base_text;
s->mem_color = gfx_mem_base_color;
s->mem_char = gfx_mem_base_char;
s->mem_key = gfx_mem_base_key;
s->mem_bitmap = gfx_mem_base_bitmap;
}
/* Parse 1024, $400, or 0x400 into 16-bit address. */
static int parse_gfx_addr_u16(const char *value, uint16_t *out)
{
char *end;
unsigned long v;
const char *p;
if (!value || !value[0] || !out) return -1;
p = value;
if (p[0] == '$') {
p++;
v = strtoul(p, &end, 16);
} else {
v = strtoul(p, &end, 0);
}
if (end == p || *end != '\0' || v > 0xFFFFul) return -1;
*out = (uint16_t)v;
return 0;
}
static int gfx_mem_try_preset(const char *value)
{
GfxVideoState tmp;
gfx_video_init(&tmp);
gfx_mem_bases_copy_to_state(&tmp);
if (gfx_video_apply_memory_preset(&tmp, value) != 0) {
return -1;
}
gfx_mem_base_text = tmp.mem_text;
gfx_mem_base_color = tmp.mem_color;
gfx_mem_base_char = tmp.mem_char;
gfx_mem_base_key = tmp.mem_key;
gfx_mem_base_bitmap = tmp.mem_bitmap;
if (gfx_vs) {
return gfx_mem_bases_apply_to_video();
}
return 0;
}
static int gfx_mem_try_set_region(GfxMemRegion region, uint32_t base)
{
GfxVideoState tmp;
gfx_video_init(&tmp);
gfx_mem_bases_copy_to_state(&tmp);
if (gfx_video_set_memory_base(&tmp, region, base) != 0) {
return -1;
}
gfx_mem_base_text = tmp.mem_text;
gfx_mem_base_color = tmp.mem_color;
gfx_mem_base_char = tmp.mem_char;
gfx_mem_base_key = tmp.mem_key;
gfx_mem_base_bitmap = tmp.mem_bitmap;
if (gfx_vs) {
return gfx_mem_bases_apply_to_video();
}
return 0;
}
static void gfx_mem_snapshot_init(void)
{
gfx_mem_init_text = gfx_mem_base_text;
gfx_mem_init_color = gfx_mem_base_color;
gfx_mem_init_char = gfx_mem_base_char;
gfx_mem_init_key = gfx_mem_base_key;
gfx_mem_init_bitmap = gfx_mem_base_bitmap;
}
#if defined(__EMSCRIPTEN__) && defined(GFX_VIDEO)
/* Canvas WASM: TI/TI$ from high-res clock (tight GOTO loops have no SLEEP). */
static double wasm_gfx_ti_epoch_ms;
/* Canvas WASM: trek.bas-style lines pack many ':' statements; yield inside long PRINT too. */
static unsigned wasm_gfx_put_budget;
/* Yield every few execute_statement calls — LET/GOTO/IF on one line skip gfx_put_byte. */
static unsigned wasm_gfx_stmt_exec_budget;
/* Trek SRS: thousands of MID$/LEFT$/RIGHT$ per PRINT — yield every N builtin calls. */
static unsigned wasm_str_builtin_budget;
/* Q$=LEFT$+A$+RIGHT$ (eval_addsub): separate budget so FOR/NEXT tests are not slowed. */
static unsigned wasm_str_concat_budget;
#endif
#endif
#if defined(__EMSCRIPTEN__)
/* Browser: no termios, no Windows API */
#elif defined(_WIN32)
#include <windows.h>
#include <conio.h>
#else
#if defined(__unix__) || defined(__APPLE__) || defined(__MACH__)
#include <unistd.h>
#include <termios.h>
#endif
#ifndef HAVE_USLEEP
#include <sys/types.h>
#include <sys/times.h>
#include <sys/param.h>
#include <sys/time.h>
#endif
#ifndef HAVE_USLEEP
#if defined(__APPLE__) || defined(__MACH__) || defined(__linux__) || defined(_POSIX_VERSION)
#define HAVE_USLEEP 1
#endif
#endif
#endif
/* Helper structures for token expansion inside BASIC strings
* (e.g., translating {RED} to CHR$(28) at source level).
*/
typedef struct {
char *buf;
size_t len;
size_t cap;
} StrBuf;
typedef struct {
const char *name;
int code;
} TokenMap;
static int is_ident_char(int c)
{
return isalpha((unsigned char)c) || isdigit((unsigned char)c) || c == '$' || c == '_';
}
/* Token map: C64 control/color codes. See docs/c64-color-codes.md for reference.
* Multiple names may map to the same code (case-insensitive). */
static const TokenMap token_map[] = {
/* Colors (full names) */
{"WHITE", 5},
{"RED", 28},
{"CYAN", 159},
{"PURPLE", 156},
{"GREEN", 30},
{"BLUE", 31},
{"YELLOW", 158},
{"ORANGE", 129},
{"BROWN", 149},
{"PINK", 150},
{"BLACK", 144},
/* Colors (abbreviations) */
{"WHT", 5},
{"BLK", 144},
{"CYN", 159},
{"PUR", 156},
{"GRN", 30},
{"BLU", 31},
{"YEL", 158},
/* Greys */
{"GRAY1", 151},
{"GREY1", 151},
{"DARKGREY", 151},
{"DARKGRAY", 151},
{"GRAY2", 152},
{"GREY2", 152},
{"GREY", 152},
{"GRAY", 152},
{"GRAY3", 155},
{"GREY3", 155},
{"LIGHTGREY", 155},
{"LIGHTGRAY", 155},
{"LIGHTGREEN", 153},
{"LIGHT GREEN", 153},
{"LIGHTBLUE", 154},
{"LIGHT BLUE", 154},
{"LIGHT-RED", 150},
/* Screen/control */
{"HOME", 19},
{"DOWN", 17},
{"UP", 145},
{"LEFT", 157},
{"RIGHT", 29},
{"DEL", 20},
{"DELETE", 20},
{"INS", 148},
{"INST", 148},
{"INSERT", 148},
{"CLR", 147},
{"CLEAR", 147},
{"SPACE", 32},
{"RETURN", 13},
{"SHIFT RETURN", 141},
/* Cursor variants */
{"CURSOR UP", 145},
{"CURSOR DOWN", 17},
{"CURSOR LEFT", 157},
{"CURSOR RIGHT", 29},
{"CRSR UP", 145},
{"CRSR DOWN", 17},
{"CRSR LEFT", 157},
{"CRSR RIGHT", 29},
/* Reverse video */
{"RVS", 18},
{"RVS ON", 18},
{"RVSON", 18},
{"REVERSE ON", 18},
{"RVS OFF", 146},
{"RVSOFF", 146},
{"REVERSE OFF", 146},
/* Function keys */
{"F1", 133},
{"F2", 137},
{"F3", 134},
{"F4", 138},
{"F5", 135},
{"F6", 139},
{"F7", 136},
{"F8", 140},
/* Symbol */
{"PI", 126},
/* ANSI reset (terminal only): resets colors/attributes to default. No C64 equivalent. */
{"RESET", 256},
{"DEFAULT", 256},
{NULL, 0}
};
/* PETSCII/ANSI mode (set by -petscii, #OPTION); declared early for gfx_put_byte. */
static int petscii_mode = 0;
static void sb_init(StrBuf *sb)
{
sb->cap = 256;
sb->len = 0;
sb->buf = (char *)malloc(sb->cap);
if (!sb->buf) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
sb->buf[0] = '\0';
}
static void sb_reserve(StrBuf *sb, size_t extra)
{
if (sb->len + extra + 1 <= sb->cap) {
return;
}
while (sb->len + extra + 1 > sb->cap) {
sb->cap *= 2;
}
{
char *newbuf = (char *)realloc(sb->buf, sb->cap);
if (!newbuf) {
free(sb->buf);
fprintf(stderr, "Out of memory\n");
exit(1);
}
sb->buf = newbuf;
}
}
static void sb_append_char(StrBuf *sb, char c)
{
sb_reserve(sb, 1);
sb->buf[sb->len++] = c;
sb->buf[sb->len] = '\0';
}
static void sb_append_mem(StrBuf *sb, const char *s, size_t n)
{
sb_reserve(sb, n);
memcpy(sb->buf + sb->len, s, n);
sb->len += n;
sb->buf[sb->len] = '\0';
}
static void sb_append_str(StrBuf *sb, const char *s)
{
sb_append_mem(sb, s, strlen(s));
}
static char *dup_upper_trim(const char *src, size_t len)
{
char *out;
size_t i;
while (len > 0 && isspace((unsigned char)*src)) {
src++;
len--;
}
while (len > 0 && isspace((unsigned char)src[len - 1])) {
len--;
}
out = (char *)malloc(len + 1);
if (!out) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
for (i = 0; i < len; i++) {
out[i] = (char)toupper((unsigned char)src[i]);
}
out[len] = '\0';
return out;
}
static int lookup_token_code(const char *token, int *code_out)
{
char *endptr = NULL;
long n;
/* Decimal: {147} */
n = strtol(token, &endptr, 10);
if (*token != '\0' && *endptr == '\0') {
if (n >= 0 && n <= 255) {
*code_out = (int)n;
return 1;
}
return 0;
}
/* Hex: {$93} or {0x93} */
if (*token == '$') {
n = strtol(token + 1, &endptr, 16);
if (endptr && *endptr == '\0' && n >= 0 && n <= 255) {
*code_out = (int)n;
return 1;
}
}
if ((token[0] == '0' && (token[1] == 'x' || token[1] == 'X'))) {
n = strtol(token + 2, &endptr, 16);
if (endptr && *endptr == '\0' && n >= 0 && n <= 255) {
*code_out = (int)n;
return 1;
}
}
/* Binary: {%10010011} */
if (*token == '%') {
n = strtol(token + 1, &endptr, 2);
if (endptr && *endptr == '\0' && n >= 0 && n <= 255) {
*code_out = (int)n;
return 1;
}
}
{
int i;
for (i = 0; token_map[i].name != NULL; i++) {
if (strcmp(token, token_map[i].name) == 0) {
*code_out = token_map[i].code;
return 1;
}
}
}
return 0;
}
static void append_quoted(StrBuf *out, const char *text, size_t len)
{
sb_append_char(out, '\"');
sb_append_mem(out, text, len);
sb_append_char(out, '\"');
}
/* Transform a BASIC source line so that tokens inside quoted strings of the form
* "HELLO {RED}WORLD"
* are expanded to:
* "HELLO ";CHR$(28);"WORLD"
* Tokens map either to explicit numeric CHR$ codes or to named PETSCII
* control/color names in token_map[].
*/
static char *transform_basic_line(const char *input)
{
StrBuf out;
int in_string = 0;
const char *segment_start = NULL;
int piece_count = 0;
size_t i;
sb_init(&out);
for (i = 0; input[i] != '\0'; i++) {
char c = input[i];
if (!in_string) {
if (c == '\"') {
in_string = 1;
segment_start = input + i + 1;
piece_count = 0;
} else {
sb_append_char(&out, c);
}
continue;
}
if (c == '{') {
size_t j = i + 1;
while (input[j] != '\0' && input[j] != '}') {
j++;
}
if (input[j] == '}') {
char *token = dup_upper_trim(input + i + 1, j - (i + 1));
int code = 0;
if (lookup_token_code(token, &code)) {
size_t seg_len = (size_t)((input + i) - segment_start);
if (seg_len > 0) {
if (piece_count > 0) {
sb_append_char(&out, '+');
}
append_quoted(&out, segment_start, seg_len);
piece_count++;
}
if (piece_count > 0) {
sb_append_char(&out, '+');
}
if (code == 256) {
/* ANSI reset: ESC [ 0 m — resets terminal to default colors/attributes */
sb_append_str(&out, "CHR$(27)+\"[0m\"");
} else {
char tmp[32];
sprintf(tmp, "CHR$(%d)", code);
sb_append_str(&out, tmp);
}
piece_count++;
segment_start = input + j + 1;
i = j;
free(token);
continue;
}
free(token);
}
continue;
}
if (c == '\"') {
size_t seg_len = (size_t)((input + i) - segment_start);
if (seg_len > 0 || piece_count == 0) {
if (piece_count > 0) {
sb_append_char(&out, '+');
}
append_quoted(&out, segment_start, seg_len);
}
in_string = 0;
segment_start = NULL;
piece_count = 0;
continue;
}
}
if (in_string) {
sb_append_char(&out, '\"');
if (segment_start) {
sb_append_str(&out, segment_start);
}
}
return out.buf;
}
/* Normalize certain keywords in a BASIC source line to restore
* CBM-style whitespace that may have been stripped, e.g.:
* IFB3<1THENIFE>10ORD(7)=0THEN GOTO 890
* becomes:
* IF B3<1 THEN IF E>10 OR D(7)=0 THEN GOTO 890
* The transformation is applied only outside of quoted strings.
*/
static char *normalize_keywords_line(const char *input)
{
StrBuf out;
int in_string = 0;
size_t i = 0;
sb_init(&out);
while (input[i] != '\0') {
char c = input[i];
if (c == '\"') {
in_string = !in_string;
sb_append_char(&out, c);
i++;
continue;
}
if (!in_string) {
char c1 = (char)toupper((unsigned char)c);
char c2 = (char)toupper((unsigned char)input[i + 1]);
char c3 = (char)toupper((unsigned char)input[i + 2]);
char c4 = (char)toupper((unsigned char)input[i + 3]);
/* IF followed immediately by identifier/digit without space */
/* Do not split JIFFIES_*, DIFF*, etc. — same prev_ident guard as FOR (PLATFORM). */
if (c1 == 'I' && c2 == 'F') {
char next = input[i + 2];
int prev_ident = (i > 0 && (isalnum((unsigned char)input[i - 1]) || input[i - 1] == '$' || input[i - 1] == '_'));
if (!prev_ident && next != '\0' && !isspace((unsigned char)next) && next != ':' ) {
/* Insert space before IF if needed */
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != ':' && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "IF");
i += 2;
/* Ensure space after IF */
sb_append_char(&out, ' ');
continue;
}
}
/* FOR followed immediately by identifier/digit: FORI=1TO9 -> FOR I=1TO9 */
/* Do not split PLATFORM, BEFORE, etc. — only when FOR is a whole word. */
if (c1 == 'F' && c2 == 'O' && c3 == 'R') {
char next = input[i + 3];
int prev_ident = (i > 0 && (isalnum((unsigned char)input[i-1]) || input[i-1] == '$' || input[i-1] == '_'));
if (!prev_ident && next != '\0' && !isspace((unsigned char)next) && next != ':' ) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != ':' && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "FOR");
i += 3;
sb_append_char(&out, ' ');
continue;
}
}
/* GOTO followed immediately by digit: GOTO410 -> GOTO 410 */
if (c1 == 'G' && c2 == 'O' && c3 == 'T' && (char)toupper((unsigned char)input[i + 3]) == 'O') {
char next = input[i + 4];
if (next != '\0' && !isspace((unsigned char)next) && next != ':' ) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != ':' && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "GOTO");
i += 4;
sb_append_char(&out, ' ');
continue;
}
}
/* GOSUB followed immediately by digit: GOSUB410 -> GOSUB 410 */
if (c1 == 'G' && c2 == 'O' && c3 == 'S' && c4 == 'U' &&
(char)toupper((unsigned char)input[i + 4]) == 'B') {
char next = input[i + 5];
if (next != '\0' && !isspace((unsigned char)next) && next != ':' ) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != ':' && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "GOSUB");
i += 5;
sb_append_char(&out, ' ');
continue;
}
}
/* NEXT followed immediately by identifier: NEXTI -> NEXT I */
if (c1 == 'N' && c2 == 'E' && c3 == 'X' && c4 == 'T') {
char next = input[i + 4];
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != ':' && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "NEXT");
i += 4;
if (next != '\0' && !isspace((unsigned char)next) && next != ':' ) {
sb_append_char(&out, ' ');
}
continue;
}
/* THEN */
if (c1 == 'T' && c2 == 'H' && c3 == 'E' && c4 == 'N') {
/* Insert space before THEN if needed */
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != ':' && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "THEN");
i += 4;
/* Skip any existing spaces after THEN */
while (isspace((unsigned char)input[i])) {
i++;
}
/* Ensure one space after THEN if next char is non-separator */
if (input[i] != '\0' && input[i] != ':' && !isspace((unsigned char)input[i])) {
sb_append_char(&out, ' ');
}
continue;
}
/* TO inside numeric ranges: 1TO9 -> 1 TO 9, but never split GOTO. */
if (c1 == 'T' && c2 == 'O') {
size_t j;
char prev_ns = ' ';
char next_ns = '\0';
/* Skip if this is the TO in GOTO (e.g. ...GOTO 100). */
if (i >= 2) {
char g = (char)toupper((unsigned char)input[i - 2]);
char o = (char)toupper((unsigned char)input[i - 1]);
if (g == 'G' && o == 'O') {
/* fall through to normal character handling */
} else {
/* Find previous non-space character. */
j = i;
while (j > 0) {
j--;
if (!isspace((unsigned char)input[j])) {
prev_ns = input[j];
break;
}
}
/* Find next non-space character after TO. */
j = i + 2;
while (input[j] != '\0' && isspace((unsigned char)input[j])) {
j++;
}
next_ns = input[j];
/* Treat as TO only when between numeric-ish tokens, like 1TO9. */
if ((isdigit((unsigned char)prev_ns) || prev_ns == ')') &&
(isdigit((unsigned char)next_ns) || next_ns == '+' || next_ns == '-')) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "TO");
i += 2;
if (next_ns != '\0' && !isspace((unsigned char)next_ns) &&
next_ns != ':' && next_ns != ')') {
sb_append_char(&out, ' ');
}
continue;
}
}
}
}
/* AND / OR infix operators without spaces.
* Only treat as operators when they are not embedded in identifiers
* (e.g., avoid splitting FOR into F OR, or ORD into OR D).
*/
if (c1 == 'A' && c2 == 'N' && c3 == 'D') {
char prev_in = (i > 0) ? input[i - 1] : ' ';
char next_in = input[i + 3];
if (!is_ident_char(prev_in) && !is_ident_char(next_in)) {
/* Surround AND with spaces */
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "AND");
i += 3;
if (input[i] != '\0' && !isspace((unsigned char)input[i]) && input[i] != ')') {
sb_append_char(&out, ' ');
}
continue;
}
}
if (c1 == 'O' && c2 == 'R') {
char prev_in = (i > 0) ? input[i - 1] : ' ';
char next_in = (input[i + 2] != '\0') ? input[i + 2] : ' ';
if (!is_ident_char(prev_in) && !is_ident_char(next_in)) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "OR");
i += 2;
if (input[i] != '\0' && !isspace((unsigned char)input[i]) && input[i] != ')') {
sb_append_char(&out, ' ');
}
continue;
}
}
if (c1 == 'M' && c2 == 'O' && (input[i + 2] == 'D' || input[i + 2] == 'd')) {
char prev_in = (i > 0) ? input[i - 1] : ' ';
char next_in = (input[i + 3] != '\0') ? input[i + 3] : ' ';
if (!isalpha((unsigned char)prev_in) && !isalpha((unsigned char)next_in)) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "MOD");
i += 3;
if (input[i] != '\0' && !isspace((unsigned char)input[i]) && input[i] != ')') {
sb_append_char(&out, ' ');
}
continue;
}
}
if (c1 == 'X' && c2 == 'O' && (input[i + 2] == 'R' || input[i + 2] == 'r')) {
char prev_in = (i > 0) ? input[i - 1] : ' ';
char next_in = input[i + 3];
if (!is_ident_char(prev_in) && !is_ident_char(next_in)) {
if (out.len > 0) {
char prev = out.buf[out.len - 1];
if (!isspace((unsigned char)prev) && prev != '(') {
sb_append_char(&out, ' ');
}
}
sb_append_str(&out, "XOR");
i += 3;
if (input[i] != '\0' && !isspace((unsigned char)input[i]) && input[i] != ')') {
sb_append_char(&out, ' ');
}
continue;
}
}
}
sb_append_char(&out, c);
i++;
}
return out.buf;
}
/* Platform-specific handling for ANSI escape sequences.
* On Unix-like systems (macOS/Linux), standard ANSI escapes work in most terminals.
* On Windows, we enable virtual terminal processing where available so that
* ANSI color/control sequences render correctly instead of being printed literally. */
#if defined(__EMSCRIPTEN__) || defined(_WIN32)
#if defined(_WIN32)
static int ansi_enabled = 0;
#endif
static void init_console_ansi(void)
{
#if defined(__EMSCRIPTEN__)
/* Browser: no console mode to configure; stdout goes to Module.print */
#elif defined(_WIN32)
HANDLE hOut;
DWORD mode;
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hOut == INVALID_HANDLE_VALUE || hOut == NULL) {
return;
}
if (!GetConsoleMode(hOut, &mode)) {
return;
}
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(hOut, mode)) {
return;
}
ansi_enabled = 1;
#endif
}
#else
static void init_console_ansi(void)
{
/* Standard ANSI escapes are generally supported on macOS/Linux terminals. */
}
#endif
// DEFINES
#define MAX_LINES 65536 /* 64K; classic BASIC line-number range; trek.bas ~680 lines */
#define MAX_LINE_LEN 256
/* Source lines when loading from disk (UTF-8 PETSCII art can exceed 256 bytes). */
#define MAX_LINE_LEN_LOAD 65536
#define MAX_INCLUDE_DEPTH 16
#define MAX_INCLUDE_PATH 512
static char include_path_store[MAX_INCLUDE_DEPTH][MAX_INCLUDE_PATH];
#define MAX_VARS 128
#define VAR_NAME_MAX 32
#define MAX_GOSUB 64
#define MAX_FOR 32
#define MAX_STR_LEN 4096 /* default max; #OPTION maxstr N can reduce for C64 compatibility */
#define DEFAULT_ARRAY_SIZE 11
#define DEFAULT_PRINT_WIDTH 40
#ifndef TICKS_PER_SEC_FALLBACK
#ifdef HZ
#define TICKS_PER_SEC_FALLBACK HZ
#else
#define TICKS_PER_SEC_FALLBACK 60
#endif
#endif
enum value_type { VAL_NUM = 0, VAL_STR = 1 };
struct value {
int type;
double num;
char str[MAX_STR_LEN];
};
struct line {
int number;
char *text;
};
#define MAX_DIMS 3
struct var {
char name[VAR_NAME_MAX];
int is_string;
int is_array;
int dims; /* 0 for scalar, >=1 for arrays */
int dim_sizes[MAX_DIMS]; /* per-dimension sizes */
int size; /* total number of elements (product of dim_sizes) */
struct value scalar;
struct value *array; /* flat buffer of length size */
};
struct gosub_frame {
int line_index;
char *position;
};
struct for_frame {
char name[VAR_NAME_MAX];
int is_string;
double end_value;
double step;
int line_index;
char *resume_pos;
struct value *var;
/* GOSUB depth when this FOR was entered; RETURN unwinds FOR frames above the new depth (CBM-style). */
int gosub_depth_at_entry;
};
static struct line *program_lines[MAX_LINES];
static int line_count = 0;
static struct var vars[MAX_VARS];