-
Notifications
You must be signed in to change notification settings - Fork 46
/
basic.cpp
1984 lines (1852 loc) · 63.2 KB
/
basic.cpp
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
/* ---------------------------------------------------------------------------
* Basic Interpreter
* Robin Edwards 2014
* ---------------------------------------------------------------------------
* This BASIC is modelled on Sinclair BASIC for the ZX81 and ZX Spectrum. It
* should be capable of running most of the examples in the manual for both
* machines, with the exception of anything machine specific (i.e. graphics,
* sound & system variables).
*
* Notes
* - All numbers (except line numbers) are floats internally
* - Multiple commands are allowed per line, seperated by :
* - LET is optional e.g. LET a = 6: b = 7
* - MOD provides the modulo operator which was missing from Sinclair BASIC.
* Both numbers are first rounded to ints e.g. 5 mod 2 = 1
* - CONT can be used to continue from a STOP. It does not continue from any
* other error condition.
* - Arrays can be any dimension. There is no single char limit to names.
* - Like Sinclair BASIC, DIM a(10) and LET a = 5 refer to different 'a's.
* One is a simple variable, the other is an array. There is no ambiguity
* since the one being referred to is always clear from the context.
* - String arrays differ from Sinclair BASIC. DIM a$(5,5) makes an array
* of 25 strings, which can be any length. e.g. LET a$(1,1)="long string"
* - functions like LEN, require brackets e.g. LEN(a$)
* - String manipulation functions are LEFT$, MID$, RIGHT$
* - RND is a nonary operator not a function i.e. RND not RND()
* - PRINT AT x,y ... is replaced by POSITION x,y : PRINT ...
* - LIST takes an optional start and end e.g. LIST 1,100 or LIST 50
* - INKEY$ reads the last key pressed from the keyboard, or an empty string
* if no key pressed. The (single key) buffer is emptied after the call.
* e.g. a$ = INKEY$
* - LOAD/SAVE load and save the current program to the EEPROM (1k limit).
* SAVE+ will set the auto-run flag, which loads the program automatically
* on boot. With a filename e.g. SAVE "test" saves to an external EEPROM.
* - DIR/DELETE "filename" - list and remove files from external EEPROM.
* - PINMODE <pin>, <mode> - sets the pin mode (0=input, 1=output, 2=pullup)
* - PIN <pin>, <state> - sets the pin high (non zero) or low (zero)
* - PINREAD(pin) returns pin value, ANALOGRD(pin) for analog pins
* ---------------------------------------------------------------------------
*/
// TODO
// ABS, SIN, COS, EXP etc
// DATA, READ, RESTORE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include "basic.h"
#include "host.h"
#include <avr/pgmspace.h>
int sysPROGEND;
int sysSTACKSTART, sysSTACKEND;
int sysVARSTART, sysVAREND;
int sysGOSUBSTART, sysGOSUBEND;
const char string_0[] PROGMEM = "OK";
const char string_1[] PROGMEM = "Bad number";
const char string_2[] PROGMEM = "Line too long";
const char string_3[] PROGMEM = "Unexpected input";
const char string_4[] PROGMEM = "Unterminated string";
const char string_5[] PROGMEM = "Missing bracket";
const char string_6[] PROGMEM = "Error in expr";
const char string_7[] PROGMEM = "Numeric expr expected";
const char string_8[] PROGMEM = "String expr expected";
const char string_9[] PROGMEM = "Line number too big";
const char string_10[] PROGMEM = "Out of memory";
const char string_11[] PROGMEM = "Div by zero";
const char string_12[] PROGMEM = "Variable not found";
const char string_13[] PROGMEM = "Bad command";
const char string_14[] PROGMEM = "Bad line number";
const char string_15[] PROGMEM = "Break pressed";
const char string_16[] PROGMEM = "NEXT without FOR";
const char string_17[] PROGMEM = "STOP statement";
const char string_18[] PROGMEM = "Missing THEN in IF";
const char string_19[] PROGMEM = "RETURN without GOSUB";
const char string_20[] PROGMEM = "Wrong array dims";
const char string_21[] PROGMEM = "Bad array index";
const char string_22[] PROGMEM = "Bad string index";
const char string_23[] PROGMEM = "Error in VAL input";
const char string_24[] PROGMEM = "Bad parameter";
//PROGMEM const char *errorTable[] = {
const char* const errorTable[] PROGMEM = {
string_0, string_1, string_2, string_3,
string_4, string_5, string_6, string_7,
string_8, string_9, string_10, string_11,
string_12, string_13, string_14, string_15,
string_16, string_17, string_18, string_19,
string_20, string_21, string_22, string_23,
string_24
};
// Token flags
// bits 1+2 number of arguments
#define TKN_ARGS_NUM_MASK 0x03
// bit 3 return type (set if string)
#define TKN_RET_TYPE_STR 0x04
// bits 4-6 argument type (set if string)
#define TKN_ARG1_TYPE_STR 0x08
#define TKN_ARG2_TYPE_STR 0x10
#define TKN_ARG3_TYPE_STR 0x20
#define TKN_ARG_MASK 0x38
#define TKN_ARG_SHIFT 3
// bits 7,8 formatting
#define TKN_FMT_POST 0x40
#define TKN_FMT_PRE 0x80
PROGMEM const TokenTableEntry tokenTable[] = {
{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},
{":",TKN_FMT_POST}, {";",0}, {",",0}, {"AND",TKN_FMT_PRE|TKN_FMT_POST},
{"OR",TKN_FMT_PRE|TKN_FMT_POST}, {"NOT",TKN_FMT_POST}, {"PRINT",TKN_FMT_POST}, {"LET",TKN_FMT_POST},
{"LIST",TKN_FMT_POST}, {"RUN",TKN_FMT_POST}, {"GOTO",TKN_FMT_POST}, {"REM",TKN_FMT_POST},
{"STOP",TKN_FMT_POST}, {"INPUT",TKN_FMT_POST}, {"CONT",TKN_FMT_POST}, {"IF",TKN_FMT_POST},
{"THEN",TKN_FMT_PRE|TKN_FMT_POST}, {"LEN",1|TKN_ARG1_TYPE_STR}, {"VAL",1|TKN_ARG1_TYPE_STR}, {"RND",0},
{"INT",1}, {"STR$", 1|TKN_RET_TYPE_STR}, {"FOR",TKN_FMT_POST}, {"TO",TKN_FMT_PRE|TKN_FMT_POST},
{"STEP",TKN_FMT_PRE|TKN_FMT_POST}, {"NEXT", TKN_FMT_POST}, {"MOD",TKN_FMT_PRE|TKN_FMT_POST}, {"NEW",TKN_FMT_POST},
{"GOSUB",TKN_FMT_POST}, {"RETURN",TKN_FMT_POST}, {"DIM", TKN_FMT_POST}, {"LEFT$",2|TKN_ARG1_TYPE_STR|TKN_RET_TYPE_STR},
{"RIGHT$",2|TKN_ARG1_TYPE_STR|TKN_RET_TYPE_STR}, {"MID$",3|TKN_ARG1_TYPE_STR|TKN_RET_TYPE_STR}, {"CLS",TKN_FMT_POST}, {"PAUSE",TKN_FMT_POST},
{"POSITION", TKN_FMT_POST}, {"PIN",TKN_FMT_POST}, {"PINMODE", TKN_FMT_POST}, {"INKEY$", 0},
{"SAVE", TKN_FMT_POST}, {"LOAD", TKN_FMT_POST}, {"PINREAD",1}, {"ANALOGRD",1},
{"DIR", TKN_FMT_POST}, {"DELETE", TKN_FMT_POST}
};
/* **************************************************************************
* PROGRAM FUNCTIONS
* **************************************************************************/
void printTokens(unsigned char *p) {
int modeREM = 0;
while (*p != TOKEN_EOL) {
if (*p == TOKEN_IDENT) {
p++;
while (*p < 0x80)
host_outputChar(*p++);
host_outputChar((*p++)-0x80);
}
else if (*p == TOKEN_NUMBER) {
p++;
host_outputFloat(*(float*)p);
p+=4;
}
else if (*p == TOKEN_INTEGER) {
p++;
host_outputInt(*(long*)p);
p+=4;
}
else if (*p == TOKEN_STRING) {
p++;
if (modeREM) {
host_outputString((char*)p);
p+=1 + strlen((char*)p);
}
else {
host_outputChar('\"');
while (*p) {
if (*p == '\"') host_outputChar('\"');
host_outputChar(*p++);
}
host_outputChar('\"');
p++;
}
}
else {
uint8_t fmt = pgm_read_byte_near(&tokenTable[*p].format);
if (fmt & TKN_FMT_PRE)
host_outputChar(' ');
host_outputString((char *)pgm_read_word(&tokenTable[*p].token));
if (fmt & TKN_FMT_POST)
host_outputChar(' ');
if (*p==TOKEN_REM)
modeREM = 1;
p++;
}
}
}
void listProg(uint16_t first, uint16_t last) {
unsigned char *p = &mem[0];
while (p < &mem[sysPROGEND]) {
uint16_t lineNum = *(uint16_t*)(p+2);
if ((!first || lineNum >= first) && (!last || lineNum <= last)) {
host_outputInt(lineNum);
host_outputChar(' ');
printTokens(p+4);
host_newLine();
}
p+= *(uint16_t *)p;
}
}
unsigned char *findProgLine(uint16_t targetLineNumber) {
unsigned char *p = &mem[0];
while (p < &mem[sysPROGEND]) {
uint16_t lineNum = *(uint16_t*)(p+2);
if (lineNum >= targetLineNumber)
break;
p+= *(uint16_t *)p;
}
return p;
}
void deleteProgLine(unsigned char *p) {
uint16_t lineLen = *(uint16_t*)p;
sysPROGEND -= lineLen;
memmove(p, p+lineLen, &mem[sysPROGEND] - p);
}
int doProgLine(uint16_t lineNumber, unsigned char* tokenPtr, int tokensLength)
{
// find line of the at or immediately after the number
unsigned char *p = findProgLine(lineNumber);
uint16_t foundLine = 0;
if (p < &mem[sysPROGEND])
foundLine = *(uint16_t*)(p+2);
// if there's a line matching this one - delete it
if (foundLine == lineNumber)
deleteProgLine(p);
// now check to see if this is an empty line, if so don't insert it
if (*tokenPtr == TOKEN_EOL)
return 1;
// we now need to insert the new line at p
int bytesNeeded = 4 + tokensLength; // length, linenum + tokens
if (sysPROGEND + bytesNeeded > sysVARSTART)
return 0;
// make room if this isn't the last line
if (foundLine)
memmove(p + bytesNeeded, p, &mem[sysPROGEND] - p);
*(uint16_t *)p = bytesNeeded;
p += 2;
*(uint16_t *)p = lineNumber;
p += 2;
memcpy(p, tokenPtr, tokensLength);
sysPROGEND += bytesNeeded;
return 1;
}
/* **************************************************************************
* CALCULATOR STACK FUNCTIONS
* **************************************************************************/
// Calculator stack starts at the start of memory after the program
// and grows towards the end
// contains either floats or null-terminated strings with the length on the end
int stackPushNum(float val) {
if (sysSTACKEND + sizeof(float) > sysVARSTART)
return 0; // out of memory
unsigned char *p = &mem[sysSTACKEND];
*(float *)p = val;
sysSTACKEND += sizeof(float);
return 1;
}
float stackPopNum() {
sysSTACKEND -= sizeof(float);
unsigned char *p = &mem[sysSTACKEND];
return *(float *)p;
}
int stackPushStr(char *str) {
int len = 1 + strlen(str);
if (sysSTACKEND + len + 2 > sysVARSTART)
return 0; // out of memory
unsigned char *p = &mem[sysSTACKEND];
strcpy((char*)p, str);
p += len;
*(uint16_t *)p = len;
sysSTACKEND += len + 2;
return 1;
}
char *stackGetStr() {
// returns string without popping it
unsigned char *p = &mem[sysSTACKEND];
int len = *(uint16_t *)(p-2);
return (char *)(p-len-2);
}
char *stackPopStr() {
unsigned char *p = &mem[sysSTACKEND];
int len = *(uint16_t *)(p-2);
sysSTACKEND -= (len+2);
return (char *)&mem[sysSTACKEND];
}
void stackAdd2Strs() {
// equivalent to popping 2 strings, concatenating them and pushing the result
unsigned char *p = &mem[sysSTACKEND];
int str2len = *(uint16_t *)(p-2);
sysSTACKEND -= (str2len+2);
char *str2 = (char*)&mem[sysSTACKEND];
p = &mem[sysSTACKEND];
int str1len = *(uint16_t *)(p-2);
sysSTACKEND -= (str1len+2);
char *str1 = (char*)&mem[sysSTACKEND];
p = &mem[sysSTACKEND];
// shift the second string up (overwriting the null terminator of the first string)
memmove(str1 + str1len - 1, str2, str2len);
// write the length and update stackend
int newLen = str1len + str2len - 1;
p += newLen;
*(uint16_t *)p = newLen;
sysSTACKEND += newLen + 2;
}
// mode 0 = LEFT$, 1 = RIGHT$
void stackLeftOrRightStr(int len, int mode) {
// equivalent to popping the current string, doing the operation then pushing it again
unsigned char *p = &mem[sysSTACKEND];
int strlen = *(uint16_t *)(p-2);
len++; // include trailing null
if (len > strlen) len = strlen;
if (len == strlen) return; // nothing to do
sysSTACKEND -= (strlen+2);
p = &mem[sysSTACKEND];
if (mode == 0) {
// truncate the string on the stack
*(p+len-1) = 0;
}
else {
// copy the rightmost characters
memmove(p, p + strlen - len, len);
}
// write the length and update stackend
p += len;
*(uint16_t *)p = len;
sysSTACKEND += len + 2;
}
void stackMidStr(int start, int len) {
// equivalent to popping the current string, doing the operation then pushing it again
unsigned char *p = &mem[sysSTACKEND];
int strlen = *(uint16_t *)(p-2);
len++; // include trailing null
if (start > strlen) start = strlen;
start--; // basic strings start at 1
if (start + len > strlen) len = strlen - start;
if (len == strlen) return; // nothing to do
sysSTACKEND -= (strlen+2);
p = &mem[sysSTACKEND];
// copy the characters
memmove(p, p + start, len-1);
*(p+len-1) = 0;
// write the length and update stackend
p += len;
*(uint16_t *)p = len;
sysSTACKEND += len + 2;
}
/* **************************************************************************
* VARIABLE TABLE FUNCTIONS
* **************************************************************************/
// Variable table starts at the end of memory and grows towards the start
// Simple variable
// table +--------+-------+-----------------+-----------------+ . . .
// <--- | len | type | name | value |
// grows | 2bytes | 1byte | null terminated | float/string |
// +--------+-------+-----------------+-----------------+ . . .
//
// Array
// +--------+-------+-----------------+----------+-------+ . . .+-------+-------------+. .
// | len | type | name | num dims | dim1 | | dimN | elem(1,..1) |
// | 2bytes | 1byte | null terminated | 2bytes | 2bytes| | 2bytes| float |
// +--------+-------+-----------------+----------+-------+ . . .+-------+-------------+. .
// variable type byte
#define VAR_TYPE_NUM 0x1
#define VAR_TYPE_FORNEXT 0x2
#define VAR_TYPE_NUM_ARRAY 0x4
#define VAR_TYPE_STRING 0x8
#define VAR_TYPE_STR_ARRAY 0x10
unsigned char *findVariable(char *searchName, int searchMask) {
unsigned char *p = &mem[sysVARSTART];
while (p < &mem[sysVAREND]) {
int type = *(p+2);
if (type & searchMask) {
unsigned char *name = p+3;
if (strcasecmp((char*)name, searchName) == 0)
return p;
}
p+= *(uint16_t *)p;
}
return NULL;
}
void deleteVariableAt(unsigned char *pos) {
int len = *(uint16_t *)pos;
if (pos == &mem[sysVARSTART]) {
sysVARSTART += len;
return;
}
memmove(&mem[sysVARSTART] + len, &mem[sysVARSTART], pos - &mem[sysVARSTART]);
sysVARSTART += len;
}
// todo - consistently return errors rather than 1 or 0?
int storeNumVariable(char *name, float val) {
// these can be modified in place
int nameLen = strlen(name);
unsigned char *p = findVariable(name, VAR_TYPE_NUM|VAR_TYPE_FORNEXT);
if (p != NULL)
{ // replace the old value
// (could either be VAR_TYPE_NUM or VAR_TYPE_FORNEXT)
p += 3; // len + type;
p += nameLen + 1;
*(float *)p = val;
}
else
{ // allocate a new variable
int bytesNeeded = 3; // len + flags
bytesNeeded += nameLen + 1; // name
bytesNeeded += sizeof(float); // val
if (sysVARSTART - bytesNeeded < sysSTACKEND)
return 0; // out of memory
sysVARSTART -= bytesNeeded;
unsigned char *p = &mem[sysVARSTART];
*(uint16_t *)p = bytesNeeded;
p += 2;
*p++ = VAR_TYPE_NUM;
strcpy((char*)p, name);
p += nameLen + 1;
*(float *)p = val;
}
return 1;
}
int storeForNextVariable(char *name, float start, float step, float end, uint16_t lineNum, uint16_t stmtNum) {
int nameLen = strlen(name);
int bytesNeeded = 3; // len + flags
bytesNeeded += nameLen + 1; // name
bytesNeeded += 3 * sizeof(float); // vals
bytesNeeded += 2 * sizeof(uint16_t);
// unlike simple numeric variables, these are reallocated if they already exist
// since the existing value might be a simple variable or a for/next variable
unsigned char *p = findVariable(name, VAR_TYPE_NUM|VAR_TYPE_FORNEXT);
if (p != NULL) {
// check there will actually be room for the new value
uint16_t oldVarLen = *(uint16_t*)p;
if (sysVARSTART - (bytesNeeded - oldVarLen) < sysSTACKEND)
return 0; // not enough memory
deleteVariableAt(p);
}
if (sysVARSTART - bytesNeeded < sysSTACKEND)
return 0; // out of memory
sysVARSTART -= bytesNeeded;
p = &mem[sysVARSTART];
*(uint16_t *)p = bytesNeeded;
p += 2;
*p++ = VAR_TYPE_FORNEXT;
strcpy((char*)p, name);
p += nameLen + 1;
*(float *)p = start;
p += sizeof(float);
*(float *)p = step;
p += sizeof(float);
*(float *)p = end;
p += sizeof(float);
*(uint16_t *)p = lineNum;
p += sizeof(uint16_t);
*(uint16_t *)p = stmtNum;
return 1;
}
int storeStrVariable(char *name, char *val) {
int nameLen = strlen(name);
int valLen = strlen(val);
int bytesNeeded = 3; // len + type
bytesNeeded += nameLen + 1; // name
bytesNeeded += valLen + 1; // val
// strings and arrays are re-allocated if they already exist
unsigned char *p = findVariable(name, VAR_TYPE_STRING);
if (p != NULL) {
// check there will actually be room for the new value
uint16_t oldVarLen = *(uint16_t*)p;
if (sysVARSTART - (bytesNeeded - oldVarLen) < sysSTACKEND)
return 0; // not enough memory
deleteVariableAt(p);
}
if (sysVARSTART - bytesNeeded < sysSTACKEND)
return 0; // out of memory
sysVARSTART -= bytesNeeded;
p = &mem[sysVARSTART];
*(uint16_t *)p = bytesNeeded;
p += 2;
*p++ = VAR_TYPE_STRING;
strcpy((char*)p, name);
p += nameLen + 1;
strcpy((char*)p, val);
return 1;
}
int createArray(char *name, int isString) {
// dimensions and number of dimensions on the calculator stack
int nameLen = strlen(name);
int bytesNeeded = 3; // len + flags
bytesNeeded += nameLen + 1; // name
bytesNeeded += 2; // num dims
int numElements = 1;
int i = 0;
int numDims = (int)stackPopNum();
// keep the current stack position, since we'll need to pop these values again
int oldSTACKEND = sysSTACKEND;
for (int i=0; i<numDims; i++) {
int dim = (int)stackPopNum();
numElements *= dim;
}
bytesNeeded += 2 * numDims + (isString ? 1 : sizeof(float)) * numElements;
// strings and arrays are re-allocated if they already exist
unsigned char *p = findVariable(name, (isString ? VAR_TYPE_STR_ARRAY : VAR_TYPE_NUM_ARRAY));
if (p != NULL) {
// check there will actually be room for the new value
uint16_t oldVarLen = *(uint16_t*)p;
if (sysVARSTART - (bytesNeeded - oldVarLen) < sysSTACKEND)
return 0; // not enough memory
deleteVariableAt(p);
}
if (sysVARSTART - bytesNeeded < sysSTACKEND)
return 0; // out of memory
sysVARSTART -= bytesNeeded;
p = &mem[sysVARSTART];
*(uint16_t *)p = bytesNeeded;
p += 2;
*p++ = (isString ? VAR_TYPE_STR_ARRAY : VAR_TYPE_NUM_ARRAY);
strcpy((char*)p, name);
p += nameLen + 1;
*(uint16_t *)p = numDims;
p += 2;
sysSTACKEND = oldSTACKEND;
for (int i=0; i<numDims; i++) {
int dim = (int)stackPopNum();
*(uint16_t *)p = dim;
p += 2;
}
memset(p, 0, numElements * (isString ? 1 : sizeof(float)));
return 1;
}
int _getArrayElemOffset(unsigned char **p, int *pOffset) {
// check for correct dimensionality
int numArrayDims = *(uint16_t*)*p;
*p+=2;
int numDimsGiven = (int)stackPopNum();
if (numArrayDims != numDimsGiven)
return ERROR_WRONG_ARRAY_DIMENSIONS;
// now lookup the element
int offset = 0;
int base = 1;
for (int i=0; i<numArrayDims; i++) {
int index = (int)stackPopNum();
int arrayDim = *(uint16_t*)*p;
*p+=2;
if (index < 1 || index > arrayDim)
return ERROR_ARRAY_SUBSCRIPT_OUT_RANGE;
offset += base * (index-1);
base *= arrayDim;
}
*pOffset = offset;
return 0;
}
int setNumArrayElem(char *name, float val) {
// each index and number of dimensions on the calculator stack
unsigned char *p = findVariable(name, VAR_TYPE_NUM_ARRAY);
if (p == NULL)
return ERROR_VARIABLE_NOT_FOUND;
p += 3 + strlen(name) + 1;
int offset;
int ret = _getArrayElemOffset(&p, &offset);
if (ret) return ret;
p += sizeof(float)*offset;
*(float *)p = val;
return ERROR_NONE;
}
int setStrArrayElem(char *name) {
// string is top of the stack
// each index and number of dimensions on the calculator stack
// keep the current stack position, since we can't overwrite the value string
int oldSTACKEND = sysSTACKEND;
// how long is the new value?
char *newValPtr = stackPopStr();
int newValLen = strlen(newValPtr);
unsigned char *p = findVariable(name, VAR_TYPE_STR_ARRAY);
unsigned char *p1 = p; // so we can correct the length when done
if (p == NULL)
return ERROR_VARIABLE_NOT_FOUND;
p += 3 + strlen(name) + 1;
int offset;
int ret = _getArrayElemOffset(&p, &offset);
if (ret) return ret;
// find the correct element by skipping over null terminators
int i = 0;
while (i < offset) {
if (*p == 0) i++;
p++;
}
int oldValLen = strlen((char*)p);
int bytesNeeded = newValLen - oldValLen;
// check if we've got enough room for the new value
if (sysVARSTART - bytesNeeded < oldSTACKEND)
return 0; // out of memory
// correct the length of the variable
*(uint16_t*)p1 += bytesNeeded;
memmove(&mem[sysVARSTART - bytesNeeded], &mem[sysVARSTART], p - &mem[sysVARSTART]);
// copy in the new value
strcpy((char*)(p - bytesNeeded), newValPtr);
sysVARSTART -= bytesNeeded;
return ERROR_NONE;
}
float lookupNumArrayElem(char *name, int *error) {
// each index and number of dimensions on the calculator stack
unsigned char *p = findVariable(name, VAR_TYPE_NUM_ARRAY);
if (p == NULL) {
*error = ERROR_VARIABLE_NOT_FOUND;
return 0.0f;
}
p += 3 + strlen(name) + 1;
int offset;
int ret = _getArrayElemOffset(&p, &offset);
if (ret) {
*error = ret;
return 0.0f;
}
p += sizeof(float)*offset;
return *(float *)p;
}
char *lookupStrArrayElem(char *name, int *error) {
// each index and number of dimensions on the calculator stack
unsigned char *p = findVariable(name, VAR_TYPE_STR_ARRAY);
if (p == NULL) {
*error = ERROR_VARIABLE_NOT_FOUND;
return NULL;
}
p += 3 + strlen(name) + 1;
int offset;
int ret = _getArrayElemOffset(&p, &offset);
if (ret) {
*error = ret;
return NULL;
}
// find the correct element by skipping over null terminators
int i = 0;
while (i < offset) {
if (*p == 0) i++;
p++;
}
return (char *)p;
}
float lookupNumVariable(char *name) {
unsigned char *p = findVariable(name, VAR_TYPE_NUM|VAR_TYPE_FORNEXT);
if (p == NULL) {
return FLT_MAX;
}
p += 3 + strlen(name) + 1;
return *(float *)p;
}
char *lookupStrVariable(char *name) {
unsigned char *p = findVariable(name, VAR_TYPE_STRING);
if (p == NULL) {
return NULL;
}
p += 3 + strlen(name) + 1;
return (char *)p;
}
ForNextData lookupForNextVariable(char *name) {
ForNextData ret;
unsigned char *p = findVariable(name, VAR_TYPE_NUM|VAR_TYPE_FORNEXT);
if (p == NULL)
ret.val = FLT_MAX;
else if (*(p+2) != VAR_TYPE_FORNEXT)
ret.step = FLT_MAX;
else {
p += 3 + strlen(name) + 1;
ret.val = *(float *)p;
p += sizeof(float);
ret.step = *(float *)p;
p += sizeof(float);
ret.end = *(float *)p;
p += sizeof(float);
ret.lineNumber = *(uint16_t *)p;
p += sizeof(uint16_t);
ret.stmtNumber = *(uint16_t *)p;
}
return ret;
}
/* **************************************************************************
* GOSUB STACK
* **************************************************************************/
// gosub stack (if used) is after the variables
int gosubStackPush(int lineNumber,int stmtNumber) {
int bytesNeeded = 2 * sizeof(uint16_t);
if (sysVARSTART - bytesNeeded < sysSTACKEND)
return 0; // out of memory
// shift the variable table
memmove(&mem[sysVARSTART]-bytesNeeded, &mem[sysVARSTART], sysVAREND-sysVARSTART);
sysVARSTART -= bytesNeeded;
sysVAREND -= bytesNeeded;
// push the return address
sysGOSUBSTART = sysVAREND;
uint16_t *p = (uint16_t*)&mem[sysGOSUBSTART];
*p++ = (uint16_t)lineNumber;
*p = (uint16_t)stmtNumber;
return 1;
}
int gosubStackPop(int *lineNumber, int *stmtNumber) {
if (sysGOSUBSTART == sysGOSUBEND)
return 0;
uint16_t *p = (uint16_t*)&mem[sysGOSUBSTART];
*lineNumber = (int)*p++;
*stmtNumber = (int)*p;
int bytesFreed = 2 * sizeof(uint16_t);
// shift the variable table
memmove(&mem[sysVARSTART]+bytesFreed, &mem[sysVARSTART], sysVAREND-sysVARSTART);
sysVARSTART += bytesFreed;
sysVAREND += bytesFreed;
sysGOSUBSTART = sysVAREND;
return 1;
}
/* **************************************************************************
* LEXER
* **************************************************************************/
static unsigned char *tokenIn, *tokenOut;
static int tokenOutLeft;
// nextToken returns -1 for end of input, 0 for success, +ve number = error code
int nextToken()
{
// Skip any whitespace.
while (isspace(*tokenIn))
tokenIn++;
// check for end of line
if (*tokenIn == 0) {
*tokenOut++ = TOKEN_EOL;
tokenOutLeft--;
return -1;
}
// Number: [0-9.]+
// TODO - handle 1e4 etc
if (isdigit(*tokenIn) || *tokenIn == '.') { // Number: [0-9.]+
int gotDecimal = 0;
char numStr[MAX_NUMBER_LEN+1];
int numLen = 0;
do {
if (numLen == MAX_NUMBER_LEN) return ERROR_LEXER_BAD_NUM;
if (*tokenIn == '.') {
if (gotDecimal) return ERROR_LEXER_BAD_NUM;
else gotDecimal = 1;
}
numStr[numLen++] = *tokenIn++;
}
while (isdigit(*tokenIn) || *tokenIn == '.');
numStr[numLen] = 0;
if (tokenOutLeft <= 5) return ERROR_LEXER_TOO_LONG;
tokenOutLeft -= 5;
if (!gotDecimal) {
long val = strtol(numStr, 0, 10);
if (val == LONG_MAX || val == LONG_MIN)
gotDecimal = true;
else {
*tokenOut++ = TOKEN_INTEGER;
*(long*)tokenOut = (long)val;
tokenOut += sizeof(long);
}
}
if (gotDecimal)
{
*tokenOut++ = TOKEN_NUMBER;
*(float*)tokenOut = (float)strtod(numStr, 0);
tokenOut += sizeof(float);
}
return 0;
}
// identifier: [a-zA-Z][a-zA-Z0-9]*[$]
if (isalpha(*tokenIn)) {
char identStr[MAX_IDENT_LEN+1];
int identLen = 0;
identStr[identLen++] = *tokenIn++; // copy first char
while (isalnum(*tokenIn) || *tokenIn=='$') {
if (identLen < MAX_IDENT_LEN)
identStr[identLen++] = *tokenIn;
tokenIn++;
}
identStr[identLen] = 0;
// check to see if this is a keyword
for (int i = FIRST_IDENT_TOKEN; i <= LAST_IDENT_TOKEN; i++) {
if (strcasecmp(identStr, (char *)pgm_read_word(&tokenTable[i].token)) == 0) {
if (tokenOutLeft <= 1) return ERROR_LEXER_TOO_LONG;
tokenOutLeft--;
*tokenOut++ = i;
// special case for REM
if (i == TOKEN_REM) {
*tokenOut++ = TOKEN_STRING;
// skip whitespace
while (isspace(*tokenIn))
tokenIn++;
// copy the comment
while (*tokenIn) {
*tokenOut++ = *tokenIn++;
}
*tokenOut++ = 0;
}
return 0;
}
}
// no matching keyword - this must be an identifier
// $ is only allowed at the end
char *dollarPos = strchr(identStr, '$');
if (dollarPos && dollarPos!= &identStr[0] + identLen - 1) return ERROR_LEXER_UNEXPECTED_INPUT;
if (tokenOutLeft <= 1+identLen) return ERROR_LEXER_TOO_LONG;
tokenOutLeft -= 1+identLen;
*tokenOut++ = TOKEN_IDENT;
strcpy((char*)tokenOut, identStr);
tokenOut[identLen-1] |= 0x80;
tokenOut += identLen;
return 0;
}
// string
if (*tokenIn=='\"') {
*tokenOut++ = TOKEN_STRING;
tokenOutLeft--;
if (tokenOutLeft <= 1) return ERROR_LEXER_TOO_LONG;
tokenIn++;
while (*tokenIn) {
if (*tokenIn == '\"' && *(tokenIn+1) != '\"')
break;
else if (*tokenIn == '\"')
tokenIn++;
*tokenOut++ = *tokenIn++;
tokenOutLeft--;
if (tokenOutLeft <= 1) return ERROR_LEXER_TOO_LONG;
}
if (!*tokenIn) return ERROR_LEXER_UNTERMINATED_STRING;
tokenIn++;
*tokenOut++ = 0;
tokenOutLeft--;
return 0;
}
// handle non-alpha tokens e.g. =
for (int i=LAST_NON_ALPHA_TOKEN; i>=FIRST_NON_ALPHA_TOKEN; i--) {
// do this "backwards" so we match >= correctly, not as > then =
int len = strlen((char *)pgm_read_word(&tokenTable[i].token));
if (strncmp((char *)pgm_read_word(&tokenTable[i].token), (char*)tokenIn, len) == 0) {
if (tokenOutLeft <= 1) return ERROR_LEXER_TOO_LONG;
*tokenOut++ = i;
tokenOutLeft--;
tokenIn += len;
return 0;
}
}
return ERROR_LEXER_UNEXPECTED_INPUT;
}
int tokenize(unsigned char *input, unsigned char *output, int outputSize)
{
tokenIn = input;
tokenOut = output;
tokenOutLeft = outputSize;
int ret;
while (1) {
ret = nextToken();
if (ret) break;
}
return (ret > 0) ? ret : 0;
}
/* **************************************************************************
* PARSER / INTERPRETER
* **************************************************************************/
static char executeMode; // 0 = syntax check only, 1 = execute
uint16_t lineNumber, stmtNumber;
// stmt number is 0 for the first statement, then increases after each command seperator (:)
// Note that IF a=1 THEN PRINT "x": print "y" is considered to be only 2 statements
static uint16_t jumpLineNumber, jumpStmtNumber;
static uint16_t stopLineNumber, stopStmtNumber;
static char breakCurrentLine;
static unsigned char *tokenBuffer, *prevToken;
static int curToken;
static char identVal[MAX_IDENT_LEN+1];
static char isStrIdent;
static float numVal;
static char *strVal;
static long numIntVal;
int getNextToken()
{
prevToken = tokenBuffer;
curToken = *tokenBuffer++;
if (curToken == TOKEN_IDENT) {
int i=0;
while (*tokenBuffer < 0x80)
identVal[i++] = *tokenBuffer++;
identVal[i] = (*tokenBuffer++)-0x80;
isStrIdent = (identVal[i++] == '$');
identVal[i++] = '\0';
}
else if (curToken == TOKEN_NUMBER) {
numVal = *(float*)tokenBuffer;
tokenBuffer += sizeof(float);
}
else if (curToken == TOKEN_INTEGER) {
// these are really just for line numbers
numVal = (float)(*(long*)tokenBuffer);
tokenBuffer += sizeof(long);
}
else if (curToken == TOKEN_STRING) {
strVal = (char*)tokenBuffer;
tokenBuffer += 1 + strlen(strVal);
}
return curToken;
}
// value (int) returned from parseXXXXX
#define ERROR_MASK 0x0FFF
#define TYPE_MASK 0xF000
#define TYPE_NUMBER 0x0000
#define TYPE_STRING 0x1000
#define IS_TYPE_NUM(x) ((x & TYPE_MASK) == TYPE_NUMBER)
#define IS_TYPE_STR(x) ((x & TYPE_MASK) == TYPE_STRING)
// forward declarations
int parseExpression();
int parsePrimary();
int expectNumber();
// parse a number
int parseNumberExpr()
{
if (executeMode && !stackPushNum(numVal))
return ERROR_OUT_OF_MEMORY;
getNextToken(); // consume the number
return TYPE_NUMBER;
}
// parse (x1,....xn) e.g. DIM a(10,20)
int parseSubscriptExpr() {
// stacks x1, .. xn followed by n
int numDims = 0;
if (curToken != TOKEN_LBRACKET) return ERROR_EXPR_MISSING_BRACKET;
getNextToken();
while(1) {
numDims++;
int val = expectNumber();
if (val) return val; // error
if (curToken == TOKEN_RBRACKET)
break;
else if (curToken == TOKEN_COMMA)
getNextToken();
else
return ERROR_EXPR_MISSING_BRACKET;
}
getNextToken(); // eat )
if (executeMode && !stackPushNum(numDims))
return ERROR_OUT_OF_MEMORY;
return 0;
}