-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathib.c
More file actions
1942 lines (1753 loc) · 52.9 KB
/
ib.c
File metadata and controls
1942 lines (1753 loc) · 52.9 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
/*
* =============================================================================
* FILENAME: ib.c
* VERSION: 5.0
* AUTHOR: BASIC++ Community (Jeff)
* DESCRIPTION: BASIC++ (IB) Interpreter
*
* This is a minimal, portable BASIC interpreter written in a single C file.
* It is designed as a framework, prioritizing memory optimization and clarity,
* with speed as a secondary goal. It is intended to be easily expandable.
* =============================================================================
*
*
* =============================================================================
* LICENSE
* =============================================================================
*
* Modified MIT License
*
* Copyright (c) 2025 Jeff
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, but not sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* THIS SOFTWARE IS NOT TO BE SOLD.
*
* =============================================================================
* DEVELOPMENT PHILOSOPHY (UNIX PHILOSOPHY)
* =============================================================================
*
* 1. Do one thing and do it well:
* This interpreter executes a minimal, 8-bit Integer BASIC. It does not
* manage a GUI, edit files (beyond SAVE/LOAD), or perform complex OS tasks.
*
* 2. Write programs that work together:
* This interpreter reads/writes plain text files (.bas, lprint.out),
* allowing it to be scripted or have its output piped to other tools.
*
* 3. Handle plain text streams:
* The core I/O (PRINT, INPUT, SAVE, LOAD) is text-based, adhering
* to this principle.
*
* 4. Modularity:
* While this is a single file for portability, the design (stubs for
* $IMPORT, etc.) is intended to be refactored into a modular architecture.
*
* 5. Clarity over cleverness:
* The code prioritizes readability. For example, it uses a simple
* left-to-right parser and a straightforward GOSUB stack.
*
* =============================================================================
* HOW TO COMPILE (POSIX / GCC)
* =============================================================================
*
* This code is POSIX-compliant C and should compile on any standard
* Linux distribution (Debian, Fedora, etc.) or FreeDOS (using DJGPP)
* with GCC or an equivalent C compiler.
*
* 1. For Portability and Size (Recommended):
* This flag (-Os) optimizes for the smallest possible executable size,
* which is ideal for portability and resource-constrained systems.
*
* gcc -Wall -Os -o ib ib.c
*
* 2. For Speed (Performance):
* This flag (-O2) enables a suite of optimizations for execution speed,
* potentially at the cost of a larger binary.
*
* gcc -Wall -O2 -o ib ib.c
*
* 3. For Debugging (Development):
* This flag (-g) includes debugging symbols in the executable,
* allowing you to use a debugger like GDB.
*
* gcc -Wall -g -o ib ib.c
*
* =============================================================================
*
* MEMORY LAYOUT:
*
* The interpreter's "user memory" is defined by static, fixed-size
* arrays. The total allocatable memory (with v5.0 defaults) is:
*
* | Memory Area | Constant | Size | Calculation (assuming 4-byte int) | Total Size |
* | :---------------- | :------------ | :----------- | :------------------------------------ | :----------- |
* | Program Storage | MAX_LINES | 500 lines | 500 * (127 chars + 4 bytes for line#) | 64.0 KB |
* | Variable Storage | NUM_VARIABLES | 26 vars | 26 * 1 byte (signed char) | 26 bytes |
* | GOSUB Stack | STACK_SIZE | 64 levels | 64 * 4 bytes (int) | 256 bytes |
* | **Total** | | | | **~64.2 KB** |
*
* The "xx kbytes Free" message at startup only reports the main
* "Program Storage" (65,500 bytes / 1024 = 63 KB, via integer division).
*
* --- HOW TO ADJUST MEMORY ---
*
* To change the memory limits, you must edit the #define constants
* in the "--- Constants ---" section below:
*
* - To increase/decrease program memory, change MAX_LINES or MAX_LINE_LEN.
* - To increase/decrease GOSUB depth, change STACK_SIZE.
* - NUM_VARIABLES is fixed at 26 (A-Z) and should not be changed
* without modifying the variable storage logic.
*
* After changing these values, you MUST re-compile the interpreter.
*
* =============================================================================
*
* HOW TO STOP AN ENDLESS LOOP:
*
* If your BASIC program enters an endless loop (e.g., "10 GOTO 10"),
* you can force-quit the interpreter by pressing:
*
* Ctrl+C
*
* This will send an interrupt signal (SIGINT), stop the program, and return you
* to your command-line shell (POSIX or FreeDOS).
*
* =============================================================================
*/
/*
* =============================================================================
* --- Includes ---
* =============================================================================
*/
#include <stdio.h> /* For printf, fgets, FILE, fopen, etc. (Standard I/O) */
#include <stdlib.h> /* For strtol, exit, atoi (Standard Library) */
#include <string.h> /* For strcmp, strncpy, strlen, strtok, memset (String ops) */
#include <ctype.h> /* For isdigit, isalpha, isspace (Character types) */
#include <stddef.h> /* For size_t (used by string.h etc.) */
/*
* Note: We provide our own portable, case-insensitive string compare
* function `ib_stricmp` at the end of this file to avoid
* non-standard functions like `stricmp` or `strcasecmp`.
*/
/*
* =============================================================================
* --- Constants ---
* =============================================================================
*/
/**
* @brief MAX_LINES
* The maximum number of lines the BASIC program can have.
* This directly impacts the "Program Storage" memory.
*/
#define MAX_LINES 500
/**
* @brief MAX_LINE_LEN
* The maximum number of characters allowed in a single line of BASIC code,
* *not* including the line number itself.
* This directly impacts the "Program Storage" memory.
*/
#define MAX_LINE_LEN 127
/**
* @brief STACK_SIZE
* The maximum number of nested GOSUB calls.
* This directly impacts the "GOSUB Stack" memory.
*/
#define STACK_SIZE 64
/**
* @brief NUM_VARIABLES
* The number of variables (A-Z). This is fixed at 26.
*/
#define NUM_VARIABLES 26
/**
* @brief COMMAND_MAX_LEN
* Internal buffer size for parsing the command (e.g., "PRINT", "GOTO").
* Should be a few chars larger than the longest command.
*/
#define COMMAND_MAX_LEN 32
/*
* =============================================================================
* --- Data Structures ---
* =============================================================================
*/
/**
* @brief Line
* A structure to hold a single line of BASIC code in program storage.
* It stores the line number and the text of the line.
*/
typedef struct
{
int line_number;
char text[MAX_LINE_LEN];
} Line;
/*
* =============================================================================
* --- Global Variables ---
* =============================================================================
*/
/*
* Program Storage:
* An array to hold all lines of the user's BASIC program.
* Its size is (MAX_LINES * sizeof(Line)).
*/
static Line program_storage[MAX_LINES];
/**
* @brief line_count
* The number of lines *currently* stored in `program_storage`.
*/
static int line_count = 0;
/**
* @brief variables
* A simple array for variables A-Z. 'A' maps to index 0, 'B' to 1, etc.
* We use `signed char` as it's typically the smallest signed type (1 byte),
* which gives us our 8-bit signed range (-128 to +127).
*/
static signed char variables[NUM_VARIABLES];
/**
* @brief gosub_stack
* A fixed-size stack to store return addresses (line indices) for GOSUB.
*/
static int gosub_stack[STACK_SIZE];
/**
* @brief stack_pointer
* Points to the next *free* slot in the `gosub_stack`.
*/
static int stack_pointer = 0;
/**
* @brief program_counter
* The *index* in `program_storage` of the line being executed.
* This is only used when `RUN`ning a program.
*/
static int program_counter = 0;
/**
* @brief is_running
* A flag to control the `RUN` loop. Set to 0 by END, STOP, or an error.
*/
static int is_running = 0;
/**
* @brief is_debug_mode
* A flag set at startup by the --debug argument.
* This will enable verbose logging of interpreter state.
*/
static int is_debug_mode = 0;
/**
* @brief parser_ptr
* A global string pointer used by the parser.
* This points to the *current character* being parsed within a line.
* This is a common and simple way to manage state in a recursive parser.
*/
static char* parser_ptr;
/**
* @brief current_dialect_name
* A global variable to hold the name of the dialect for the startup banner.
* This allows modules to "re-brand" the interpreter.
*/
static const char* current_dialect_name = "core";
/**
* @brief current_version
* A global variable to hold the version string.
* This is the "single source of truth" for the version number.
*/
static const char* current_version = "5.0";
/*
* =============================================================================
* --- Forward Declarations ---
* =============================================================================
*/
/*
* This is a "table of contents" for all our functions.
* It tells the C compiler about the "shape" of each function *before* it's
* used. This allows us to define functions in a clean, logical order
* without worrying about "implicit declaration" compile errors.
*/
/* --- Core Interpreter Functions --- */
static void execute_statement(void);
static void run_program(void);
static void list_program(void);
static void new_program(void);
static void save_program(const char* filename);
static void load_program(const char* filename);
/* --- Program Storage Functions --- */
static int find_line_index(int line_number);
static void store_line(const char* line_str);
/* --- Command Handlers (cmd_*.c) --- */
static void cmd_print(void);
static void cmd_lprint(void);
static void cmd_input(void);
static void cmd_let(void);
static void cmd_goto(void);
static void cmd_gosub(void);
static void cmd_return(void);
static void cmd_if(void);
static void cmd_rem(void);
static void cmd_end(void);
static void cmd_beep(void);
static void cmd_system(void);
static void cmd_exit(void);
static void cmd_quit(void);
static void cmd_stub(const char* command);
/* --- Parser Functions (parser.c) --- */
static signed char parse_expression(void);
static signed char parse_term(void);
static signed char parse_number(void);
/* --- Utility Functions (utils.c) --- */
static void report_error(const char* message);
static void skip_whitespace(void);
static int ib_stricmp(const char* s1, const char* s2);
/*
* =============================================================================
* --- Core Interpreter ---
* =============================================================================
*/
/**
* @brief main
* The main entry point for the IB interpreter.
* It initializes the interpreter and runs the main REPL
* (Read-Evaluate-Print Loop).
*
* @param argc The count of command-line arguments.
* @param argv An array of command-line argument strings.
* @return 0 on successful exit.
*
* We add `argc` and `argv` to check for command-line arguments
* like `--debug`, as requested in the project specifications.
*/
int main(int argc, char *argv[])
{
/*
* We use MAX_LINE_LEN for the input buffer, but add extra space
* (+20) to safely accommodate a line number and spaces, preventing
* a buffer overflow on user input.
*/
char input_buffer[MAX_LINE_LEN + 20];
long total_program_bytes = sizeof(program_storage);
long total_program_kb = total_program_bytes / 1024;
/*
* A temporary buffer for the "immediate mode" line.
* We copy the user's input into this buffer because
* `execute_statement` will modify it (via `parser_ptr` and `strtok`).
*/
char immediate_line[MAX_LINE_LEN + 20];
/* --- Check for --debug flag --- */
/*
* This fulfills the requirement for a --debug flag.
* We loop through all arguments, not just the first one.
*/
int i;
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--debug") == 0)
{
is_debug_mode = 1;
printf("[DEBUG] Debug mode enabled.\n");
break; /* Stop checking once found */
}
}
/* Clear memory and prepare the interpreter for startup. */
new_program();
/* --- Startup Banner --- */
/* Note: We use %ld for 'long' to be portable. */
printf("BASIC++ (%s) v%s\n", current_dialect_name, current_version);
printf("%ld kbytes Free\n", total_program_kb);
printf("READY\n");
/*
* --- Main REPL Loop ---
* This is the main Read-Evaluate-Print Loop.
* 1. READ: It waits for user input (using fgets).
* 2. EVAL: It figures out if it's a direct command or a stored line.
* 3. PRINT: It executes the command (printing output) or stores the line.
* 4. LOOP: It repeats.
*/
while (1)
{
printf("> ");
fflush(stdout); /* Ensure prompt is displayed before input */
if (fgets(input_buffer, sizeof(input_buffer), stdin) == NULL)
{
/*
* User pressed Ctrl+D (end-of-file) or an error occurred.
* This is a clean way to exit the REPL.
*/
printf("\n"); /* Print a newline to make it clean */
break; /* Exit loop and terminate program */
}
/* Remove newline character (both \n and \r) from input */
input_buffer[strcspn(input_buffer, "\r\n")] = 0;
/* --- Direct Mode or Stored Line? --- */
parser_ptr = input_buffer; /* MUST set parser_ptr before skip_whitespace() */
skip_whitespace();
if (isdigit((unsigned char)*parser_ptr))
{
/*
* 1. STORED LINE
* The line starts with a digit, so it's a program line
* that needs to be stored.
*/
store_line(input_buffer);
}
else if (*parser_ptr != '\0')
{
/*
* 2. DIRECT MODE
* The line does NOT start with a digit, and it's not empty.
* This is a direct command to be executed immediately.
*/
/*
* We MUST copy the input line before executing.
* `execute_statement` modifies the string it's parsing,
* so we give it a temporary copy to work with.
*/
strncpy(immediate_line, input_buffer, sizeof(immediate_line));
immediate_line[sizeof(immediate_line) - 1] = '\0'; /* Safety */
/* Set the global parser pointer to the start of our copy */
parser_ptr = immediate_line;
/*
* Set the `is_running` flag. This tells our functions
* (like `report_error`) that we are in "execution mode"
* (even though it's just one line).
*/
is_running = 1;
/* Call the main dispatch function to run this single line. */
execute_statement();
/*
* The line is done, so we clear the flag.
* If an error occurred, `is_running` will already be 0,
* but it's safe to set it again.
*/
is_running = 0;
printf("OK\n"); /* "OK" is the standard response in direct mode */
printf("READY\n");
}
else
{
/*
* 3. BLANK LINE
* The user just hit Enter. Do nothing and show the prompt.
*/
printf("READY\n");
}
}
return 0; /* User exited the REPL */
}
/**
* @brief execute_statement
* The main "dispatch" function for the interpreter.
*
* This function reads the *first word* from the global `parser_ptr`
* (which is assumed to be a command) and then "dispatches"
* execution to the correct `cmd_...` handler function.
*
* This is the primary place to **ADD NEW COMMANDS**.
* As per the architecture proposals, this large if/else block is the
* component that will be replaced by a dynamic dispatch table.
*/
static void execute_statement(void)
{
/*
* A small, local buffer to hold the parsed command.
* We use a fixed size for simplicity (COMMAND_MAX_LEN).
*/
char command[COMMAND_MAX_LEN];
int i = 0;
/* Ensure the `is_running` flag is checked before we do anything. */
if (!is_running) return;
/* 1. Get the command (the first "token") */
skip_whitespace();
/*
* Parse the command token manually.
* We use `toupper` to make the command case-insensitive
* *as we read it*.
*
* We don't use `strtok` here because it's destructive and can
* cause issues. A simple loop is safer and cleaner.
*/
while (*parser_ptr && !isspace((unsigned char)*parser_ptr) && i < (COMMAND_MAX_LEN - 1))
{
command[i] = toupper((unsigned char)*parser_ptr);
parser_ptr++;
i++;
}
command[i] = '\0'; /* Null-terminate the command string */
/* 2. Skip whitespace *after* the command to point to its arguments */
skip_whitespace();
if (is_debug_mode)
{
printf("[DEBUG] Executing command: '%s', Args: '%s'\n", command, parser_ptr);
}
/*
* --- COMMAND DISPATCH TABLE ---
*
* This is the "switchboard" of the interpreter. It compares the
* parsed `command` string to our list of known commands and
* calls the appropriate function.
*
* TO ADD A NEW COMMAND:
* 1. Write a `cmd_mycommand(void)` function.
* 2. Add its prototype to the "Forward Declarations" section.
* 3. Add an `else if (strcmp(command, "MYCOMMAND") == 0)`
* block here to call your new function.
*/
if (command[0] == '\0')
{
/* Empty line (or just a line number), do nothing. */
return;
}
else if (strcmp(command, "PRINT") == 0)
{
cmd_print();
}
else if (strcmp(command, "LPRINT") == 0)
{
cmd_lprint();
}
else if (strcmp(command, "LET") == 0)
{
cmd_let();
}
else if (strcmp(command, "INPUT") == 0)
{
cmd_input();
}
else if (strcmp(command, "GOTO") == 0)
{
cmd_goto();
}
else if (strcmp(command, "GOSUB") == 0)
{
cmd_gosub();
}
else if (strcmp(command, "RETURN") == 0)
{
cmd_return();
}
else if (strcmp(command, "IF") == 0)
{
cmd_if();
}
else if (strcmp(command, "REM") == 0)
{
cmd_rem(); /* Does nothing, just a comment */
}
else if (strcmp(command, "END") == 0)
{
cmd_end();
}
else if (strcmp(command, "STOP") == 0)
{
/* STOP is an alias for END in our simple dialect */
cmd_end();
}
else if (strcmp(command, "BEEP") == 0)
{
cmd_beep();
}
else if (strcmp(command, "RUN") == 0)
{
/*
* Special case: RUN is a direct-mode command.
* If we are *already* running, it's an error.
* (This check prevents "10 RUN" from causing chaos).
*/
if (is_running && program_counter > 0)
{
report_error("CAN'T USE RUN IN A PROGRAM");
}
else
{
run_program();
}
}
else if (strcmp(command, "LIST") == 0)
{
/* Same as RUN, this is a direct-mode command. */
if (is_running && program_counter > 0)
{
report_error("CAN'T USE LIST IN A PROGRAM");
}
else
{
list_program();
}
}
else if (strcmp(command, "NEW") == 0)
{
/* Same as RUN, this is a direct-mode command. */
if (is_running && program_counter > 0)
{
report_error("CAN'T USE NEW IN A PROGRAM");
}
else
{
new_program();
}
}
else if (strcmp(command, "SAVE") == 0)
{
if (is_running && program_counter > 0)
{
report_error("CAN'T USE SAVE IN A PROGRAM");
}
else
{
/*
* We pass the `parser_ptr` (which now points
* to the filename) to the save function.
*/
save_program(parser_ptr);
}
}
else if (strcmp(command, "LOAD") == 0)
{
if (is_running && program_counter > 0)
{
report_error("CAN'T USE LOAD IN A PROGRAM");
}
else
{
load_program(parser_ptr);
}
}
else if (strcmp(command, "SYSTEM") == 0)
{
cmd_system();
}
else if (strcmp(command, "QUIT") == 0)
{
/*
* QUIT is a direct-mode command, but we also allow
* "10 QUIT" as a way to exit a program.
*/
cmd_quit();
}
else if (strcmp(command, "EXIT") == 0)
{
/* EXIT is an alias for QUIT */
cmd_exit();
}
/*
* --- Module Extension Stubs ---
* These commands are reserved for future modules.
* They are handled by a simple "stub" function.
*/
else if (strcmp(command, "$IMPORT") == 0)
{
cmd_stub("$IMPORT");
}
else if (strcmp(command, "$INCLUDE") == 0)
{
cmd_stub("$INCLUDE");
}
else if (strcmp(command, "$MERGE") == 0)
{
cmd_stub("$MERGE");
}
else
{
/*
* If the command is not in our list, it's an error.
* We pass the buffer we parsed for a clean error message.
*/
report_error("UNKNOWN COMMAND");
}
}
/*
* =============================================================================
* --- Core Functions ---
* =============================================================================
*/
/**
* @brief run_program
* Executes the stored BASIC program from the beginning.
*/
static void run_program(void)
{
/*
* A temporary buffer for the line being executed.
* We *must* copy the line from `program_storage` before
* parsing, because the parser (`execute_statement`)
* modifies the string it is parsing.
*/
char line_buffer[MAX_LINE_LEN];
if (is_debug_mode)
{
printf("[DEBUG] --- RUNNING PROGRAM ---\n");
}
/* 1. Initialize the "CPU" */
is_running = 1; /* Set the run flag to ON */
program_counter = 0; /* Start at the first line (index 0) */
stack_pointer = 0; /* Clear the GOSUB stack */
memset(variables, 0, sizeof(variables)); /* Clear all variables */
/*
* 2. Main Execution Loop
* This loop is the "CPU" of our interpreter.
* It runs as long as `is_running` is true and we haven't
* run off the end of the program.
*/
while (is_running && program_counter < line_count)
{
/*
* We store the *current* line index.
* This lets us detect if a GOTO or GOSUB
* has changed the `program_counter`.
*/
int current_line_index = program_counter;
if (is_debug_mode)
{
printf("[DEBUG] Running line %d: %s\n",
program_storage[program_counter].line_number,
program_storage[program_counter].text);
}
/*
* Copy the line text to our temporary buffer.
* This is CRITICAL. We must not let the parser
* modify our original program code in `program_storage`.
*/
strncpy(line_buffer, program_storage[program_counter].text, MAX_LINE_LEN);
line_buffer[MAX_LINE_LEN - 1] = '\0'; /* Ensure null-termination */
/* Set the global parser pointer to the start of this line */
parser_ptr = line_buffer;
/* Execute the statement(s) on this line */
execute_statement();
/*
* 3. Advance the Program Counter
* If the `program_counter` *was not* changed by the statement
* (e.g., it was not a GOTO, GOSUB, or RETURN),
* then we manually advance it to the next line.
*/
if (is_running && program_counter == current_line_index)
{
program_counter++;
}
}
/* 4. Program finished */
if (is_debug_mode)
{
printf("[DEBUG] --- PROGRAM ENDED ---\n");
}
is_running = 0; /* Set the run flag to OFF */
}
/**
* @brief list_program
* Prints all lines currently in program storage.
*/
static void list_program(void)
{
int i;
for (i = 0; i < line_count; i++)
{
printf("%d %s\n", program_storage[i].line_number, program_storage[i].text);
}
}
/**
* @brief new_program
* Clears the program, variables, and GOSUB stack.
* Resets the interpreter to a clean state.
*/
static void new_program(void)
{
if (is_debug_mode)
{
printf("[DEBUG] Clearing all memory (NEW).\n");
}
/*
* We just set line_count to 0. This "orphans" all the
* data in `program_storage`, effectively clearing it
* without spending time zeroing the memory.
*/
line_count = 0;
program_counter = 0;
stack_pointer = 0;
/* We *must*, however, zero the variable and stack memory. */
memset(variables, 0, sizeof(variables));
memset(gosub_stack, 0, sizeof(gosub_stack));
}
/**
* @brief save_program
* Saves the current program to a text file.
* @param filename The name of the file to save.
*/
static void save_program(const char* filename)
{
FILE *file;
int i;
/*
* The `filename` pointer comes from `parser_ptr`,
* which is already pointing at the filename.
* We just need to check if it's empty.
*/
if (filename == NULL || *filename == '\0')
{
report_error("FILENAME REQUIRED");
return;
}
/*
* NOTE: We are not trimming whitespace from the filename
* for simplicity. "SAVE my file.bas" will fail.
* The user must type "SAVE myfile.bas".
*/
if (is_debug_mode)
{
printf("[DEBUG] Saving program to '%s'\n", filename);
}
file = fopen(filename, "w"); /* "w" = Write mode (create/overwrite) */
if (file == NULL)
{
report_error("CANNOT OPEN FILE");
return;
}
/* Iterate through program storage and print each line to the file */
for (i = 0; i < line_count; i++)
{
fprintf(file, "%d %s\n", program_storage[i].line_number, program_storage[i].text);
}
fclose(file);
}
/**
* @brief load_program
* Loads a program from a text file, replacing the current one.
* @param filename The name of the file to load.
*/
static void load_program(const char* filename)
{
FILE *file;
/*
* Buffer for reading lines *from the file*.
* It must be large enough to hold the line number, space,
* and the line text.
*/
char file_line_buffer[MAX_LINE_LEN + 20];
if (filename == NULL || *filename == '\0')
{
report_error("FILENAME REQUIRED");
return;
}
if (is_debug_mode)
{
printf("[DEBUG] Loading program from '%s'\n", filename);
}
file = fopen(filename, "r"); /* "r" = Read mode */
if (file == NULL)
{
report_error("FILE NOT FOUND");
return;
}
/* 1. Clear the old program */
new_program();
/*
* 2. Read every line from the file
* `fgets` reads one line at a time into `file_line_buffer`.
*/
while (fgets(file_line_buffer, sizeof(file_line_buffer), file) != NULL)
{
/* Remove newline character */
file_line_buffer[strcspn(file_line_buffer, "\r\n")] = 0;
/*
* 3. Store the line
* We pass the freshly-read line to `store_line`,
* which will parse the line number and add it to
* our `program_storage`.
*/
store_line(file_line_buffer);
}
fclose(file);
}
/*
* =============================================================================
* --- Program Storage Functions ---
* =============================================================================
*/
/**
* @brief find_line_index
* Finds the array index for a given line number.
* Uses a simple linear search.
*
* @param line_number The BASIC line number to find (e.g., 100).
* @return The array index (0 to line_count-1), or -1 if not found.
*/
static int find_line_index(int line_number)
{
int i;
for (i = 0; i < line_count; i++)
{
if (program_storage[i].line_number == line_number)
{
return i; /* Found it */
}
if (program_storage[i].line_number > line_number)
{
/*
* The list is sorted, so if we've passed it,
* it doesn't exist. Stop early.
*/
return -1;
}
}
return -1; /* Not found */
}
/**