-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathXenonCode.hpp
More file actions
9662 lines (9201 loc) · 344 KB
/
XenonCode.hpp
File metadata and controls
9662 lines (9201 loc) · 344 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
#pragma once
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <vector>
#include <initializer_list>
#include <map>
#include <set>
#include <unordered_map>
#include <stack>
#include <cassert>
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <functional>
#include <cstring>
#include <utility>
#ifndef XC_NAMESPACE
#define XC_NAMESPACE XenonCode
#endif
namespace XC_NAMESPACE {
// Version
const int VERSION_MAJOR = 0; // Requires assembly compiled with the same major version
const int VERSION_MINOR = 1; // Requires assembly compiled with a version <= than interpreter's minor version
const int VERSION_PATCH = 0;
#pragma region Limitations/Settings // these are default values, may be overridden by the implementation
#ifndef XC_APP_NAME
#define XC_APP_NAME "DEFAULT_XC_APP" // MUST be set by the implementation
#endif
#ifndef XC_APP_VERSION
#define XC_APP_VERSION 1
#endif
#ifndef XC_PROGRAM_EXECUTABLE
#define XC_PROGRAM_EXECUTABLE "xc_program.bin"
#endif
#ifndef XC_MAX_TEXT_LENGTH
#define XC_MAX_TEXT_LENGTH 4096 // max number of chars in text variables (absolute maximum is 16M)
#endif
#ifndef XC_MAX_STORAGE_MEMORY_SIZE
#define XC_MAX_STORAGE_MEMORY_SIZE 100'000'000u // max storage memory size in bytes
#endif
#ifndef XC_MAX_ARRAY_SIZE
#define XC_MAX_ARRAY_SIZE 65535 // max number of elements in arrays (absolute maximum is 16M)
#endif
#ifndef XC_MAX_ROM_SIZE
#define XC_MAX_ROM_SIZE 0xFFFFFF // number of 32-bit words (absolute maximum is 16M)
#endif
#ifndef XC_TEXT_MEMORY_PENALTY
#define XC_TEXT_MEMORY_PENALTY 16 // memory usage multiplier for text variables
#endif
#ifndef XC_ARRAY_NUMERIC_MEMORY_PENALTY
#define XC_ARRAY_NUMERIC_MEMORY_PENALTY 32 // memory usage multiplier for an array of numbers
#endif
#ifndef XC_ARRAY_TEXT_MEMORY_PENALTY
#define XC_ARRAY_TEXT_MEMORY_PENALTY 512 // memory usage multiplier for an array of text
#endif
#ifndef XC_OBJECT_MEMORY_PENALTY
#define XC_OBJECT_MEMORY_PENALTY 16 // memory usage multiplier for objects
#endif
#ifndef XC_MAX_CALL_DEPTH
#define XC_MAX_CALL_DEPTH 16
#endif
#ifndef XC_RECURSIVE_MEMORY_PENALTY
#define XC_RECURSIVE_MEMORY_PENALTY 16
#endif
#pragma endregion
#pragma region Helper Functions
#define EPSILON_DOUBLE 0.0000001
inline static double step(double edge1, double edge2, double val) {
if (edge1 > edge2) {
if (val >= edge2 && val <= edge1) {
return 1.0;
}
} else {
if (val >= edge1 && val <= edge2) {
return 1.0;
}
}
return 0.0;
}
inline static double step(double edge, double val) {
if (val >= edge) {
return 1.0;
}
return 0.0;
}
inline static double smoothstep(double edge1, double edge2, double val) {
if (edge1 == edge2) return 0.0;
val = std::clamp((val - edge1) / (edge2 - edge1), 0.0, 1.0);
return val * val * val * (val * (val * 6 - 15) + 10);
}
inline static void strtolower(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){ return std::tolower(c); });
}
inline static void strtoupper(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){ return std::toupper(c); });
}
inline static size_t utf8length(const std::string& str) {
const size_t n = str.length();
const char* data = str.data();
// Check if ASCII-only using 8-byte scanning (faster even for short strings)
size_t i = 0;
uint64_t orAccum = 0;
for (; i + 8 <= n; i += 8) {
uint64_t chunk;
std::memcpy(&chunk, data + i, 8);
orAccum |= chunk;
}
for (; i < n; ++i) {
orAccum |= (unsigned char)data[i];
}
if ((orAccum & 0x8080808080808080ULL) == 0) {
return n;
}
// Count UTF-8 code points for non-ASCII strings
size_t len = 0;
for (i = 0; i < n; ++i) {
if ((data[i] & 0xC0) != 0x80) {
++len;
}
}
return len;
}
// Fast ASCII case conversion (avoids locale overhead of std::toupper/tolower)
inline static void asciiToUpper(std::string& str) {
for (char& c : str) {
if (c >= 'a' && c <= 'z') c -= 32;
}
}
inline static void asciiToLower(std::string& str) {
for (char& c : str) {
if (c >= 'A' && c <= 'Z') c += 32;
}
}
inline static std::string utf8substr(const std::string& str, size_t start, int length = -1) {
if (length < 0) {
length = utf8length(str) - start;
}
if (start == 0 && length == 0) {
return "";
}
size_t len = 0;
size_t i = 0;
for (; i < str.length(); ++i) {
if ((str[i] & 0xC0) != 0x80) {
if (len == start) {
break;
}
++len;
}
}
size_t j = i;
for (; j < str.length(); ++j) {
if ((str[j] & 0xC0) != 0x80) {
if (len == start + size_t(length)) {
break;
}
++len;
}
}
return str.substr(i, j-i);
}
inline static void utf8assign(std::string& str, size_t start, const std::string& substr) {
size_t substrLen = utf8length(substr);
size_t len = 0;
size_t i = 0;
for (; i < str.length(); ++i) {
if ((str[i] & 0xC0) != 0x80) {
if (len == start) {
break;
}
++len;
}
}
size_t j = i;
for (; j < str.length(); ++j) {
if ((str[j] & 0xC0) != 0x80) {
if (len == start + substrLen) {
break;
}
++len;
}
}
str.replace(i, j-i, substr);
}
#pragma endregion
#pragma region Errors
struct ParseError : public std::runtime_error {
using std::runtime_error::runtime_error;
ParseError(const std::string& pre, const std::string& word) : runtime_error(pre + " '" + word + "'") {}
ParseError(const std::string& pre, const std::string& word, const std::string& post) : runtime_error(pre + " '" + word + "' " + post) {}
};
struct CompileError : public std::runtime_error {
using std::runtime_error::runtime_error;
CompileError(const std::string& pre, const std::string& word) : runtime_error(pre + " '" + word + "'") {}
CompileError(const std::string& pre, const std::string& word, const std::string& post) : runtime_error(pre + " '" + word + "' " + post) {}
};
struct RuntimeError : public std::runtime_error {
using std::runtime_error::runtime_error;
};
#pragma endregion
#pragma region Parser
inline static bool isoperator(int c) {
switch (c) {
case '=':
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
case '>':
case '<':
case '&':
case '|':
case '!':
case '~':
case '?':
case '.':
case ':':
case ',':
return true;
default: return false;
}
}
inline static bool isalpha_(int c) {
return isalpha(c) || c == '_';
}
inline static bool isalnum_(int c) {
return isalnum(c) || c == '_';
}
// Converts a string to a double, if empty returns 0.0.
[[nodiscard]] inline static double ToDouble(const std::string& str) {
try {
return str.empty() ? 0.0 : std::stod(str);
}
catch (...) {
throw RuntimeError("Invalid text conversion to number");
}
}
// Converts a string to a float, if empty returns 0.0.
[[nodiscard]] inline static float ToFloat(const std::string& str) {
try {
return str.empty() ? 0.0f : std::stof(str);
}
catch (...) {
throw RuntimeError("Invalid text conversion to number");
}
}
// Convert a double to a string with fixed precision of 6, removing trailing zeros and the decimal point if it is the last character.
inline static std::string ToString(double value) {
auto str = std::to_string(value);
str.erase(str.find_last_not_of('0') + 1, std::string::npos);
str.erase(str.find_last_not_of('.') + 1, std::string::npos);
return str;
}
// Convert a double to a string with a given precision, removing trailing zeros and the decimal point if it is the last character.
inline static std::string ToStringHighPrecision(double value, int precision = 15) {
std::ostringstream oss;
oss << std::fixed << std::setprecision(precision) << value;
std::string str = oss.str();
str.erase(str.find_last_not_of('0') + 1, std::string::npos);
str.erase(str.find_last_not_of('.') + 1, std::string::npos);
return str;
}
inline static const int WORD_ENUM_FINAL_TYPE_START = 11;
inline static const int WORD_ENUM_OPERATOR_START = 101;
struct Word {
std::string word = "";
enum Type : int {
// Intermediate types
Empty = 0, // nothing or comment or \n
Invalid,
Tab, // \t
Expression, // ( )
Operator, // + - * / ++ -- ....
FileInfo, // will contain the name of the current file, for error handling purposes
// Final types starting here
Numeric = WORD_ENUM_FINAL_TYPE_START, // 0.0
Text, // ""
Varname, // $
Funcname, // @
Name, // any other alphanumeric word that starts with alpha
ExpressionBegin, // (
ExpressionEnd, // )
HashTag, // #
Void, // placeholder for operators with only two parameters
// Operators (by order of precedence)
TrailOperator = WORD_ENUM_OPERATOR_START, // .
NamespaceOperator, // ::
CastOperator, // :
ConcatOperator, // & (text concatenation operator)
SuffixOperatorGroup, // ++ -- !!
NotOperator, // !
PowerOperator, // ^
MulOperatorGroup, // % * /
AddOperatorGroup, // + -
CompareOperatorGroup, // < <= > >=
EqualityOperatorGroup, // == != <>
AndOperator, // && and
OrOperator, // || or
XorOperator,
AssignmentOperatorGroup, // = += -= *= /= ^= %= &=
CommaOperator, // ,
MAX_ENUM
} type = Empty;
void Clear() {
word = "";
type = Empty;
}
operator bool() const {
return type != Empty;
}
operator double() const {
if (type == Numeric)
return stod(word);
return 0;
}
operator const std::string&() const {
return word;
}
bool operator == (Type t) const {
return type == t;
}
bool operator == (const std::string& str) const {
return word == str;
}
bool operator == (const char* str) const {
return word == str;
}
bool operator != (Type t) const {return !(*this == t);}
bool operator != (const std::string& str) const {return !(*this == str);}
bool operator != (const char* str) const {return !(*this == str);}
Word(Type type_, std::string word_ = "") : word(word_), type(type_) {
// Automatically assign a string word when constructed only via the type
if (word == "") {
switch (type) {
case Empty: case Void:{
// OK
}break;
case Numeric:{
this->word = "0";
}break;
case Text:{
// OK
}break;
case ExpressionBegin:{
this->word = "(";
}break;
case ExpressionEnd:{
this->word = ")";
}break;
case HashTag:{
this->word = "#";
}break;
case TrailOperator:{
this->word = ".";
}break;
case NamespaceOperator:{
this->word = "::";
}break;
case CastOperator:{
this->word = ":";
}break;
case NotOperator:{
this->word = "!";
}break;
case AndOperator:{
this->word = "&&";
}break;
case OrOperator:{
this->word = "||";
}break;
case XorOperator:{
this->word = "xor";
}break;
case ConcatOperator:{
this->word = "&";
}break;
case CommaOperator:{
this->word = ",";
}break;
// // Don't specify a word for those when constructed only via the type, we will assert instead
// case Varname:
// this->word = "Varname";
// break;
// case Funcname:
// this->word = "Funcname";
// break;
// case Name:
// this->word = "Name";
// break;
case SuffixOperatorGroup:
this->word = "SuffixOperatorGroup";
break;
case PowerOperator:
this->word = "PowerOperator";
break;
case MulOperatorGroup:
this->word = "MulOperatorGroup";
break;
case AddOperatorGroup:
this->word = "AddOperatorGroup";
break;
case CompareOperatorGroup:
this->word = "CompareOperatorGroup";
break;
case EqualityOperatorGroup:
this->word = "EqualityOperatorGroup";
break;
case AssignmentOperatorGroup:
this->word = "AssignmentOperatorGroup";
break;
default: assert(!"Word not specified");
}
}
}
explicit Word(const std::string& value) : word(value), type(Text) {}
explicit Word(double value) : word(ToStringHighPrecision(value)), type(Numeric) {}
Word(const Word& other) = default;
Word(Word&& other) = default;
Word& operator= (const Word& other) = default;
Word& operator= (Word&& other) = default;
Word& operator= (const std::string& value) {
word = value;
type = Text;
return *this;
}
Word& operator= (double value) {
word = ToString(value);
type = Numeric;
return *this;
}
Word(std::istringstream& s) {
for (int c; int8_t(c = s.get()) != -1; ) if (c != ' ') {
switch (c) {
case '\t':{
word = c;
type = Tab;
}return;
// Variables and Constants
case '$':{
if (isalpha_(s.peek())) {
do {
word += tolower(s.get());
} while (!s.eof() && isalnum_(s.peek()));
type = Varname;
} else throw ParseError("Invalid var/const name");
}return;
// User-defined Functions
case '@':{
if (isalpha_(s.peek())) {
do {
word += tolower(s.get());
} while (!s.eof() && isalnum_(s.peek()));
type = Funcname;
} else throw ParseError("Invalid function name");
}return;
// Text literals
case '"':{
while (!s.eof()) {
if (s.peek() == '"') {
s.get();
if (s.eof() || s.peek() != '"') {
break;
}
}
if (word.length() >= XC_MAX_TEXT_LENGTH) {
throw ParseError("Text too long");
}
word += s.get();
}
type = Text;
}return;
// Expressions
case '(':{
int stack = 0;
bool inString = false;
while (!s.eof()) {
if (inString) {
if (s.peek() == '"') {
word += s.get();
if (s.peek() != '"') {
inString = false;
continue;
}
}
} else {
if (s.peek() == '(') {
stack++;
} else if (s.peek() == ')') {
if (stack-- == 0) {
s.get();
break;
}
} else if (s.peek() == '"') {
inString = true;
}
}
word += s.get();
}
if (stack < -1) {
throw ParseError("Extra parenthesis");
}
if (stack > -1) {
throw ParseError("Missing parenthesis");
}
type = Expression;
}return;
case ')':{
throw ParseError("Extra parenthesis");
}
}
// Comments
if (c == ';' || (c == '/' && s.peek() == '/')) {
s = {};
return;
}
// HashTag
if (c == '#') {
word = c;
type = HashTag;
return;
}
// Operators
if (isoperator(c)) {
word += c;
int c2 = s.peek();
if (isoperator(c2) && (c2 == c || c2 == '=' || (c == '<' && c2 == '>'))) {
word += s.get();
}
type = Operator;
return;
}
// Numeric
if (isdigit(c)) {
word += c;
bool hasDecimal = false;
while (!s.eof()) {
if (s.peek() == '.') {
if (hasDecimal) break;
// Only consume dot if followed by a digit (to avoid consuming trail operator in e.g. $m.0.x)
s.get(); // consume dot temporarily
if (!s.eof() && isdigit(s.peek())) {
hasDecimal = true;
word += '.';
} else {
// Put the dot back by seeking
s.putback('.');
break;
}
}
if (!isdigit(s.peek())) {
if (!hasDecimal && isalnum_(s.peek())) goto ContinueWithName;
else break;
}
word += s.get();
}
type = Numeric;
return;
}
// Name
if (isalpha_(c)) {
word += tolower(c);
ContinueWithName:
while (isalnum_(s.peek())) {
word += tolower(s.get());
}
type = Name;
return;
}
// Invalid
word = c;
type = Invalid;
return;
}
}
};
inline static std::ostream& operator << (std::ostream& s, const Word& w) {
return s << std::string(w);
}
// Parses one or more words from given string (including expressions done recursively), and assign final types to words. Sets resulting words in given words ref. This will NOT add expressions according to operator precedence.
inline static void ParseWords(const std::string& str, std::vector<Word>& words, int& scope) {
std::istringstream line(str);
while (Word word {line}) {
if (word == Word::Tab) {
if (words.size() == 0) {
++scope;
}
} else if (word == Word::Invalid) {
throw ParseError("Invalid character", word);
} else {
if (word == Word::Operator) {
if (word == ".")
word.type = Word::TrailOperator;
else if (word == "::")
word.type = Word::NamespaceOperator;
else if (word == ":")
word.type = Word::CastOperator;
else if (word == "++" || word == "--" || word == "!!")
word.type = Word::SuffixOperatorGroup;
else if (word == "&")
word.type = Word::ConcatOperator;
else if (word == "!")
word.type = Word::NotOperator;
else if (word == "^")
word.type = Word::PowerOperator;
else if (word == "*" || word == "/" || word == "%")
word.type = Word::MulOperatorGroup;
else if (word == "+" || word == "-")
word.type = Word::AddOperatorGroup;
else if (word == "<" || word == ">" || word == "<=" || word == ">=")
word.type = Word::CompareOperatorGroup;
else if (word == "==" || word == "!=" || word == "<>")
word.type = Word::EqualityOperatorGroup;
else if (word == "&&")
word.type = Word::AndOperator;
else if (word == "||")
word.type = Word::OrOperator;
else if (word == "=" || word == "+=" || word == "-=" || word == "*=" || word == "/=" || word == "^=" || word == "%=" || word == "&=")
word.type = Word::AssignmentOperatorGroup;
else if (word == ",")
word.type = Word::CommaOperator;
else throw ParseError("Invalid Operator", word);
} else if (word == Word::Name) {
if (word == "and")
word.type = Word::AndOperator;
else if (word == "or")
word.type = Word::OrOperator;
else if (word == "xor")
word.type = Word::XorOperator;
}
if (word == Word::Expression) {
words.push_back(Word::ExpressionBegin);
ParseWords(word, words, scope);
words.push_back(Word::ExpressionEnd);
} else if (word == Word::HashTag) {
return; // ignore the remaining of the line
} else {
words.push_back(word);
}
}
}
}
// From a given index of an opening parenthesis, returns the index of the corresponsing closing parenthesis, or -1 if not found.
inline static int GetExpressionEnd(const std::vector<Word>& words, int begin, int end = -1) {
int stack = 0;
if (end < 0) end += words.size();
while(++begin <= end) {
if (words[begin] == Word::ExpressionEnd) {
if (stack == 0) return begin;
--stack;
} else if (words[begin] == Word::ExpressionBegin) {
++stack;
}
}
return -1;
}
// From a given index of a closing parenthesis (end), returns the index of the corresponsing opening parenthesis, or -1 if not found. This function will include a leading Name if there is one (for a function call)
inline static int GetExpressionBegin(const std::vector<Word>& words, int begin, int end) {
int stack = 0;
while(--end >= 0) {
if (words[end] == Word::ExpressionBegin) {
if (stack == 0) {
if (end > 0 && (words[end-1] == Word::Name || words[end-1] == Word::Funcname)) {
if (end-1 >= begin) {
return end-1;
}
}
return end;
}
--stack;
} else if (words[end] == Word::ExpressionEnd) {
++stack;
}
}
return -1;
}
// From a given begin index for a function argument, returns the index of the last word before either the next comma or the argument list closing parenthesis, or -1 if not found.
inline static int GetArgEnd(const std::vector<Word>& words, int begin, int end = -1) {
int stack = 0;
if (end < 0) end += words.size();
if (words[begin] == Word::ExpressionBegin) ++stack;
else if (words[begin] == Word::ExpressionEnd) return -1; // no argument
while(begin++ < end) {
if (words[begin] == Word::ExpressionEnd) {
if (stack == 0) return begin - 1;
--stack;
} else if (words[begin] == Word::ExpressionBegin) {
++stack;
} else if (words[begin] == Word::CommaOperator) {
if (stack == 0) return begin - 1;
}
}
return -1;
}
// Prints out the interpreted code after it's fully parsed (after ParseLine, or after a ParseExpression)
inline static void DebugWords(std::vector<Word>& words, int startIndex = 0, bool verbose = false) {
for (unsigned int i = startIndex; i < words.size(); ++i) {
const auto& word = words[i];
if (verbose) {
switch (word.type) {
case Word::Numeric:
std::cout << "Numeric{" << word << "} ";
break;
case Word::Text:
std::cout << "Text{" << word << "} ";
break;
case Word::Varname:
std::cout << "Varname{" << word << "} ";
break;
case Word::Funcname:
std::cout << "Funcname{" << word << "} ";
break;
case Word::ExpressionBegin:
std::cout << "Expression{ ";
break;
case Word::ExpressionEnd:
std::cout << "} ";
break;
case Word::Name:
std::cout << "Name{" << word << "} ";
break;
case Word::TrailOperator:
std::cout << "TrailOperator{" << word << "} ";
break;
case Word::NamespaceOperator:
std::cout << "NamespaceOperator{" << word << "} ";
break;
case Word::CastOperator:
std::cout << "CastOperator{" << word << "} ";
break;
case Word::SuffixOperatorGroup:
std::cout << "SuffixOperatorGroup{" << word << "} ";
break;
case Word::ConcatOperator:
std::cout << "ConcatOperator{" << word << "} ";
break;
case Word::NotOperator:
std::cout << "NotOperator{" << word << "} ";
break;
case Word::PowerOperator:
std::cout << "PowerOperator{" << word << "} ";
break;
case Word::MulOperatorGroup:
std::cout << "MulOperatorGroup{" << word << "} ";
break;
case Word::AddOperatorGroup:
std::cout << "AddOperatorGroup{" << word << "} ";
break;
case Word::CompareOperatorGroup:
std::cout << "CompareOperatorGroup{" << word << "} ";
break;
case Word::EqualityOperatorGroup:
std::cout << "EqualityOperatorGroup{" << word << "} ";
break;
case Word::AndOperator:
std::cout << "AndOperator{" << word << "} ";
break;
case Word::OrOperator:
std::cout << "OrOperator{" << word << "} ";
case Word::XorOperator:
std::cout << "XorOperator{" << word << "} ";
break;
case Word::AssignmentOperatorGroup:
std::cout << "AssignmentOperatorGroup{" << word << "} ";
break;
case Word::CommaOperator:
std::cout << "CommaOperator{" << word << "} ";
break;
case Word::Void:
std::cout << "void ";
break;
case Word::FileInfo:
std::cout << "FileInfo{" << word << "} ";
break;
default: assert(!"Parse Error");
}
} else {
switch (word.type) {
case Word::Numeric:
std::cout << word << " ";
break;
case Word::Text:
std::cout << "\"" << word << "\" ";
break;
case Word::Varname:
std::cout << "$" << word << " ";
break;
case Word::Funcname:
std::cout << "@" << word << " ";
break;
case Word::ExpressionBegin:
std::cout << "( ";
break;
case Word::ExpressionEnd:
std::cout << ") ";
break;
case Word::Name:
std::cout << word << " ";
break;
case Word::TrailOperator:
case Word::NamespaceOperator:
case Word::CastOperator:
case Word::SuffixOperatorGroup:
case Word::ConcatOperator:
case Word::NotOperator:
case Word::PowerOperator:
case Word::MulOperatorGroup:
case Word::AddOperatorGroup:
case Word::CompareOperatorGroup:
case Word::EqualityOperatorGroup:
case Word::AssignmentOperatorGroup:
case Word::CommaOperator:
std::cout << word << " ";
break;
case Word::AndOperator:
std::cout << "and ";
break;
case Word::OrOperator:
std::cout << "or ";
break;
case Word::XorOperator:
std::cout << "xor ";
break;
case Word::Void:
break;
case Word::FileInfo:
std::cout << "// <" << word << "> ";
break;
default: assert(!"Parse Error");
}
}
}
}
// Parse an expression following an assignement or function call arguments excluding surrounding parenthesis. Returns true on success, false on error. This function may add words to the given vector, mostly to add parenthesis around operations based on operator precedence.
inline static bool ParseExpression(std::vector<Word>& words, int startIndex, int endIndex = -1) {
auto lastWord = [&words, &endIndex]{
return endIndex == -1? words.size()-1 : std::min(size_t(endIndex), words.size()-1);
};
// Handle single-word literal expressions (also includes single variable name)
if (startIndex == (int)lastWord() && (words[startIndex] == Word::Numeric || words[startIndex] == Word::Text || words[startIndex] == Word::Varname || words[startIndex] == Word::Name)) {
return true;
}
// Any other type of single-word expression should be invalid
if (startIndex >= (int)lastWord()) {
return false;
}
// Encapsulate operations within expressions, based on operator precedence
for (Word::Type op = Word::Type(WORD_ENUM_OPERATOR_START); op < Word::CommaOperator; op = Word::Type(+op+1)) {
for (int opIndex = startIndex; opIndex <= (int)lastWord(); ++opIndex) {
if (words[opIndex] == op) {
auto word = words[opIndex];
int prevPos = opIndex-1;
int nextPos = opIndex+1;
Word prev = prevPos >= startIndex? words[prevPos] : Word::Empty;
Word next = nextPos <= (int)lastWord()? words[nextPos] : Word::Empty;
// Suffix operators (INVALID IN EXPRESSIONS, because they modify the variable itself, and that should require a direct assignment in a separate statement, as per the language's philosophy)
if (word == Word::SuffixOperatorGroup) {
throw ParseError("Cannot use a suffix operator within an expression");
// if (!prev || prev != Word::Varname) {
// throw ParseError("Suffix operators can only be used after a variable name");
// }
// words.insert(words.begin() + nextPos, Word::ExpressionEnd);
// words.insert(words.begin() + prevPos, Word::ExpressionBegin);
// ++opIndex;
// if (endIndex != -1) endIndex += 2;
} else {
// Find expression boundaries
if (next == Word::AddOperatorGroup || next == Word::NotOperator) {
++nextPos;
next = nextPos <= (int)lastWord()? words[nextPos] : Word::Empty;
}
if (next == Word::ExpressionBegin) {
nextPos = GetExpressionEnd(words, nextPos);
if (nextPos == -1 || nextPos > (int)lastWord()) {
return false;
}
}
if (prev == Word::ExpressionEnd) {
prevPos = GetExpressionBegin(words, startIndex, prevPos);
if (prevPos < 0) {
return false;
}
}
// Handle function calls (and cast) within expressions
if (next == Word::Name || next == Word::Funcname) {
Word after = nextPos+1 <= (int)lastWord()? words[nextPos+1] : Word::Empty;
if (word != Word::CastOperator && word != Word::TrailOperator && next == Word::Funcname && after != Word::ExpressionBegin) {
return false;
}
if (after == Word::ExpressionBegin) {
nextPos = GetExpressionEnd(words, nextPos+1);
if (nextPos == -1 || nextPos > (int)lastWord()) {
return false;
}
}
}
// Middle operators
if (prev && next && prev != Word::ExpressionBegin && next != Word::ExpressionEnd && prev.type < WORD_ENUM_OPERATOR_START && next.type < WORD_ENUM_OPERATOR_START) {
Word before = prevPos >= startIndex && prevPos > 0? words[prevPos-1] : Word::Empty;
Word after = nextPos+1 <= (int)lastWord()? words[nextPos+1] : Word::Empty;
// Check if not already between parenthesis
if (before != Word::ExpressionBegin || after != Word::ExpressionEnd) {
if (word == Word::TrailOperator) {
if (prev != Word::Varname && prev != Word::ExpressionEnd) {
throw ParseError("A trail operator (.) is not allowed after", prev);
}
if (next != Word::Numeric && next != Word::Varname && next != Word::Name && next != Word::ExpressionBegin) {
throw ParseError("A trail operator (.) cannot be followed by", next, "within an expression");
}
} else if (word == Word::CastOperator) {
if (prev != Word::Varname && prev != Word::ExpressionEnd) {
throw ParseError("A cast operator (:) is not allowed after", prev);
}
if (next != Word::Name) {
throw ParseError("A cast operator (:) cannot be followed by", next);
}
}
words.insert(words.begin() + nextPos + 1, Word::ExpressionEnd);
words.insert(words.begin() + prevPos, Word::ExpressionBegin);
++opIndex;
if (endIndex != -1) endIndex += 2;
}
} else {
// Prefix operators
if (next && next != Word::ExpressionEnd && (word == Word::AddOperatorGroup || word == Word::NotOperator)) {
if (word == "-") {
if (next == Word::Numeric) {
words[nextPos].word = "-" + next.word;
words.erase(words.begin() + opIndex);
--opIndex;
if (endIndex != -1) --endIndex;