-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbasic.c
More file actions
5835 lines (5512 loc) · 177 KB
/
basic.c
File metadata and controls
5835 lines (5512 loc) · 177 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 "petscii.h"
#ifdef GFX_VIDEO
#include "gfx_video.h"
#endif
#if 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 == '_';
}
static const TokenMap token_map[] = {
{"WHITE", 5},
{"RED", 28},
{"CYAN", 159},
{"PURPLE", 156},
{"GREEN", 30},
{"BLUE", 31},
{"YELLOW", 158},
{"ORANGE", 129},
{"BROWN", 149},
{"PINK", 150},
{"GRAY1", 151},
{"GREY1", 151},
{"GRAY2", 152},
{"GREY2", 152},
{"LIGHTGREEN", 153},
{"LIGHT GREEN", 153},
{"LIGHTBLUE", 154},
{"LIGHT BLUE", 154},
{"GRAY3", 155},
{"GREY3", 155},
{"BLACK", 144},
{"HOME", 19},
{"DOWN", 17},
{"UP", 145},
{"LEFT", 157},
{"RIGHT", 29},
{"DEL", 20},
{"DELETE", 20},
{"INS", 148},
{"INSERT", 148},
{"CLR", 147},
{"CLEAR", 147},
{"RVS", 18},
{"REVERSE ON", 18},
{"RVS OFF", 146},
{"REVERSE OFF", 146},
{NULL, 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;
n = strtol(token, &endptr, 10);
if (*token != '\0' && *endptr == '\0') {
if (n >= 0 && n <= 255) {
*code_out = (int)n;
return 1;
}
return 0;
}
{
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, '+');
}
{
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 */
if (c1 == 'I' && c2 == 'F') {
char next = input[i + 2];
if (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 */
if (c1 == 'F' && c2 == 'O' && c3 == 'R') {
char next = input[i + 3];
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, "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];
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;
}
}
}
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(_WIN32)
static int ansi_enabled = 0;
static void init_console_ansi(void)
{
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;
}
#else
static void init_console_ansi(void)
{
/* Standard ANSI escapes are generally supported on macOS/Linux terminals. */
}
#endif
// DEFINES
#define MAX_LINES 1024
#define MAX_LINE_LEN 256
#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 256
#define DEFAULT_ARRAY_SIZE 11
#define 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;
};
static struct line *program_lines[MAX_LINES];
static int line_count = 0;
static struct var vars[MAX_VARS];
static int var_count = 0;
static struct gosub_frame gosub_stack[MAX_GOSUB];
static int gosub_top = 0;
static struct for_frame for_stack[MAX_FOR];
static int for_top = 0;
/* IF ELSE END IF block stack */
#define MAX_IF_DEPTH 16
struct if_block {
int took_then; /* 1 if we executed THEN branch, 0 if we skipped to ELSE/END IF */
};
static struct if_block if_stack[MAX_IF_DEPTH];
static int if_depth = 0;
/* WHILE WEND block stack */
#define MAX_WHILE_DEPTH 16
struct while_frame {
int line_index;
char *position;
};
static struct while_frame while_stack[MAX_WHILE_DEPTH];
static int while_top = 0;
#define MAX_UDF_PARAMS 16
#define MAX_UDF_FUNCS 32
#define MAX_UDF_DEPTH 16
struct udf_func {
char name[VAR_NAME_MAX];
int param_count;
char param_names[MAX_UDF_PARAMS][VAR_NAME_MAX];
int param_is_string[MAX_UDF_PARAMS];
int body_line;
char *body_pos;
};
static struct udf_func udf_funcs[MAX_UDF_FUNCS];
static int udf_func_count = 0;
static int udf_call_depth = 0;
static struct value udf_return_value;
static int udf_returned = 0;
struct udf_call_frame {
int func_index;
int saved_line;
char *saved_pos;
struct value saved_params[MAX_UDF_PARAMS];
};
static struct udf_call_frame udf_call_stack[MAX_UDF_DEPTH];
/* User-defined functions created with DEF FN. */
#define MAX_USER_FUNCS 32
struct user_func {
char name[8]; /* Function name, e.g. "FNY" (uppercased) */
char param_name[8]; /* Parameter variable name, e.g. "X" (uppercased) */
int param_is_string; /* Non-zero if parameter is string type */
char *body; /* Duplicated expression text after '=' */
};
static struct user_func user_funcs[MAX_USER_FUNCS];
static int user_func_count = 0;
/* DATA/READ support */
#define MAX_DATA_ITEMS 256
static struct value data_items[MAX_DATA_ITEMS];
static int data_count = 0;
static int data_index = 0;
/* File I/O: logical file numbers 1-255, CBM-style OPEN/CLOSE/PRINT#/INPUT#/GET#.
* Device 1 = disk/file (filename required). Secondary: 0=read, 1=write, 2=append.
* ST (status) is updated after INPUT#/GET#: 0=ok, 64=EOF, 1=error/not open. */
#define MAX_OPEN_FILES 16
static FILE *open_files[256]; /* 1-based; [0] unused; NULL = closed */
static void set_io_status(int st);
static int current_line = 0;
static char *statement_pos = NULL;
static volatile int halted = 0;
static int print_col = 0;
#ifdef GFX_VIDEO
static GfxVideoState *gfx_vs = NULL;
/* GFX text output state (mirrors a C64-like 40x25 text screen). */
#define GFX_COLS 40
#define GFX_ROWS 25
static int gfx_x = 0;
static int gfx_y = 0;
static uint8_t gfx_fg = 14; /* default light blue */
static uint8_t gfx_bg = 6; /* default blue background */
static int gfx_reverse = 0;
static int gfx_raw_screen_codes = 0; /* when set, bytes 0–255 are screen codes */
static uint8_t gfx_ascii_to_screencode(unsigned char c)
{
if (c >= 'A' && c <= 'Z') return (uint8_t)(c - 'A' + 1);
if (c >= 'a' && c <= 'z') return (uint8_t)(c - 'a' + 1);
if (c == '@') return 0;
if (c >= ' ' && c <= '?') return (uint8_t)c;
return 32;
}
static void gfx_scroll_up(void)
{
int row;
if (!gfx_vs) return;
for (row = 0; row < GFX_ROWS - 1; row++) {
memcpy(&gfx_vs->screen[row * GFX_COLS],
&gfx_vs->screen[(row + 1) * GFX_COLS],
GFX_COLS);
memcpy(&gfx_vs->color[row * GFX_COLS],
&gfx_vs->color[(row + 1) * GFX_COLS],
GFX_COLS);
}
memset(&gfx_vs->screen[(GFX_ROWS - 1) * GFX_COLS], 32, GFX_COLS);
memset(&gfx_vs->color[(GFX_ROWS - 1) * GFX_COLS], gfx_fg, GFX_COLS);
}
static void gfx_newline(void)
{
gfx_x = 0;
gfx_y++;
if (gfx_y >= GFX_ROWS) {
gfx_scroll_up();
gfx_y = GFX_ROWS - 1;
}
print_col = gfx_x;
}
static void gfx_clear_screen(void)
{
if (!gfx_vs) return;
memset(gfx_vs->screen, 32, GFX_TEXT_SIZE);
memset(gfx_vs->color, gfx_fg, GFX_COLOR_SIZE);
gfx_x = 0;
gfx_y = 0;
print_col = 0;
}
static int gfx_apply_control_code(unsigned char code)
{
/* Return non-zero if the code was handled as control/state. */
switch (code) {
case 14: /* switch to lowercase/uppercase charset */
if (gfx_vs) gfx_vs->charset_lowercase = 1;
petscii_set_lowercase(1);
return 1;
case 142: /* switch to uppercase/graphics charset */
if (gfx_vs) gfx_vs->charset_lowercase = 0;
petscii_set_lowercase(0);
return 1;
case 13: /* CR */
case 10: /* LF */
/* Avoid double newline: gfx_put_byte already wraps at col 40, so when
* the viewer sends CR after wrapping, we're already at col 0. */
if (gfx_x != 0) gfx_newline();
return 1;
case 19: /* HOME */
gfx_x = 0;
gfx_y = 0;
print_col = 0;
return 1;
case 147: /* CLR */
gfx_clear_screen();
return 1;
case 17: /* down */
if (gfx_y < GFX_ROWS - 1) gfx_y++;
return 1;
case 145: /* up */
if (gfx_y > 0) gfx_y--;
return 1;
case 29: /* right */
if (gfx_x < GFX_COLS - 1) gfx_x++;
print_col = gfx_x;
return 1;
case 157: /* left */
if (gfx_x > 0) gfx_x--;
print_col = gfx_x;
return 1;
case 18: /* reverse on */
gfx_reverse = 1;
return 1;
case 146: /* reverse off */
gfx_reverse = 0;
return 1;
case 20: /* DEL: backspace — cursor left and erase (like C64) */
if (gfx_x > 0 && gfx_vs) {
int del_idx;
gfx_x--;
del_idx = gfx_y * GFX_COLS + gfx_x;
if (del_idx >= 0 && del_idx < (int)GFX_TEXT_SIZE) {
gfx_vs->screen[del_idx] = 32;
gfx_vs->color[del_idx] = (uint8_t)(gfx_fg & 0x0F);
}
print_col = gfx_x;
}
return 1;
/* PETSCII colour control codes -> set current foreground colour index. */
case 144: gfx_fg = 0; return 1; /* black */
case 5: gfx_fg = 1; return 1; /* white */
case 28: gfx_fg = 2; return 1; /* red */
case 159: gfx_fg = 3; return 1; /* cyan */
case 156: gfx_fg = 4; return 1; /* purple */
case 30: gfx_fg = 5; return 1; /* green */
case 31: gfx_fg = 6; return 1; /* blue */
case 158: gfx_fg = 7; return 1; /* yellow */
case 129: gfx_fg = 8; return 1; /* orange */
case 149: gfx_fg = 9; return 1; /* brown */
case 150: gfx_fg = 10; return 1; /* light red */
case 151: gfx_fg = 11; return 1; /* dark gray */
case 152: gfx_fg = 12; return 1; /* medium gray */
case 153: gfx_fg = 13; return 1; /* light green */
case 154: gfx_fg = 14; return 1; /* light blue */
case 155: gfx_fg = 15; return 1; /* light gray */
default:
break;
}
return 0;
}
static void gfx_put_byte(unsigned char b)
{
int idx;
uint8_t sc;
if (!gfx_vs) return;
if (gfx_apply_control_code(b)) return;
/* By default, map printable ASCII to C64 screen codes for convenience.
* With SCREENCODES ON (gfx_raw_screen_codes): bytes are PETSCII from .seq
* streams—same as CHR$/PRINT. Convert PETSCII→screen code; the font (like
* gfx_charset_demo via POKE) expects screen codes 0–255. */
if (gfx_raw_screen_codes) {
sc = petscii_to_screencode(b);
} else if (b >= 32 && b <= 126) {
sc = gfx_ascii_to_screencode(b);
} else {
sc = (uint8_t)b;
}
if (gfx_reverse && sc < 128) {
sc |= 0x80;
}
if (gfx_x < 0) gfx_x = 0;
if (gfx_x >= GFX_COLS) gfx_newline();
if (gfx_y < 0) gfx_y = 0;
if (gfx_y >= GFX_ROWS) gfx_y = GFX_ROWS - 1;
idx = gfx_y * GFX_COLS + gfx_x;
if (idx >= 0 && idx < (int)GFX_TEXT_SIZE) {
gfx_vs->screen[idx] = sc;
gfx_vs->color[idx] = (uint8_t)(gfx_fg & 0x0F);
}
gfx_x++;
if (gfx_x >= GFX_COLS) {
gfx_newline();
} else {
print_col = gfx_x;
}
}
static int gfx_keyq_pop(uint8_t *out)
{
uint8_t head;
if (!gfx_vs) return 0;
head = gfx_vs->key_q_head;
if (head == gfx_vs->key_q_tail) {
return 0; /* empty */
}
*out = gfx_vs->key_queue[head];
head++;
if (head >= (uint8_t)sizeof(gfx_vs->key_queue)) head = 0;
gfx_vs->key_q_head = head;
return 1;
}
#endif
/* PETSCII/ANSI configuration */
static int petscii_mode = 0;
/* When set, do not output ANSI (color/reverse/cursor); output is paste-friendly, no extra bytes. */
static int petscii_plain = 0;
/* When set (e.g. stdout is a pipe), do not insert newlines at PRINT_WIDTH. */
static int petscii_no_wrap = 0;
enum {
PALETTE_ANSI = 0, /* Standard ANSI SGR colors */
PALETTE_C64_8BIT = 1 /* 8-bit palette approximating C64 colors */
};
static int palette_mode = PALETTE_ANSI;
static int cursor_hidden = 0;
static int petscii_lowercase_opt = 0;
/* Case-insensitive string compare. */
static int str_eq_ci(const char *a, const char *b)
{
if (!a || !b) return (a == b);
while (*a && *b) {
if (toupper((unsigned char)*a) != toupper((unsigned char)*b)) return 0;
a++; b++;
}
return (*a == *b);
}
/* Apply option from #OPTION directive (file overrides CLI). Returns 0 on success, -1 on error. */
static int apply_option_directive(const char *name, const char *value)