forked from wled/WLED
-
-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy patharti.h
More file actions
2781 lines (2405 loc) · 101 KB
/
arti.h
File metadata and controls
2781 lines (2405 loc) · 101 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
/*
@title Arduino Real Time Interpreter (ARTI)
@file arti.h
@date 20220818
@author Ewoud Wijma
@Copyright (c) 2024 Ewoud Wijma
@repo https://github.com/ewoudwijma/ARTI
@remarks
- #define ARDUINOJSON_DEFAULT_NESTING_LIMIT 100 //set this in ArduinoJson!!!, currently not necessary...
- IF UPDATING THIS FILE IN THE WLED REPO, SEND A PULL REQUEST TO https://github.com/ewoudwijma/ARTI AS WELL!!!
@later
- Code improvement
- See 'for some weird reason this causes a crash on esp32'
- check why column/lineno not correct
- Definition improvements
- support string (e.g. for print)
- add integer and string stacks
- print every x seconds (to use it in loops. e.g. to show free memory)
- reserved words (ext functions and variables cannot be used as variables)
- check on return values
- arrays (indices) for varref
- WLED improvements
- rename program to sketch?
@progress
- SetPixelColor without colorwheel
- extend errorOccurred and add warnings (continue) next to errors (stop). Include stack full/empty
- WLED: *arti in SEGENV.data: not working well as change mode will free(data)
- move code from interpreter to analyzer to speed up interpreting
@done?
@done
- save log after first run of loop to get runtime errors included (or 30 iterations to also capture any stack overflows)
@todo
- check why statement is not 'shrinked'
- make default work in js (remove default as we have now load template)
- add PI
- color_fade_pulse because /pixelCount instead of ledCount should not crash
*/
#pragma once
#define ARTI_SERIAL 1
#define ARTI_FILE 2
#if ARTI_PLATFORM == ARTI_ARDUINO //defined in arti_definition.h e.g. arti_wled.h!
#include "../../wled00/wled.h"
#include "../../wled00/src/dependencies/json/ArduinoJson-v6.h"
File logFile;
#define ARTI_ERRORWARNING 1 //shows lexer, parser, analyzer and interpreter errors
// #define ARTI_DEBUG 1
// #define ARTI_ANDBG 1
// #define ARTI_RUNLOG 1 //if set on arduino this will create massive amounts of output (as ran in a loop)
#define ARTI_MEMORY 1 //to do analyses of memory usage, trace memoryleaks (works only on arduino)
#define ARTI_PRINT 1 //will show the printf calls
const char spaces[51] PROGMEM = " ";
#if defined(ARDUINO_ARCH_ESP32)
#define FREE_SIZE esp_get_free_heap_size()
#define asChar(x) x.as<std::string>().c_str() //WLEDMM: tbd: find out why char * is causing crashes!!!
#else
#define FREE_SIZE ESP.getFreeHeap()
#define asChar(x) ""
//x.as<const char *>() //WLEDMM: no arduinojson output for the moment as this is in testing phase
#endif
// #define OPTIMIZED_TREE 1
#else //embedded
#include "dependencies/ArduinoJson-recent.h"
FILE * logFile; // FILE needed to use in fprintf (std stream does not work)
#define ARTI_ERRORWARNING 1
#define ARTI_DEBUG 1
#define ARTI_ANDBG 1
#define ARTI_RUNLOG 1
#define ARTI_MEMORY 1
#define ARTI_PRINT 1
#include <math.h>
#include <iostream>
#include <fstream>
#include <sstream>
const char spaces[51] = " ";
#define FREE_SIZE (unsigned int)0 //No free heap function found on embedded
#define asChar(x) x.as<const char *>()
// #define OPTIMIZED_TREE 1
#endif
bool logToFile = true; //print output to file (e.g. default.wled.log)
uint32_t frameCounter = 0; //tbd move to class if more instances run
void artiPrintf(char const * format, ...)
{
va_list argp;
va_start(argp, format);
// if (!logToFile)
// {
// //WLEDMM: not working to use USER_PRINTF here in case of arduino so moving to rocket science part
// vprintf(format, argp);
// }
// else
#if ARTI_PLATFORM == ARTI_ARDUINO
// rocket science here! As logfile.printf causes crashes/wrong output we create our own printf here
// logFile.printf(format, argp);
for (size_t i = 0; i < strlen(format); i++)
{
if (format[i] == '%')
{
switch (format[i+1])
{
case 's':
if (logToFile) logFile.print(va_arg(argp, const char *)); else USER_PRINT(va_arg(argp, const char *));
break;
case 'u':
if (logToFile) logFile.print(va_arg(argp, unsigned int)); else USER_PRINT(va_arg(argp, unsigned int));
break;
case 'c':
if (logToFile) logFile.print((char)va_arg(argp, int)); else USER_PRINT(va_arg(argp, int));
break;
case 'f':
if (logToFile) logFile.print(va_arg(argp, double)); else USER_PRINT(va_arg(argp, double));
break;
case '%':
if (logToFile) logFile.print("%"); else USER_PRINT("%"); // in case of %%
break;
default:
va_arg(argp, int);
// logFile.print(x);
if (logToFile) logFile.print(format[i]); else USER_PRINT(format[i]);
if (logToFile) logFile.print(format[i+1]); else USER_PRINT(format[i+1]);
}
i++;
}
else
{
if (logToFile) logFile.print(format[i]); else USER_PRINT(format[i]);
}
}
#else
vfprintf(logFile, format, argp);
#endif
va_end(argp);
}
//add millis function for non arduino
#if ARTI_PLATFORM != ARTI_ARDUINO
uint32_t millis()
{
return std::chrono::system_clock::now().time_since_epoch().count();
}
#endif
#ifdef ARTI_DEBUG
#define DEBUG_ARTI(...) artiPrintf(__VA_ARGS__)
#else
#define DEBUG_ARTI(...)
#endif
#ifdef ARTI_ANDBG
#define ANDBG_ARTI(...) artiPrintf(__VA_ARGS__)
#else
#define ANDBG_ARTI(...)
#endif
#ifdef ARTI_RUNLOG
#define RUNLOG_ARTI(...) artiPrintf(__VA_ARGS__)
#else
#define RUNLOG_ARTI(...)
#endif
#ifdef ARTI_PRINT
#define PRINT_ARTI(...) artiPrintf(__VA_ARGS__)
#else
#define PRINT_ARTI(...)
#endif
#ifdef ARTI_ERRORWARNING
#define ERROR_ARTI(...) artiPrintf(__VA_ARGS__)
#define WARNING_ARTI(...) artiPrintf(__VA_ARGS__)
#else
#define ERROR_ARTI(...)
#define WARNING_ARTI(...)
#endif
#ifdef ARTI_MEMORY
#define MEMORY_ARTI(...) artiPrintf(__VA_ARGS__)
#else
#define MEMORY_ARTI(...)
#endif
#define charLength 30
#define fileNameLength 50
#define arrayLength 30
#define floatNull -32768
const char * stringOrEmpty(const char *charS) {
if (charS == nullptr)
return "";
else
return charS;
}
//define strupr as only supported in windows toolchain
char* strupr(char* s)
{
char* tmp = s;
for (;*tmp;++tmp) {
*tmp = toupper((unsigned char) *tmp);
}
return s;
}
enum Tokens
{
F_integerConstant,
F_realConstant,
F_plus,
F_minus,
F_multiplication,
F_division,
F_modulo,
F_bitShiftLeft,
F_bitShiftRight,
F_equal,
F_notEqual,
F_lessThen,
F_lessThenOrEqual,
F_greaterThen,
F_greaterThenOrEqual,
F_and,
F_or,
F_plusplus,
F_minmin,
F_NoToken = 255
};
const char * tokenToString(uint8_t key)
{
switch (key) {
case F_integerConstant:
return "integer";
break;
case F_realConstant:
return "real";
break;
case F_plus:
return "+";
break;
case F_minus:
return "-";
break;
case F_multiplication:
return "*";
break;
case F_division:
return "/";
break;
case F_modulo:
return "%";
break;
case F_bitShiftLeft:
return "<<";
break;
case F_bitShiftRight:
return ">>";
break;
case F_equal:
return "==";
break;
case F_notEqual:
return "!=";
break;
case F_lessThen:
return "<";
break;
case F_lessThenOrEqual:
return "<=";
break;
case F_greaterThen:
return ">";
break;
case F_greaterThenOrEqual:
return ">=";
break;
case F_and:
return "&&";
break;
case F_or:
return "||";
break;
case F_plusplus:
return "++";
break;
case F_minmin:
return "--";
break;
}
return "unknown key";
}
uint8_t stringToToken(const char * token, const char * value)
{
if (strcmp(token, "INTEGER_CONST") == 0)
return F_integerConstant;
else if (strcmp(token, "REAL_CONST") == 0)
return F_realConstant;
else if (strcmp(value, "+") == 0)
return F_plus;
else if (strcmp(value, "-") == 0)
return F_minus;
else if (strcmp(value, "*") == 0)
return F_multiplication;
else if (strcmp(value, "/") == 0)
return F_division;
else if (strcmp(value, "%") == 0)
return F_modulo;
else if (strcmp(value, "<<") == 0)
return F_bitShiftLeft;
else if (strcmp(value, ">>") == 0)
return F_bitShiftRight;
else if (strcmp(value, "==") == 0)
return F_equal;
else if (strcmp(value, "!=") == 0)
return F_notEqual;
else if (strcmp(value, ">") == 0)
return F_greaterThen;
else if (strcmp(value, ">=") == 0)
return F_greaterThenOrEqual;
else if (strcmp(value, "<") == 0)
return F_lessThen;
else if (strcmp(value, "<=") == 0)
return F_lessThenOrEqual;
else if (strcmp(value, "&&") == 0)
return F_and;
else if (strcmp(value, "||") == 0)
return F_or;
else if (strcmp(value, "+=") == 0)
return F_plus;
else if (strcmp(value, "-=") == 0)
return F_minus;
else if (strcmp(value, "*=") == 0)
return F_multiplication;
else if (strcmp(value, "/=") == 0)
return F_division;
else if (strcmp(value, "++") == 0)
return F_plusplus;
else if (strcmp(value, "--") == 0)
return F_minmin;
else
return F_NoToken;
}
enum Nodes
{
F_Program,
F_Function,
F_Call,
F_VarDef,
F_Assign,
F_Formal,
F_VarRef,
F_For,
F_If,
F_Cex,
F_Expr,
F_Term,
#ifdef OPTIMIZED_TREE
F_Statement,
F_Indices,
F_Formals,
F_Factor,
F_Block,
F_Actuals,
F_Increment,
F_AssignOperator,
#endif
F_NoNode = 255
};
//Tokens
// ID
//Optimizer
// level
// index
// external
// block
// formals
// actuals
// increment
// assignoperator
// type (not used yet in wled)
//expr
//indices
const char * nodeToString(uint8_t key)
{
switch (key) {
case F_Program:
return "program";
case F_Function:
return "function";
case F_Call:
return "call";
case F_VarDef:
return "variable";
case F_Assign:
return "assign";
case F_Formal:
return "formal";
case F_VarRef:
return "varref";
case F_For:
return "for";
case F_If:
return "if";
case F_Cex:
return "cex";
case F_Expr:
return "expr";
case F_Term:
return "term";
#ifdef OPTIMIZED_TREEX
case F_Statement:
return "statement";
case F_Indices:
return "indices";
case F_Formals:
return "formals";
case F_Factor:
return "factor";
case F_Block:
return "block";
case F_Actuals:
return "actuals";
#endif
}
return "unknown key";
}
uint8_t stringToNode(const char * node)
{
if (strcmp(node, "program") == 0)
return F_Program;
else if (strcmp(node, "function") == 0)
return F_Function;
else if (strcmp(node, "call") == 0)
return F_Call;
else if (strcmp(node, "variable") == 0)
return F_VarDef;
else if (strcmp(node, "assign") == 0)
return F_Assign;
else if (strcmp(node, "formal") == 0)
return F_Formal;
else if (strcmp(node, "varref") == 0)
return F_VarRef;
else if (strcmp(node, "for") == 0)
return F_For;
else if (strcmp(node, "if") == 0)
return F_If;
else if (strcmp(node, "cex") == 0)
return F_Cex;
else if (strcmp(node, "expr") == 0)
return F_Expr;
else if (strcmp(node, "term") == 0)
return F_Term;
#ifdef OPTIMIZED_TREE
else if (strcmp(node, "statement") == 0)
return F_Statement;
else if (strcmp(node, "indices") == 0)
return F_Indices;
else if (strcmp(node, "formals") == 0)
return F_Formals;
else if (strcmp(node, "factor") == 0)
return F_Factor;
else if (strcmp(node, "block") == 0)
return F_Block;
else if (strcmp(node, "actuals") == 0)
return F_Actuals;
else if (strcmp(node, "increment") == 0)
return F_Increment;
else if (strcmp(node, "assignoperator") == 0)
return F_AssignOperator;
#endif
return F_NoNode;
}
bool errorOccurred = false;
struct Token {
uint16_t lineno;
uint16_t column;
char type[charLength];
char value[charLength];
};
struct LexerPosition {
uint16_t pos;
char current_char;
uint16_t lineno;
uint16_t column;
char type[charLength];
char value[charLength];
};
#define nrOfPositions 20
class Lexer {
private:
public:
const char * text;
uint16_t pos;
char current_char;
uint16_t lineno;
uint16_t column;
JsonObject definitionJson;
Token current_token;
LexerPosition positions[nrOfPositions]; //should be array of pointers but for some reason get seg fault (because a struct and not a class...)
uint8_t positions_index = 0;
Lexer(const char * programText, JsonObject definitionJson) {
this->text = programText;
this->definitionJson = definitionJson;
this->pos = 0;
this->current_char = this->text[this->pos];
this->lineno = 1;
this->column = 1;
}
~Lexer() {
DEBUG_ARTI("Destruct Lexer\n");
}
void advance() {
if (this->current_char == '\n')
{
this->lineno += 1;
this->column = 0;
}
this->pos++;
if (this->pos > strlen(this->text) - 1)
this->current_char = -1;
else
{
this->current_char = this->text[this->pos];
this->column++;
}
}
void skip_whitespace()
{
while (this->current_char != -1 && isspace(this->current_char))
this->advance();
}
void skip_comment(const char * endTokens)
{
while (strncmp(this->text + this->pos, endTokens, strlen(endTokens)) != 0)
this->advance();
for (size_t i=0; i<strlen(endTokens); i++)
this->advance();
}
void number()
{
current_token.lineno = this->lineno;
current_token.column = this->column;
strcpy(current_token.type, "");
strcpy(current_token.value, "");
char result[charLength] = "";
while (this->current_char != -1 && isdigit(this->current_char))
{
result[strlen(result)] = this->current_char;
this->advance();
}
if (this->current_char == '.')
{
result[strlen(result)] = this->current_char;
this->advance();
while (this->current_char != -1 && isdigit(this->current_char))
{
result[strlen(result)] = this->current_char;
this->advance();
}
result[strlen(result)] = '\0';
strcpy(current_token.type, "REAL_CONST");
strcpy(current_token.value, result);
}
else
{
result[strlen(result)] = '\0';
strcpy(current_token.type, "INTEGER_CONST");
strcpy(current_token.value, result);
}
}
void id()
{
current_token.lineno = this->lineno;
current_token.column = this->column;
strcpy(current_token.type, "");
strcpy(current_token.value, "");
char result[charLength] = "";
while (this->current_char != -1 && (isalnum(this->current_char) || this->current_char == '_'))
{
result[strlen(result)] = this->current_char;
this->advance();
}
result[strlen(result)] = '\0';
char resultUpper[charLength];
strcpy(resultUpper, result);
strupr(resultUpper);
if (definitionJson["TOKENS"].containsKey(resultUpper))
{
strcpy(current_token.type, definitionJson["TOKENS"][resultUpper]);
strcpy(current_token.value, resultUpper);
}
else
{
strcpy(current_token.type, "ID");
strcpy(current_token.value, result);
}
}
void get_next_token()
{
current_token.lineno = this->lineno;
current_token.column = this->column;
strcpy(current_token.type, "");
strcpy(current_token.value, "");
if (errorOccurred) return;
while (this->current_char != -1 && this->pos <= strlen(this->text) - 1 && !errorOccurred)
{
if (isspace(this->current_char)) {
this->skip_whitespace();
continue;
}
if (strncmp(this->text + this->pos, "/*", 2) == 0)
{
this->advance();
skip_comment("*/");
continue;
}
if (strncmp(this->text + this->pos, "//", 2) == 0)
{
this->advance();
skip_comment("\n");
continue;
}
if (isalpha(this->current_char))
{
this->id();
return;
}
if (isdigit(this->current_char) || (this->current_char == '.' && isdigit(this->text[this->pos+1])))
{
this->number();
return;
}
// findLongestMatchingToken
char token_type[charLength] = "";
char token_value[charLength] = "";
uint8_t longestTokenLength = 0;
for (JsonPair tokenPair: definitionJson["TOKENS"].as<JsonObject>()) {
const char * value = tokenPair.value();
char currentValue[charLength+1];
strncpy(currentValue, this->text + this->pos, charLength);
currentValue[strlen(value)] = '\0';
if (strcmp(value, currentValue) == 0 && strlen(value) > longestTokenLength) {
strcpy(token_type, tokenPair.key().c_str());
strcpy(token_value, value);
longestTokenLength = strlen(value);
}
}
if (strcmp(token_type, "") != 0 && strcmp(token_value, "") != 0)
{
strcpy(current_token.type, token_type);
strcpy(current_token.value, token_value);
for (size_t i=0; i<strlen(token_value); i++)
this->advance();
return;
}
else {
ERROR_ARTI("Lexer error on %c line %u col %u\n", this->current_char, this->lineno, this->column);
errorOccurred = true;
}
}
} //get_next_token
void eat(const char * token_type) {
// DEBUG_ARTI("try to eat %s %s\n", lexer->current_token.type, token_type);
if (strcmp(current_token.type, token_type) == 0) {
get_next_token();
// DEBUG_ARTI("eating %s -> %s %s\n", token_type, lexer->current_token.type, lexer->current_token.value);
}
else {
ERROR_ARTI("Lexer Error: Unexpected token %s %s\n", current_token.type, current_token.value);
errorOccurred = true;
}
}
void push_position() {
if (positions_index < nrOfPositions) {
positions[positions_index].pos = this->pos;
positions[positions_index].current_char = this->current_char;
positions[positions_index].lineno = this->lineno;
positions[positions_index].column = this->column;
strcpy(positions[positions_index].type, current_token.type);
strcpy(positions[positions_index].value, current_token.value);
positions_index++;
}
else
ERROR_ARTI("not enough positions %u\n", nrOfPositions);
}
void pop_position() {
if (positions_index > 0) {
positions_index--;
this->pos = positions[positions_index].pos;
this->current_char = positions[positions_index].current_char;
this->lineno = positions[positions_index].lineno;
this->column = positions[positions_index].column;
strcpy(current_token.type, positions[positions_index].type);
strcpy(current_token.value, positions[positions_index].value);
}
else
ERROR_ARTI("no positions saved\n");
}
}; //Lexer
#define ResultFail 0
#define ResultStop 2
#define ResultContinue 1
class ScopedSymbolTable; //forward declaration
class Symbol {
private:
public:
uint8_t symbol_type;
char name[charLength];
uint8_t type;
uint8_t scope_level;
uint8_t scope_index;
ScopedSymbolTable* scope = nullptr;
ScopedSymbolTable* function_scope = nullptr; //used to find the formal parameters in the scope of a function node
JsonVariant block;
Symbol(uint8_t symbol_type, const char * name, uint8_t type = 9) {
this->symbol_type = symbol_type;
strcpy(this->name, name);
this->type = type;
this->scope_level = 0;
}
~Symbol() {
MEMORY_ARTI("Destruct Symbol %s (%u)\n", name, FREE_SIZE);
}
}; //Symbol
#define nrOfSymbolsPerScope 30
#define nrOfChildScope 10 //add checks
class ScopedSymbolTable {
private:
public:
Symbol* symbols[nrOfSymbolsPerScope];
uint8_t symbolsIndex = 0;
uint8_t nrOfFormals = 0;
char scope_name[charLength];
uint8_t scope_level;
ScopedSymbolTable *enclosing_scope;
ScopedSymbolTable *child_scopes[nrOfChildScope];
uint8_t child_scopesIndex = 0;
ScopedSymbolTable(const char * scope_name, int scope_level, ScopedSymbolTable *enclosing_scope = nullptr) {
strcpy(this->scope_name, scope_name);
this->scope_level = scope_level;
this->enclosing_scope = enclosing_scope;
}
~ScopedSymbolTable() {
for (uint8_t i=0; i<child_scopesIndex; i++) {
delete child_scopes[i]; child_scopes[i] = nullptr;
}
for (uint8_t i=0; i<symbolsIndex; i++) {
delete symbols[i]; symbols[i] = nullptr;
}
MEMORY_ARTI("Destruct ScopedSymbolTable %s (%u)\n", scope_name, FREE_SIZE);
}
void init_builtins() {
// this->insert(BuiltinTypeSymbol('INTEGER'));
// this->insert(BuiltinTypeSymbol('REAL'));
}
void insert(Symbol* symbol)
{
#ifdef _SHOULD_LOG_SCOPE
ANDBG_ARTI("Log scope Insert %s\n", symbol->name.c_str());
#endif
symbol->scope_level = this->scope_level;
symbol->scope = this;
symbol->scope_index = symbolsIndex;
if (symbolsIndex < nrOfSymbolsPerScope)
this->symbols[symbolsIndex++] = symbol;
else
ERROR_ARTI("ScopedSymbolTable %s symbols full (%d)", scope_name, nrOfSymbolsPerScope);
}
Symbol* lookup(const char * name, bool current_scope_only=false)
{
for (uint8_t i=0; i<symbolsIndex; i++) {
if (strcmp(symbols[i]->name, name) == 0)
return symbols[i];
}
if (current_scope_only)
return nullptr;
// # recursively go up the chain and lookup the name;
if (this->enclosing_scope != nullptr)
return this->enclosing_scope->lookup(name);
return nullptr;
} //lookup
}; //ScopedSymbolTable
#define nrOfVariables 20
class ActivationRecord
{
private:
public:
char name[charLength];
char type[charLength];
int nesting_level;
// char charMembers[charLength][nrOfVariables];
float floatMembers[nrOfVariables];
char lastSet[charLength];
uint8_t lastSetIndex;
ActivationRecord(const char * name, const char * type, int nesting_level)
{
strcpy(this->name, name);
strcpy(this->type, type);
this->nesting_level = nesting_level;
}
~ActivationRecord()
{
RUNLOG_ARTI("Destruct activation record %s\n", name);
}
// void set(uint8_t index, const char * value)
// {
// lastSetIndex = index;
// strcpy(charMembers[index], value);
// }
void set(uint8_t index, float value)
{
lastSetIndex = index;
floatMembers[index] = value;
}
// const char * getChar(uint8_t index)
// {
// return charMembers[index];
// }
float getFloat(uint8_t index)
{
return floatMembers[index];
}
}; //ActivationRecord
#define nrOfRecords 20
class CallStack {
public:
ActivationRecord* records[nrOfRecords];
uint8_t recordsCounter = 0;
CallStack() {
}
~CallStack()
{
RUNLOG_ARTI("Destruct callstack\n");
}
void push(ActivationRecord* ar)
{
if (recordsCounter < nrOfRecords)
{
// RUNLOG_ARTI("%s\n", "Push ", ar->name);
this->records[recordsCounter++] = ar;
}
else
{
errorOccurred = true;
ERROR_ARTI("no space left in callstack\n");
}
}
ActivationRecord* pop()
{
if (recordsCounter > 0)
{
// RUNLOG_ARTI("%s\n", "Pop ", this->peek()->name);
return this->records[recordsCounter--];
}
else
{
ERROR_ARTI("no ar left on callstack\n");
return nullptr;
}
}
ActivationRecord* peek()
{
return this->records[recordsCounter-1];
}
}; //CallStack
class ValueStack
{
private:
public:
// char charStack[arrayLength][charLength]; //currently only floatStack used.
float floatStack[arrayLength];
uint8_t stack_index = 0;
ValueStack()
{
}
~ValueStack()
{
RUNLOG_ARTI("Destruct valueStack\n");
}
// void push(const char * value) {
// if (stack_index >= arrayLength)
// ERROR_ARTI("Push charStack full %u of %u\n", stack_index, arrayLength);
// else if (value == nullptr) {
// strcpy(charStack[stack_index++], "empty");
// ERROR_ARTI("Push null pointer on float stack\n");
// }
// else
// // RUNLOG_ARTI("calc push %s %s\n", key, value);
// strcpy(charStack[stack_index++], value);
// }
void push(float value)
{
if (stack_index >= arrayLength)
{
ERROR_ARTI("Push floatStack full (check functions with result assigned) %u\n", arrayLength);
errorOccurred = true;
}
else if (value == floatNull)
ERROR_ARTI("Push null value on float stack\n");
else
// RUNLOG_ARTI("calc push %s %s\n", key, value);
floatStack[stack_index++] = value;