-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathMMBasic.c
More file actions
6346 lines (5898 loc) · 226 KB
/
MMBasic.c
File metadata and controls
6346 lines (5898 loc) · 226 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
/*
* @cond
* The following section will be excluded from the documentation.
*/
/***********************************************************************************************************************
PicoMite MMBasic
MMBasic.c
<COPYRIGHT HOLDERS> Geoff Graham, Peter Mather
Copyright (c) 2021, <COPYRIGHT HOLDERS> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. The name MMBasic be used when referring to the interpreter in any documentation and promotional material and the original copyright message be displayed
on the console at startup (additional copyright messages may be added).
4. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed
by the <copyright holder>.
5. Neither the name of the <copyright holder> nor the names of its contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDERS> AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDERS> BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
************************************************************************************************************************/
#include <stdio.h>
#include <limits.h>
#include <stdarg.h>
#include "MMBasic.h"
#include "pico/stdlib.h"
#include "Functions.h"
#include "Commands.h"
#include "Operators.h"
#include "Custom.h"
#include "Hardware_Includes.h"
#include "Turtle.h"
#include "hardware/flash.h"
#ifndef PICOMITEWEB
#include "pico/multicore.h"
#endif
// this is the command table that defines the various tokens for commands in the source code
// most of them are listed in the .h files so you should not add your own here but instead add
// them to the appropiate .h file
#define INCLUDE_COMMAND_TABLE
const struct s_tokentbl commandtbl[] = {
#include "Functions.h"
#include "Commands.h"
#include "Operators.h"
#include "Custom.h"
#include "Hardware_Includes.h"
};
#undef INCLUDE_COMMAND_TABLE
// this is the token table that defines the other tokens in the source code
// most of them are listed in the .h files so you should not add your own here
// but instead add them to the appropiate .h file
#define INCLUDE_TOKEN_TABLE
const struct s_tokentbl tokentbl[] = {
#include "Functions.h"
#include "Commands.h"
#include "Operators.h"
#include "Custom.h"
#include "Hardware_Includes.h"
};
#undef INCLUDE_TOKEN_TABLE
static int maxlocalvars = MAXLOCALVARS;
static int maxglobalvars = MAXGLOBALVARS;
// these are initialised at startup
int CommandTableSize, TokenTableSize;
#ifdef rp2350
struct s_funtbl funtbl[MAXSUBFUN];
// void hashlabels(int errabort);
void hashlabels(unsigned char *p, int ErrAbort);
// Character classification - single memory access vs function calls
__not_in_flash("data") const unsigned char name_start_tbl[256] = {
['A' ... 'Z'] = 1, ['a' ... 'z'] = 1, ['_'] = 1};
__not_in_flash("data") const unsigned char name_char_tbl[256] = {
['A' ... 'Z'] = 1, ['a' ... 'z'] = 1, ['0' ... '9'] = 1, ['_'] = 1, ['.'] = 1, [0x1e] = 1};
__not_in_flash("data") const unsigned char name_end_tbl[256] = {
['A' ... 'Z'] = 1, ['a' ... 'z'] = 1, ['0' ... '9'] = 1, ['_'] = 1, ['.'] = 1, ['$'] = 1, ['!'] = 1, ['%'] = 1};
__not_in_flash("data") const unsigned char charmap[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff};
#endif
// Forward declarations for struct helper functions (NOT in RAM for size savings)
#ifdef STRUCTENABLED
int ValidateStructParam(int varIndex, int argVarIndex, void *argval_s, int argtype, unsigned char *argname);
unsigned char *CopyStructReturn(void *struct_data, int struct_type_idx, int *out_struct_type);
void *ResolveStructMember(unsigned char *struct_ptr, int struct_idx, unsigned char *member_path,
unsigned char **pp, int *member_type);
int FindStructBase(unsigned char *basename, int baselen, int *pvindex);
#endif
struct s_vartbl __attribute__((aligned(64))) g_vartbl[MAXVARS] = {0}; // this table stores all variables
int g_varcnt = 0; // number of variables
int g_VarIndex; // Global set by findvar after a variable has been created or found
int g_Localvarcnt; // number of LOCAL variables
int g_Globalvarcnt; // number of GLOBAL variables
int g_LocalIndex; // used to track the level of local variables
unsigned char OptionExplicit, OptionEscape, OptionConsole; // used to force the declaration of variables before their use
bool OptionNoCheck = false;
unsigned char DefaultType; // the default type if a variable is not specifically typed
int emptyarray = 0;
int TempStringClearStart; // used to prevent clearing of space in an expression that called a FUNCTION
unsigned char *subfun[MAXSUBFUN]; // table used to locate all subroutines and functions
char CurrentSubFunName[MAXVARLEN + 1]; // the name of the current sub or fun
char CurrentInterruptName[MAXVARLEN + 1]; // the name of the current interrupt function
jmp_buf jmprun;
jmp_buf mark; // longjump to recover from an error and abort
jmp_buf ErrNext; // longjump to recover from an error and continue
unsigned char inpbuf[STRINGSIZE]; // used to store user keystrokes until we have a line
unsigned char tknbuf[STRINGSIZE]; // used to store the tokenised representation of the users input line
// unsigned char lastcmd[STRINGSIZE]; // used to store the last command in case it is needed by the EDIT command
unsigned char PromptString[MAXPROMPTLEN]; // the prompt for input, an empty string means use the default
int ProgramChanged; // true if the program in memory has been changed and not saved
struct s_hash g_hashlist[MAXLOCALVARS] = {0};
int g_hashlistpointer = 0;
unsigned char *LibMemory; // This is where the library is stored. At the last flash slot (4)
int multi = false;
unsigned char *ProgMemory; // program memory, this is where the program is stored
int PSize; // the size of the program stored in ProgMemory[]
int NextData; // used to track the next item to read in DATA & READ stmts
unsigned char *NextDataLine; // used to track the next line to read in DATA & READ stmts
int g_OptionBase; // track the state of OPTION BASE
int PrepareProgramExt(unsigned char *, int, unsigned char **, int);
char PreprogramErrMsg[MAXERRMSG]; // Error message from PrepareProgram if it fails
unsigned char *PreprogramErrLine = NULL; // Line pointer where PrepareProgram error occurred
#ifndef rp2350
static int subfun_letter_start[26];
// Compare two SUB/FUNCTION identifiers by base name (case-insensitive), ignoring type suffixes.
static int CompareSubFunBaseName(unsigned char *a, unsigned char *b)
{
unsigned char *p1 = a + sizeof(CommandToken);
unsigned char *p2 = b + sizeof(CommandToken);
skipspace(p1);
skipspace(p2);
while (isnamechar(*p1) && isnamechar(*p2))
{
int c1 = mytoupper(*p1);
int c2 = mytoupper(*p2);
if (c1 != c2)
return c1 - c2;
p1++;
p2++;
}
if (isnamechar(*p1))
return 1;
if (isnamechar(*p2))
return -1;
return 0;
}
// Compare a caller identifier to a subfun entry by base name only.
static int CompareNameToSubFunBase(unsigned char *name, unsigned char *sub)
{
unsigned char *p1 = name;
unsigned char *p2 = sub + sizeof(CommandToken);
skipspace(p2);
while (isnamechar(*p1) && isnamechar(*p2))
{
int c1 = mytoupper(*p1);
int c2 = mytoupper(*p2);
if (c1 != c2)
return c1 - c2;
p1++;
p2++;
}
if (isnamechar(*p1))
return 1;
if (isnamechar(*p2))
return -1;
return 0;
}
#endif
// Helper function to find the T_NEWLINE that starts a line containing the given pointer
// Returns the original pointer if it already points to T_NEWLINE or if not found
static unsigned char *FindLineStart(unsigned char *linePtr, unsigned char *memStart)
{
char *p, *tp;
if (!linePtr || *linePtr == T_NEWLINE)
return linePtr;
// Search for the start of the line (similar to error() function logic)
tp = p = (char *)memStart;
while (*p != 0xff)
{
while (*p)
p++; // look for the zero marking the start of an element
if (p >= (char *)linePtr || p[1] == 0)
{ // the previous line was the one that we wanted
return (unsigned char *)tp;
}
if (p[1] == T_NEWLINE)
{
tp = ++p; // save because it might be the line we want
}
p++; // step over the zero marking the start of the element
skipspace(p);
if (p[0] == T_LABEL)
p += p[1] + 2; // skip over the label
}
return linePtr; // fallback to original
}
// Helper function to set error info for PrepareProgram errors
// This mimics what error() does for setting editor position but without longjmp
static void SetPreprogramError(const char *msg, unsigned char *linePtr)
{
strcpy(PreprogramErrMsg, msg);
PreprogramErrLine = linePtr;
// Set editor position if the line is in program memory
if (linePtr && linePtr >= ProgMemory && linePtr < ProgMemory + MAX_PROG_SIZE)
{
// Find the T_NEWLINE that starts this line (editor needs this)
StartEditPoint = FindLineStart(linePtr, ProgMemory);
StartEditChar = 0;
}
else if (linePtr && Option.LIBRARY_FLASH_SIZE == MAX_PROG_SIZE &&
linePtr >= LibMemory && linePtr < LibMemory + MAX_PROG_SIZE)
{
// In library - can't edit, but still set for display purposes
StartEditPoint = NULL;
StartEditChar = 0;
}
else
{
StartEditPoint = NULL;
StartEditChar = 0;
}
}
// Print PrepareProgram error with line info (similar to error() output)
// This displays the line number, source line, and error message
void PrintPreprogramError(void)
{
char tstr[STRINGSIZE * 2];
unsigned char linebuf[STRINGSIZE];
int line_num;
char *p, *tp;
unsigned char *linePtr = PreprogramErrLine;
if (linePtr)
{
// Determine if we're in program memory or library
unsigned char *memStart = ProgMemory;
unsigned char *memEnd = ProgMemory + MAX_PROG_SIZE;
int isLibrary = 0;
if (Option.LIBRARY_FLASH_SIZE == MAX_PROG_SIZE &&
linePtr >= LibMemory && linePtr < LibMemory + MAX_PROG_SIZE)
{
memStart = LibMemory;
memEnd = LibMemory + MAX_PROG_SIZE;
isLibrary = 1;
}
if (linePtr >= memStart && linePtr < memEnd)
{
// Handle case where linePtr doesn't point to T_NEWLINE
// (similar to error() function logic)
if (*linePtr != T_NEWLINE)
{
// Search for the start of the line
tp = p = (char *)memStart;
while (*p != 0xff)
{
while (*p)
p++; // look for the zero marking the start of an element
if (p >= (char *)linePtr || p[1] == 0)
{ // the previous line was the one that we wanted
linePtr = (unsigned char *)tp;
break;
}
if (p[1] == T_NEWLINE)
{
tp = ++p; // save because it might be the line we want
}
p++; // step over the zero marking the start of the element
skipspace(p);
if (p[0] == T_LABEL)
p += p[1] + 2; // skip over the label
}
}
// Get the line number and source text
llist(linebuf, linePtr);
if (isLibrary)
{
sprintf(tstr, "[LIBRARY] %s\r\n", linebuf);
}
else
{
line_num = CountLines(linePtr);
sprintf(tstr, "[%d] %s\r\n", line_num, linebuf);
}
MMPrintString(tstr);
}
}
// Print the error message
sprintf(tstr, "Error: %s\r\n", PreprogramErrMsg);
MMPrintString(tstr);
}
int ProgramValid = 1; // 0 = program has errors (cannot run), 1 = valid/runnable
extern uint32_t core1stack[];
;
#if defined(MMFAMILY)
unsigned char FunKey[NBRPROGKEYS][MAXKEYLEN + 1]; // data storage for the programmable function keys
#endif
uint32_t DefinedSubFunMem; // Records memory allocated to DefinedSubFun in case of an error
int DefinedSubFunLocalIndex; // Records LocalIndex at start of DefinedSubFun in case of an error
char digit[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x10
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, // 0x20
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 0x30
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x40
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x50
0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x60
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x70
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xA0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xB0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xC0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xD0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xE0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 0xF0
};
///////////////////////////////////////////////////////////////////////////////////////////////
// Global information used by operators and functions
//
MMFLOAT farg1, farg2, fret; // the two float arguments and returned value
long long int iarg1, iarg2, iret; // the two integer arguments and returned value
unsigned char *sarg1, *sarg2, *sret; // the two string arguments and returned value
int targ; // the type of the returned value
////////////////////////////////////////////////////////////////////////////////////////////////
// Global information used by functions
// functions use targ, fret and sret as defined for operators (above)
unsigned char *ep; // pointer to the argument to the function terminated with a zero byte.
// it is NOT trimmed of spaces
////////////////////////////////////////////////////////////////////////////////////////////////
// Global information used by commands
//
int cmdtoken; // Token number of the command
unsigned char *cmdline; // Command line terminated with a zero unsigned char and trimmed of spaces
unsigned char *nextstmt; // Pointer to the next statement to be executed.
unsigned char *CurrentLinePtr, *SaveCurrentLinePtr; // Pointer to the current line (used in error reporting)
unsigned char *ContinuePoint; // Where to continue from if using the continue statement
extern int TraceOn;
extern unsigned char *TraceBuff[TRACE_BUFF_SIZE];
extern int TraceBuffIndex; // used for listing the contents of the trace buffer
extern long long int CallCFunction(unsigned char *CmdPtr, unsigned char *ArgList, unsigned char *DefP, unsigned char *CallersLinePtr);
/////////////////////////////////////////////////////////////////////////////////////////////////
// Functions only used within MMBasic.c
//
// void getexpr(unsigned char *);
// void checktype(int *, int);
unsigned char *getvalue(unsigned char *p, MMFLOAT *fa, long long int *ia, unsigned char **sa, int *oo, int *ta);
unsigned char tokenTHEN, tokenELSE, tokenGOTO, tokenEQUAL, tokenTO, tokenSTEP, tokenWHILE, tokenUNTIL, tokenGOSUB, tokenAS, tokenFOR;
unsigned short cmdIF, cmdENDIF, cmdEND_IF, cmdELSEIF, cmdELSE_IF, cmdELSE, cmdSELECT_CASE, cmdFOR, cmdNEXT, cmdWHILE, cmdENDSUB, cmdENDFUNCTION, cmdLOCAL, cmdSTATIC, cmdCASE, cmdDO, cmdLOOP, cmdCASE_ELSE, cmdEND_SELECT;
unsigned short cmdSUB, cmdFUN, cmdCFUN, cmdCSUB, cmdIRET, cmdComment, cmdEndComment;
#ifdef STRUCTENABLED
unsigned short cmdTYPE, cmdEND_TYPE; // Structure type definition commands
#endif
uint32_t heapend;
#ifdef STRUCTENABLED
// Calculate the natural alignment needed for a structure (used to pad arrays of structs)
static int GetStructAlignment(struct s_structdef *sd)
{
int max_align = 1;
for (int i = 0; i < sd->num_members; i++)
{
struct s_structmember *sm = &sd->members[i];
int align = 1;
if (sm->type == T_INT || sm->type == T_NBR)
{
align = sizeof(long long int);
}
else if (sm->type == T_STRUCT)
{
if (sm->size >= 0 && sm->size < g_structcnt && g_structtbl[sm->size] != NULL)
align = GetStructAlignment(g_structtbl[sm->size]);
else
align = sizeof(long long int); // Safe default for unknown nested struct
}
if (align > max_align)
max_align = align;
}
return max_align;
}
#endif
/********************************************************************************************************************************************
Program management
Includes the routines to initialise MMBasic, start running the interpreter, and to run a program in memory
*********************************************************************************************************************************************/
// Initialise MMBasic
void MIPS16 InitBasic(void)
{
DefaultType = T_NBR;
CommandTableSize = (sizeof(commandtbl) / sizeof(struct s_tokentbl));
TokenTableSize = (sizeof(tokentbl) / sizeof(struct s_tokentbl));
#ifdef STRUCTENABLED
// Initialize structure type table pointers to NULL
for (int i = 0; i < MAX_STRUCT_TYPES; i++)
{
g_structtbl[i] = NULL;
}
g_structcnt = 0;
#endif
ClearProgram(true);
// load the commonly used tokens
// by looking them up once here performance is improved considerably
tokenTHEN = GetTokenValue((unsigned char *)"Then");
tokenELSE = GetTokenValue((unsigned char *)"Else");
tokenGOTO = GetTokenValue((unsigned char *)"GoTo");
tokenEQUAL = GetTokenValue((unsigned char *)"=");
tokenTO = GetTokenValue((unsigned char *)"To");
tokenSTEP = GetTokenValue((unsigned char *)"Step");
tokenWHILE = GetTokenValue((unsigned char *)"While");
tokenUNTIL = GetTokenValue((unsigned char *)"Until");
tokenGOSUB = GetTokenValue((unsigned char *)"GoSub");
tokenAS = GetTokenValue((unsigned char *)"As");
tokenFOR = GetTokenValue((unsigned char *)"For");
cmdLOOP = GetCommandValue((unsigned char *)"Loop");
cmdIF = GetCommandValue((unsigned char *)"If");
cmdENDIF = GetCommandValue((unsigned char *)"EndIf");
cmdEND_IF = GetCommandValue((unsigned char *)"End If");
cmdELSEIF = GetCommandValue((unsigned char *)"ElseIf");
cmdELSE_IF = GetCommandValue((unsigned char *)"Else If");
cmdELSE = GetCommandValue((unsigned char *)"Else");
cmdSELECT_CASE = GetCommandValue((unsigned char *)"Select Case");
cmdCASE = GetCommandValue((unsigned char *)"Case");
cmdCASE_ELSE = GetCommandValue((unsigned char *)"Case Else");
cmdEND_SELECT = GetCommandValue((unsigned char *)"End Select");
cmdSUB = GetCommandValue((unsigned char *)"Sub");
cmdFUN = GetCommandValue((unsigned char *)"Function");
cmdLOCAL = GetCommandValue((unsigned char *)"Local");
cmdSTATIC = GetCommandValue((unsigned char *)"Static");
cmdENDSUB = GetCommandValue((unsigned char *)"End Sub");
cmdENDFUNCTION = GetCommandValue((unsigned char *)"End Function");
cmdDO = GetCommandValue((unsigned char *)"Do");
cmdFOR = GetCommandValue((unsigned char *)"For");
cmdNEXT = GetCommandValue((unsigned char *)"Next");
cmdIRET = GetCommandValue((unsigned char *)"IReturn");
cmdCSUB = GetCommandValue((unsigned char *)"CSub");
cmdComment = GetCommandValue((unsigned char *)"/*");
cmdEndComment = GetCommandValue((unsigned char *)"*/");
#ifdef STRUCTENABLED
cmdTYPE = GetCommandValue((unsigned char *)"Type");
cmdEND_TYPE = GetCommandValue((unsigned char *)"End Type");
#endif
heapend = (uint32_t)&__heap_start + PICO_HEAP_SIZE;
// SInt(CommandTableSize);
// SIntComma(TokenTableSize);
// SSPrintString("\r\n");
}
// test the stack for overflow - this is a NULL function in the DOS version
static inline void TestStackOverflow(void)
{
uint32_t stack;
__asm volatile("MRS %0, msp" : "=r"(stack));
if (stack < heapend)
error("Stack overflow, at depth %, stack \\, heap \\", g_LocalIndex, (int64_t)stack, (int64_t)heapend);
}
int CheckEmpty(char *p)
{
int emptyarray = 0;
char *pp = strchr((char *)p, '(');
if (pp)
{
pp++;
skipspace(pp);
if (*pp == ')')
emptyarray = 1;
}
while (*(++pp))
{
if (*pp == '(')
return 1; // can't be a function call with an implied opening
if (*pp == ')')
return 0; // closing bracket without open so much be implied in a function call e.g. PEEK(
}
return emptyarray;
}
// Lightweight strtod for BASIC numeric literals only (digits, '.', 'E'/'e', '+'/'-')
// Runs from RAM to avoid XIP cache thrashing on RP2040
static double __not_in_flash_func(fast_strtod)(const char *s)
{
double result = 0.0;
double frac = 0.0;
double frac_div = 1.0;
int sign = 1;
int in_frac = 0;
// optional sign
if (*s == '-')
{
sign = -1;
s++;
}
else if (*s == '+')
{
s++;
}
// integer and fractional digits
while (*s)
{
if (*s >= '0' && *s <= '9')
{
if (in_frac)
{
frac_div *= 10.0;
frac += (*s - '0') / frac_div;
}
else
{
result = result * 10.0 + (*s - '0');
}
}
else if (*s == '.' && !in_frac)
{
in_frac = 1;
}
else if (*s == 'e' || *s == 'E')
{
s++;
int exp_sign = 1;
int exp = 0;
if (*s == '-')
{
exp_sign = -1;
s++;
}
else if (*s == '+')
{
s++;
}
while (*s >= '0' && *s <= '9')
exp = exp * 10 + (*s++ - '0');
// apply exponent
double pow10 = 1.0;
for (int i = 0; i < exp; i++)
pow10 *= 10.0;
if (exp_sign > 0)
return sign * (result + frac) * pow10;
else
return sign * (result + frac) / pow10;
}
else
{
break;
}
s++;
}
return sign * (result + frac);
}
// run a program
// this will continuously execute a program until the end (marked by TWO zero chars)
// the argument p must point to the first line to be executed
void __not_in_flash_func(ExecuteProgram)(unsigned char *p)
{
int i, SaveLocalIndex = 0;
jmp_buf SaveErrNext;
memcpy(SaveErrNext, ErrNext, sizeof(jmp_buf)); // we call ExecuteProgram() recursively so we need to store/restore old jump buffer between calls
skipspace(p); // just in case, skip any whitespace
while (1)
{
if (*p == 0)
p++; // step over the zero byte marking the beginning of a new element
if (*p == T_NEWLINE)
{
CurrentLinePtr = p; // and pointer to the line for error reporting
TraceBuff[TraceBuffIndex] = p; // used by TRACE LIST
if (++TraceBuffIndex >= TRACE_BUFF_SIZE)
TraceBuffIndex = 0;
if (TraceOn && p > ProgMemory && p < ProgMemory + MAX_PROG_SIZE)
{
inpbuf[0] = '[';
IntToStr((char *)inpbuf + 1, CountLines(p), 10);
strcat((char *)inpbuf, "]");
MMPrintString((char *)inpbuf);
uSec(1000);
}
p++; // and step over the token
}
if (*p == T_LINENBR)
p += 3; // and step over the number
skipspace(p); // and skip any trailing white space
if (p[0] == T_LABEL)
{ // got a label
p += p[1] + 2; // skip over the label
skipspace(p); // and any following spaces
}
if (*p)
{ // if p is pointing to a command
if (*p == '\'')
nextstmt = cmdline = p + 1;
else
nextstmt = cmdline = p + sizeof(CommandToken);
skipspace(cmdline);
skipelement(nextstmt);
if (*p && *p != '\'')
{ // ignore a comment line
SaveLocalIndex = g_LocalIndex; // save this if we need to cleanup after an error
if (setjmp(ErrNext) == 0)
{ // return to the else leg of this if error and OPTION ERROR SKIP/IGNORE is in effect
if (p[0] >= C_BASETOKEN && p[1] >= C_BASETOKEN)
{
cmdtoken = commandtbl_decode(p);
targ = T_CMD;
commandtbl[cmdtoken].fptr(); // execute the command
}
else
{
if (!isnamestart(*p) && *p == '~')
StandardError(36);
else if (!isnamestart(*p))
error("Invalid character: @", (int)(*p));
{
i = FindSubFun(p, false); // it could be a defined command
if (i >= 0)
{ // >= 0 means it is a user defined command
DefinedSubFun(false, p, i, NULL, NULL, NULL, NULL);
}
else
StandardError(36);
}
}
}
else
{
g_LocalIndex = SaveLocalIndex; // restore so that we can clean up any memory leaks
ClearTempMemory();
}
if (OptionErrorSkip > 0 && OptionErrorSkip < 100000)
OptionErrorSkip--; // if OPTION ERROR SKIP decrement the count - we do not error if it is greater than zero
if (g_TempMemoryIsChanged)
ClearTempMemory(); // at the end of each command we need to clear any temporary string vars
#ifndef PICOMITEWEB
if (core1stack[0] != 0x12345678)
error("CPU2 Stack overflow");
#endif
if (!OptionNoCheck)
{
CheckAbort();
check_interrupt(); // check for an MMBasic interrupt or touch event and handle it
}
}
p = nextstmt;
}
if ((p[0] == 0 && p[1] == 0) || (p[0] == 0xff && p[1] == 0xff))
break; // the end of the program is marked by TWO zero chars, empty flash by two 0xff
}
memcpy(ErrNext, SaveErrNext, sizeof(jmp_buf)); // restore old jump buffer
}
/********************************************************************************************************************************************
Code associated with processing user defined subroutines and functions
********************************************************************************************************************************************/
// Scan through the program loaded in flash and build a table pointing to the definition of all user defined subroutines and functions.
// This pre processing speeds up the program when using defined subroutines and functions
// this routine also looks for embedded fonts and adds them to the font table
// Returns: 0 = success, 1 = error (error message in PreprogramErrMsg)
int MIPS16 PrepareProgram(int ErrAbort)
{
int i, j, NbrFuncts;
#ifdef rp2350
int u, namelen;
uint32_t hash = FNV_offset_basis;
char printvar[MAXVARLEN + 1];
unsigned char *p1, *p2;
#endif
// Clear any previous error state
PreprogramErrMsg[0] = 0;
PreprogramErrLine = NULL;
ProgramValid = 1;
for (i = FONT_BUILTIN_NBR; i < FONT_TABLE_SIZE - 1; i++)
FontTable[i] = NULL; // clear the font table
#ifdef STRUCTENABLED
// Clear structure type definitions before parsing
// IMPORTANT: When called from command prompt (not after ClearProgram/InitHeap),
// memory may have been previously allocated but not freed. We must free it
// to prevent memory leaks from repeated command line entries.
for (i = 0; i < MAX_STRUCT_TYPES; i++)
{
if (g_structtbl[i] != NULL)
{
// Validate pointer is within valid heap memory before freeing
// FreeMemorySafe checks both MMHeap and PSRAM ranges
FreeMemorySafe((void **)&g_structtbl[i]);
}
}
g_structcnt = 0;
#endif
NbrFuncts = 0;
CFunctionFlash = CFunctionLibrary = NULL;
if (Option.LIBRARY_FLASH_SIZE == MAX_PROG_SIZE)
{
NbrFuncts = PrepareProgramExt(LibMemory, 0, &CFunctionLibrary, ErrAbort);
if (NbrFuncts < 0)
{
ProgramValid = 0;
return 1; // Error occurred
}
}
NbrFuncts = PrepareProgramExt(ProgMemory, NbrFuncts, &CFunctionFlash, ErrAbort);
if (NbrFuncts < 0)
{
ProgramValid = 0;
return 1; // Error occurred
}
#ifndef rp2350
// RP2040: sort subfun table in-place by base name to enable binary search in FindSubFun.
for (i = 0; i < NbrFuncts - 1; i++)
{
for (j = 0; j < NbrFuncts - i - 1; j++)
{
if (CompareSubFunBaseName(subfun[j], subfun[j + 1]) > 0)
{
unsigned char *tmp = subfun[j];
subfun[j] = subfun[j + 1];
subfun[j + 1] = tmp;
}
}
}
// Build first-letter index (A..Z) for faster bounded lookup.
for (i = 0; i < 26; i++)
subfun_letter_start[i] = -1;
for (i = 0; i < NbrFuncts; i++)
{
unsigned char *sp = subfun[i] + sizeof(CommandToken);
skipspace(sp);
int first = mytoupper(*sp);
if (first >= 'A' && first <= 'Z')
{
int idx = first - 'A';
if (subfun_letter_start[idx] == -1)
subfun_letter_start[idx] = i;
}
}
// Duplicate-name check (same behavior as before: compares base names only).
if (ErrAbort)
{
for (i = 1; i < NbrFuncts; i++)
{
if (CompareSubFunBaseName(subfun[i - 1], subfun[i]) == 0)
{
SetPreprogramError("Duplicate name", subfun[i]);
ProgramValid = 0;
return 1;
}
}
}
#endif
// check the sub/fun table for duplicates
#ifdef rp2350
memset(funtbl, 0, sizeof(struct s_funtbl) * MAXSUBFUN);
for (i = 0; i < MAXSUBFUN && subfun[i] != NULL; i++)
{
// First we will hash the function name and add it to the function table
// This allows for a fast check of a variable name being the same as a function name
// It also allows a hash look up for function name matching
p1 = subfun[i];
p1 += sizeof(CommandToken);
skipspace(p1);
p2 = (unsigned char *)printvar;
namelen = 0;
hash = FNV_offset_basis;
do
{
u = mytoupper(*p1);
hash ^= u;
hash *= FNV_prime;
*p2++ = u;
p1++;
if (++namelen > MAXVARLEN)
{
if (ErrAbort)
{
SetPreprogramError("Function name too long", CurrentLinePtr);
ProgramValid = 0;
return 1;
}
}
} while (isnamechar(*p1));
if (namelen != MAXVARLEN)
*p2 = 0;
hash %= MAXSUBFUN; // scale to size of table
while (funtbl[hash].name[0] != 0)
{
hash++;
if (hash == MAXSUBFUN)
hash = 0;
}
funtbl[hash].index = i;
memcpy(funtbl[hash].name, printvar, (namelen == MAXVARLEN ? namelen : namelen + 1));
}
if (Option.LIBRARY_FLASH_SIZE == MAX_PROG_SIZE)
{
hashlabels(LibMemory, ErrAbort);
// if(!ErrAbort) return;
}
hashlabels(ProgMemory, ErrAbort);
// if(!ErrAbort) return;
#endif
if (!ErrAbort)
return 0;
#ifdef rp2350
for (i = 0; i < MAXSUBFUN && subfun[i] != NULL; i++)
{
for (j = i + 1; j < MAXSUBFUN && subfun[j] != NULL; j++)
{
p1 = subfun[i];
p1 += sizeof(CommandToken);
skipspace(p1);
p2 = subfun[j];
p2 += sizeof(CommandToken);
skipspace(p2);
while (1)
{
if (!isnamechar(*p1) && !isnamechar(*p2))
{
if (ErrAbort)
{
// Point to the duplicate (second) function, not the original
SetPreprogramError("Duplicate name", subfun[j]);
ProgramValid = 0;
return 1;
}
return 0;
}
if (mytoupper(*p1) != mytoupper(*p2))
break;
p1++;
p2++;
}
}
}
#endif
// for(i=0;i<MAXSUBFUN;i++){
// if(funtbl[i].name[0]!=0){
// MMPrintString(funtbl[i].name);PIntHC(funtbl[i].index);PIntComma(i);PRet();
// }
// }
return 0;
}
// This scans one area (main program or the library area) for user defined subroutines and functions.
// It is only used by PrepareProgram() above.
// Returns: count of subfuns on success, -1 on error (error message set in PreprogramErrMsg)
int MIPS16 PrepareProgramExt(unsigned char *p, int i, unsigned char **CFunPtr, int ErrAbort)
{
unsigned int *cfp;
while (*p != 0xff)
{
p = GetNextCommand(p, &CurrentLinePtr, NULL);
if (*p == 0)
break; // end of the program or module
CommandToken tkn = commandtbl_decode(p);
if (tkn == cmdSUB || tkn == cmdFUN /*|| tkn == cmdCFUN*/ || tkn == cmdCSUB)
{ // found a SUB, FUN, CFUNCTION or CSUB token
if (i >= MAXSUBFUN)
{
if (ErrAbort)
{
SetPreprogramError("Too many subroutines and functions", CurrentLinePtr);
return -1;
}
continue;
}
subfun[i++] = p++; // save the address and step over the token
p++; // step past rest of command token
skipspace(p);
if (!isnamestart(*p))
{
if (ErrAbort)
{
SetPreprogramError("Invalid identifier", CurrentLinePtr);
return -1;
}
i--;
continue;
}
}
#ifdef STRUCTENABLED
// Process TYPE definitions during preprocessing
else if (tkn == cmdTYPE)
{
unsigned char *tp = p;
unsigned char name[MAXVARLEN + 1];
int namelen = 0;
int j;
struct s_structdef *sd;
// Skip past TYPE token
tp += sizeof(CommandToken);
skipspace(tp);
// Parse structure type name
if (!isnamestart(*tp))
{
if (ErrAbort)
{
SetPreprogramError("Invalid TYPE name", CurrentLinePtr);
return -1;
}
continue;
}
while (isnamechar(*tp) && namelen < MAXVARLEN)
{
name[namelen++] = mytoupper(*tp++);
}
name[namelen] = 0;
// Check for duplicate type name
for (j = 0; j < g_structcnt; j++)
{
if (g_structtbl[j] != NULL && strcmp((char *)name, (char *)g_structtbl[j]->name) == 0)
{
if (ErrAbort)
{
SetPreprogramError("TYPE already defined", CurrentLinePtr);
return -1;
}
continue;
}
}
// Check max types
if (g_structcnt >= MAX_STRUCT_TYPES)
{
if (ErrAbort)