-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTinyJS.cpp
More file actions
7901 lines (7164 loc) · 288 KB
/
TinyJS.cpp
File metadata and controls
7901 lines (7164 loc) · 288 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
/*
* TinyJS
*
* A single-file Javascript-alike engine
*
* Authored By Gordon Williams <gw@pur3.co.uk>
*
* Copyright (C) 2009 Pur3 Ltd
*
* 42TinyJS
*
* A fork of TinyJS with the goal to makes a more JavaScript/ECMA compliant engine
*
* Authored / Changed By Armin Diedering <armin@diedering.de>
*
* Copyright (C) 2010-2025 ardisoft
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <errno.h>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iterator>
#include <array>
#include <charconv>
#include <regex>
#include <algorithm>
#include <cmath>
#include <memory>
#include <sys/stat.h>
#include "TinyJS.h"
#ifndef ASSERT
# define ASSERT(X) assert(X)
#endif
namespace TinyJS {
// -----------------------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////////
/// Utils
//////////////////////////////////////////////////////////////////////////
inline int baseValue(int base, char c) {
if (base < 2 || base > 36) return -1;
int value = (c >= '0' && c <= '9') ? c - '0' :
((c | 32) >= 'a') ? (c | 32) - 'a' + 10 : -1;
return (value < base) ? value : -1;
}
inline bool baseValue(int base, char c, int &out) {
if (base < 2 || base > 36) return false;
out = (c >= '0' && c <= '9') ? c - '0' :
((c | 32) >= 'a') ? (c | 32) - 'a' + 10 : -1;
return out >= 0 && out < base;
}
inline bool isWhitespace(char ch) {
return (ch==' ') || (ch=='\t') || (ch=='\n') || (ch=='\r');
}
inline bool isNumeric(char ch) {
return (ch>='0') && (ch<='9');
}
inline bool isHexadecimal(char ch) {
return ((ch>='0') && (ch<='9')) || ((ch>='a') && (ch<='f')) || ((ch>='A') && (ch<='F'));
}
inline bool isOctal(char ch) {
return ((ch>='0') && (ch<='7'));
}
inline bool isIDStartChar(char ch) {
return ((ch>='a') && (ch<='z')) || ((ch>='A') && (ch<='Z')) || ch=='_' || ch=='$';
}
inline bool isIDChar(char ch) {
return isIDStartChar(ch) || isNumeric(ch);
}
bool isIDString(const std::string_view s) {
if (!isIDStartChar(s.front()))
return false;
for (auto c : s.substr(1)) {
if (!isIDChar(c))
return false;
}
return true;
}
bool KEY_STRING_LES::operator()(const std::string &lhs, const std::string &rhs) const {
return CScriptPropertyName(lhs).lessArayStringSymbol(rhs);
}
void replace(std::string &str, char textFrom, const char *textTo) {
size_t sLen = strlen(textTo);
size_t p = str.find(textFrom);
while (p != std::string::npos) {
str = str.substr(0, p) + textTo + str.substr(p+1);
p = str.find(textFrom, p+sLen);
}
}
std::string float2string(const double &floatData) {
std::ostringstream str;
str.unsetf(std::ios::floatfield);
#if (defined(_MSC_VER) && _MSC_VER >= 1600) || __cplusplus >= 201103L
str.precision(std::numeric_limits<double>::max_digits10);
#else
str.precision(numeric_limits<double>::digits10+2);
#endif
str << floatData;
return str.str();
}
#define size2int32(size) ((int32_t)(size > INT32_MAX ? INT32_MAX : size))
/// convert the given std::string into a quoted std::string suitable for javascript
std::string getJSString(const std::string_view str) {
char buffer[5] = "\\x00";
std::string nStr; nStr.reserve(str.length());
nStr.push_back('\"');
for (auto i : str) {
const char *replaceWith = 0;
switch (i) {
case '\\': replaceWith = "\\\\"; break;
case '\0': replaceWith = "\\0"; break;
case '\n': replaceWith = "\\n"; break;
case '\r': replaceWith = "\\r"; break;
case '\a': replaceWith = "\\a"; break;
case '\b': replaceWith = "\\b"; break;
case '\f': replaceWith = "\\f"; break;
case '\t': replaceWith = "\\t"; break;
case '\v': replaceWith = "\\v"; break;
case '"': replaceWith = "\\\""; break;
default: {
int nCh = ((unsigned char)i) & 0xff;
if(nCh<32 || nCh>127) {
static char hex[] = "0123456789ABCDEF";
buffer[2] = hex[(nCh>>4)&0x0f];
buffer[3] = hex[nCh&0x0f];
replaceWith = buffer;
};
}
}
if (replaceWith)
nStr.append(replaceWith);
else
nStr.push_back(i);
}
nStr.push_back('\"');
return nStr;
}
static inline std::string getIDString(const std::string_view str) {
if(isIDString(str) && CScriptToken::isReservedWord(str)==LEX_ID)
return std::string(str);
return getJSString(str);
}
//////////////////////////////////////////////////////////////////////////
/// CScriptException
//////////////////////////////////////////////////////////////////////////
std::string CScriptException::toString() const
{
std::ostringstream msg;
msg << ERROR_NAME[errorType] << ": " << message;
if(lineNumber >= 0) msg << " at Line:" << lineNumber+1;
if(column >=0) msg << " Column:" << column+1;
if(fileName.length()) msg << " in " << fileName;
return msg.str();
}
//////////////////////////////////////////////////////////////////////////
/// CScriptLex
//////////////////////////////////////////////////////////////////////////
#define RINGBUFFER_SIZE 1024
/////////////////////////////////
// Konstruktor, der einen istream verwendet.
/////////////////////////////////
CScriptLex::CScriptLex(std::istream& in, const std::string& File/* = ""*/, int Line/* = 1*/, [[maybe_unused]] int Column/* = 0*/)
: input(in), head(0), bomChecked(false), currentFile(File),
pos({ 0, Line, 0 }),
currCh(LEX_EOF), nextCh(LEX_EOF),
lineBreakBeforeToken(false), globalOffset(0),
tk(0), last_tk(0)
{
// Initialer Puffer: 1024 Bytes (1024 ist eine Potenz von 2).
buffer.resize(RINGBUFFER_SIZE);
reset(pos); // Setzt den internen Zustand anhand der Startposition
}
/////////////////////////////////
// Konstruktor, der einen string verwendet.
/////////////////////////////////
CScriptLex::CScriptLex(const std::string &Code, const std::string_view File/* = ""*/, int Line/* = 1*/, [[maybe_unused]] int Column/* = 0*/)
: ownedStream(new std::istringstream(Code)), input(*ownedStream), head(0), bomChecked(false),
currentFile(File), pos({ 0, Line, 0 }),
currCh(LEX_EOF), nextCh(LEX_EOF),
lineBreakBeforeToken(false), globalOffset(0),
tk(0), last_tk(0)
{
// Wähle eine Puffergröße passend zum Code.
// Wenn der Code sehr kurz ist, soll der Puffer nicht unnötig groß sein.
size_t desired = Code.size() + 1; // +1 für den Endmarker
size_t initSize = (desired < RINGBUFFER_SIZE) ? nextPowerOfTwo(desired) : RINGBUFFER_SIZE;
buffer.resize(initSize);
reset(pos);
}
// Setzt den Lexer-Zustand (Position, Tokenvariablen etc.) auf die übergebene Position zurück.
// Dabei wird auch der interne Lesezeiger (tail) neu gesetzt, sodass ab der alten Position weitergelesen werden kann.
void CScriptLex::reset(const POS& toPos) {
globalOffset = toPos.tokenStart; // Setze den globalen Offset auf den gespeicherten Wert
tk = last_tk = 0;
tkStr = "";
pos = toPos;
lineBreakBeforeToken = false;
currCh = nextCh = LEX_EOF;
// Hole zweimal das nächste Zeichen, damit currCh und nextCh initialisiert werden (entspricht dem Original).
getNextCh(); // currCh
getNextCh(); // nextCh
while (!getNextToken()); // instead recursion
}
/////////////////////////////////
// Token-Überprüfungsfunktionen
/////////////////////////////////
void CScriptLex::check(uint16_t expected_tk, uint16_t alternate_tk/* = LEX_NONE*/) {
if (expected_tk == ';' && tk == LEX_EOF)
return;
if (tk != expected_tk && tk != alternate_tk) {
std::string errorString;
if (expected_tk == LEX_EOF)
errorString = "Got unexpected " + CScriptToken::getTokenStr(tk);
else {
errorString = "Got '" + CScriptToken::getTokenStr(tk, tkStr.c_str()) +
"' expected '" + CScriptToken::getTokenStr(expected_tk) + "'";
if (alternate_tk != LEX_NONE)
errorString += " or '" + CScriptToken::getTokenStr(alternate_tk) + "'";
}
throw CScriptException(SyntaxError, errorString, currentFile, pos.currentLine, currentColumn());
}
}
void CScriptLex::match(uint16_t expected_tk, uint16_t alternate_tk/* = LEX_NONE*/) {
check(expected_tk, alternate_tk);
int lineBefore = pos.currentLine;
while (!getNextToken()); // instead recursion
lineBreakBeforeToken = (lineBefore != pos.currentLine);
if (pos.tokenStart - pos.currentLineStart > static_cast<size_t>(std::numeric_limits<int16_t>::max())) {
throw CScriptException(Error, "Maximum line length (32767 characters) exhausted", currentFile, pos.currentLine, int32_t(pos.tokenStart - pos.currentLineStart));
}
}
std::string CScriptLex::rest() {
std::string ret = "";
while (currCh != LEX_EOF) {
ret += currCh;
getNextCh();
}
return ret; } // Dummy-Implementierung
/////////////////////////////////////////////////////////////
// Ringpuffer-Mechanismus mit integrierter Erweiterung
/////////////////////////////////////////////////////////////
// Füllt den Puffer mit neuen Daten aus dem Input-Strom.
// Dabei wird sichergestellt, dass der Bereich ab der frühesten gelockten Position (tailLocked)
// nicht überschrieben wird.
bool CScriptLex::fillBuffer()
{
if (input.eof())
return false;
size_t bufSize = buffer.size();
// Berechne tailLocked: Falls gelockte Positionen existieren, entspricht tailLocked
// dem Index im Puffer der frühesten gelockten Position; ansonsten ist tailLocked gleich tail.
size_t tailLocked = getTailLocked();
// Berechne freien Platz, ohne den Bereich ab tailLocked zu überschreiben.
size_t freeSpace = ((head >= tailLocked) ? bufSize - head + tailLocked : tailLocked - head) - 1;
// Falls nicht genug freier Platz vorhanden ist, erweitern wir den Puffer.
if (freeSpace < 64/* MIN_FILL_SIZE*/ && bufSize == RINGBUFFER_SIZE) {
size_t oldSize = bufSize;
size_t newSize = oldSize * 2; // Verdopplung – garantiert eine Potenz von 2.
std::vector<char> newBuffer(newSize);
// Berechne den benutzten Speicher im alten Puffer.
size_t usedSpace = (head >= tailLocked) ? (head - tailLocked) : (oldSize - tailLocked + head);
// Kopiere die Daten vom alten Puffer in den neuen.
for (size_t i = 0; i < usedSpace; ++i) {
newBuffer[tailLocked + i] = buffer[(tailLocked + i) & (oldSize - 1)];
}
buffer = std::move(newBuffer);
if(head < tailLocked)
head += oldSize;
bufSize = newSize;
freeSpace += oldSize;
}
// Nun lesen wir in möglichst großen Blöcken, statt Zeichen für Zeichen.
while (freeSpace > 0 && input.good()) {
// Bestimme, wie viele freie Zeichen in einem Block ab head liegen.
size_t contiguousFree;
if (head >= tailLocked)
contiguousFree = bufSize - head - (tailLocked == 0 ? 1 : 0);
else
contiguousFree = freeSpace; // Der verfügbare Platz ist zusammenhängend.
input.read(&buffer[head], contiguousFree);
size_t count = static_cast<size_t>(input.gcount());
if (count == 0)
break; // Kein weiterer Input
if (!bomChecked) {
bomChecked = true;
if (static_cast<uint8_t>(buffer[0]) == 0xEF && static_cast<uint8_t>(buffer[1]) == 0xBB && static_cast<uint8_t>(buffer[2]) == 0xBF)
globalOffset += 3;
}
head = (head + count) & (bufSize - 1);
freeSpace -= count;
if (count < contiguousFree)
break; // Wahrscheinlich Ende des Streams.
}
return !needBufferFill();
}
/////////////////////////////////////////////////////////////
// Zeichen holen und Lookahead aktualisieren
/////////////////////////////////////////////////////////////
// Holt das nächste Zeichen aus dem Puffer, aktualisiert dabei currCh und nextCh sowie Positionsdaten.
void CScriptLex::getNextCh(bool raw/*=false*/)
{
// Falls das aktuelle Zeichen ein Zeilenumbruch war, aktualisiere die Positionsdaten.
if(currCh == '\n') { // Windows or Linux
pos.currentLine++;
pos.tokenStart = globalOffset - (nextCh == LEX_EOF ? 0 : 1);;
pos.currentLineStart = pos.tokenStart;
}
// Übertrage das bisherige Lookahead in currCh.
currCh = nextCh;
if (needBufferFill() && !fillBuffer()) {
nextCh = LEX_EOF; // buffer konnte nicht gefüllt werden
} else {
size_t bufSize = buffer.size();
size_t tail = globalOffset & (bufSize - 1);
nextCh = buffer[tail];
globalOffset++;
}
// Behandlung von Carriage Return: Wird currCh als '\r' gelesen,
// so wird (gegebenenfalls) mit Überspringen eines folgenden '\n' in '\n' umgewandelt.
if(!raw && currCh == '\r') { // Windows or Mac
if(nextCh == '\n')
getNextCh(); // Windows '\r\n\' --> skip '\r'
else
currCh = '\n'; // Mac (only '\r') --> convert '\r' to '\n'
}
}
static uint16_t not_allowed_tokens_befor_regexp[] = {LEX_ID, LEX_INT, LEX_FLOAT, LEX_STR, LEX_R_TRUE, LEX_R_FALSE, LEX_R_NULL, ']', ')', '.', LEX_PLUSPLUS, LEX_MINUSMINUS, LEX_EOF};
bool CScriptLex::getNextToken()
{
while (currCh && isWhitespace(currCh)) getNextCh();
// newline comments
if (currCh=='/' && nextCh=='/') {
while (currCh && currCh!='\n') getNextCh();
getNextCh();
//getNextToken();
return false;
}
// block comments
if (currCh=='/' && nextCh=='*') {
int nested=0;
do {
if (currCh=='/' && nextCh=='*') {
getNextCh(); // skip '/'
getNextCh(); // skip '*'
++nested;
} else if (currCh=='*' && nextCh=='/') {
getNextCh(); // skip '*'
getNextCh(); // skip '/'
--nested;
} else
getNextCh();
} while (currCh && nested);
//getNextToken();
return false;
}
last_tk = tk;
tk = LEX_EOF;
tkStr.clear();
// record beginning of this token
pos.tokenStart = globalOffset - (nextCh == LEX_EOF ? (currCh == LEX_EOF ? 0 : 1) : 2);
// tokens
if (isIDStartChar(currCh)) { // IDs
while (currCh >= 'a' && currCh <= 'z') {
tkStr += currCh;
getNextCh();
}
if (!isIDChar(currCh)) {
tk = CScriptToken::isReservedWord(tkStr);
#ifdef NO_GENERATORS
if (tk == LEX_R_YIELD)
throw CScriptException(Error, "42TinyJS was built without support of generators (yield expression)", currentFile, pos.currentLine, currentColumn());
#endif
} else {
while (isIDChar(currCh)) {
tkStr += currCh;
getNextCh();
}
tk = LEX_ID;
}
} else if (isNumeric(currCh) || (currCh=='.' && isNumeric(nextCh))) { // Numbers
if(currCh=='.') tkStr+='0';
bool isHex = false, isOct=false;
if (currCh=='0') {
tkStr += currCh; getNextCh();
//if(isOctal(currCh)) isOct = true;
}
if (currCh == 'o' || currCh == 'O') {
isOct = true;
tkStr += currCh; getNextCh();
} else if (currCh == 'x' || currCh == 'X') {
isHex = true;
tkStr += currCh; getNextCh();
}
tk = LEX_INT;
while (isOctal(currCh) || (!isOct && isNumeric(currCh)) || (isHex && isHexadecimal(currCh))) {
tkStr += currCh;
getNextCh();
}
if (!isHex && !isOct && currCh=='.') {
tk = LEX_FLOAT;
tkStr += '.';
getNextCh();
while (isNumeric(currCh)) {
tkStr += currCh;
getNextCh();
}
}
// do fancy e-style floating point
if (!isHex && !isOct && (currCh=='e' || currCh=='E')) {
tk = LEX_FLOAT;
tkStr += currCh; getNextCh();
if (currCh=='-') { tkStr += currCh; getNextCh(); }
while (isNumeric(currCh)) {
tkStr += currCh; getNextCh();
}
}
} else if (currCh=='"' || currCh=='\'') { // strings...
char endCh = currCh;
getNextCh();
while (currCh && currCh!=endCh && currCh!='\n') {
if (currCh == '\\') {
getNextCh(); // eat '\'
switch (currCh) {
case '\n': break; // ignore newline after '\'
case '0': tkStr += '\0'; break; // null
case 'n': tkStr += '\n'; break; // line feed
case 'r': tkStr += '\r'; break; // carriage return
case 'a': tkStr += '\a'; break; // bell - no bell in javascript
case 'b': tkStr += '\b'; break; // backspace
case 'f': tkStr += '\f'; break; // formfeed
case 't': tkStr += '\t'; break; // tabulator
case 'v': tkStr += '\v'; break; // verticl tabulator
case 'x': { // hex digits
getNextCh(); // eat x
int hi, lo;
if(baseValue(16, currCh, hi) && baseValue(16, nextCh, lo)) {
tkStr += static_cast<char>(hi << 4 | lo);
} else
throw CScriptException(SyntaxError, "malformed hexadezimal character escape sequence", currentFile, pos.currentLine, currentColumn());
}
[[fallthrough]];
default:
tkStr += currCh;
}
} else {
tkStr += currCh;
}
getNextCh();
}
if(currCh != endCh)
throw CScriptException(SyntaxError, "unterminated string literal", currentFile, pos.currentLine, currentColumn());
getNextCh();
tk = LEX_STR;
} else if(currCh == '`') { // template literal
getNextCh(); // eat '`'
while (currCh && currCh != '`' && !(currCh == '$' && nextCh == '{')) {
if (currCh == '\\' && (nextCh == '$'|| nextCh == '\\'|| nextCh == '`')) {
tkStr += currCh; // put '\\' in raw
getNextCh(true);
}
tkStr += currCh;
getNextCh(true);
}
if (currCh != '`' && currCh != '$')
throw CScriptException(SyntaxError, "unterminated template literal", currentFile, pos.currentLine, currentColumn());
if (currCh == '`') {
// no ${ ... } --> normal string
getNextCh(); // eat '`'
tk = LEX_T_TEMPLATE_LITERAL;
} else { // ${
getNextCh(); // eat '$'
getNextCh(); // eat '{'
templateLiteralBraces.push_back(1);
tk = LEX_T_TEMPLATE_LITERAL_FIRST;
}
} else {
// single chars
tk = (uint8_t)currCh;
if (currCh) getNextCh();
if (tk == '{') {
if (!templateLiteralBraces.empty()) ++templateLiteralBraces.back(); // simple count braces
} else if (tk == '}') {
if (!templateLiteralBraces.empty()) { // template literal ?
if (--templateLiteralBraces.back() == 0) { // template literal end of ${ ... }
templateLiteralBraces.pop_back();
while (currCh && currCh != '`' && !(currCh == '$' && nextCh == '{')) {
if (currCh == '\\' && nextCh == '$') {
tkStr += currCh; // put '\\' in raw
getNextCh(false);
}
tkStr += currCh;
getNextCh(false);
}
}
if (currCh != '`' && currCh != '$')
throw CScriptException(SyntaxError, "unterminated template literal", currentFile, pos.currentLine, currentColumn());
if (currCh == '`') {
// no more ${ ... } -> end of tmplate literal
getNextCh(); // eat '`'
tk = LEX_T_TEMPLATE_LITERAL_LAST;
} else {
getNextCh(); // eat '$'
getNextCh(); // eat '{'
templateLiteralBraces.push_back(1);
tk = LEX_T_TEMPLATE_LITERAL_MIDDLE;
}
}
} else if (tk == '=') {
if(currCh=='=') { // ==
tk = LEX_EQUAL;
getNextCh();
if (currCh=='=') { // ===
tk = LEX_TYPEEQUAL;
getNextCh();
}
} else if(currCh =='>') { // =>
tk = LEX_ARROW;
getNextCh();
}
} else if (tk=='!' && currCh=='=') { // !=
tk = LEX_NEQUAL;
getNextCh();
if (currCh=='=') { // !==
tk = LEX_NTYPEEQUAL;
getNextCh();
}
} else if (tk=='<') {
if (currCh=='=') { // <=
tk = LEX_LEQUAL;
getNextCh();
} else if (currCh=='<') { // <<
tk = LEX_LSHIFT;
getNextCh();
if (currCh=='=') { // <<=
tk = LEX_LSHIFTEQUAL;
getNextCh();
}
}
} else if (tk=='>') {
if (currCh=='=') { // >=
tk = LEX_GEQUAL;
getNextCh();
} else if (currCh=='>') { // >>
tk = LEX_RSHIFT;
getNextCh();
if (currCh=='=') { // >>=
tk = LEX_RSHIFTEQUAL;
getNextCh();
} else if (currCh=='>') { // >>>
tk = LEX_RSHIFTU;
getNextCh();
if (currCh=='=') { // >>>=
tk = LEX_RSHIFTUEQUAL;
getNextCh();
}
}
}
} else if (tk=='+') {
if (currCh=='=') { // +=
tk = LEX_PLUSEQUAL;
getNextCh();
} else if (currCh=='+') { // ++
tk = LEX_PLUSPLUS;
getNextCh();
}
} else if (tk=='-') {
if (currCh=='=') { // -=
tk = LEX_MINUSEQUAL;
getNextCh();
} else if (currCh=='-') { // --
tk = LEX_MINUSMINUS;
getNextCh();
}
} else if (tk=='&') {
if (currCh=='=') { // &=
tk = LEX_ANDEQUAL;
getNextCh();
} else if (currCh=='&') { // &&
tk = LEX_ANDAND;
getNextCh();
}
} else if (tk=='|') {
if (currCh=='=') { // |=
tk = LEX_OREQUAL;
getNextCh();
} else if (currCh=='|') { // ||
tk = LEX_OROR;
getNextCh();
}
} else if (tk=='^' && currCh=='=') {
tk = LEX_XOREQUAL;
getNextCh();
} else if (tk=='*' && currCh=='=') {
tk = LEX_ASTERISKEQUAL;
getNextCh();
} else if (tk=='/') {
// check if it's a RegExp-Literal
tk = LEX_REGEXP;
for(uint16_t *p = not_allowed_tokens_befor_regexp; *p; p++) {
if(*p==last_tk) { tk = '/'; break; }
}
if(tk == LEX_REGEXP) {
#ifdef NO_REGEXP
throw CScriptException(Error, "42TinyJS was built without support of regular expressions", currentFile, pos.currentLine, currentColumn());
#endif
tkStr = "/";
while (currCh && currCh!='/' && currCh!='\n') {
if (currCh == '\\' && nextCh == '/') {
tkStr.append(1, currCh);
getNextCh();
}
tkStr.append(1, currCh);
getNextCh();
}
if(currCh == '/') {
#ifndef NO_REGEXP
try { std::regex r(tkStr.substr(1), std::regex_constants::ECMAScript); } catch(std::regex_error &e) {
throw CScriptException(SyntaxError, std::string(e.what())+" - "+CScriptVarRegExp::ErrorStr(e.code()), currentFile, pos.currentLine, currentColumn());
}
#endif /* NO_REGEXP */
do {
tkStr.append(1, currCh);
getNextCh();
} while (currCh=='g' || currCh=='i' || currCh=='m' || currCh=='y');
} else
throw CScriptException(SyntaxError, "unterminated regular expression literal", currentFile, pos.currentLine, currentColumn());
} else if(currCh=='=') {
tk = LEX_SLASHEQUAL;
getNextCh();
}
} else if (tk=='%' && currCh=='=') {
tk = LEX_PERCENTEQUAL;
getNextCh();
} else if (tk == '?' && currCh == '?') {
tk = LEX_ASKASK;
getNextCh(); // eat '?'
if (currCh == '=') { // ??=
tk = LEX_ASKASKEQUAL;
getNextCh(); // eat '='
}
} else if (tk == '*' && currCh == '*') {
tk = LEX_ASTERISKASTERISK;
getNextCh(); // eat '*'
if (currCh == '=') { // **=
tk = LEX_ASTERISKASTERISKEQUAL;
getNextCh(); // eat '='
}
} else if (tk == '?' && currCh == '.') {
tk = LEX_OPTIONAL_CHAINING_MEMBER;
getNextCh(); // eat '.'
if (currCh == '[') {
tk = LEX_OPTIONAL_CHAINING_ARRAY;
getNextCh(); // eat '['
} else if (currCh == '(') {
tk = LEX_OPTIONAL_CHANING_FNC;
getNextCh(); // eat '('
}
} else if (tk == '.' && currCh == '.' && nextCh == '.') {
tk = LEX_SPREAD_REST;
getNextCh(); // eat '.'
getNextCh(); // eat '.'
}
}
/* This isn't quite right yet */
return true;
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataForwards
//////////////////////////////////////////////////////////////////////////
bool CScriptTokenDataForwards::compare_fnc_token_by_name::operator()(const CScriptToken& lhs, const CScriptToken& rhs) const {
return lhs.Fnc()->name < rhs.Fnc()->name;
}
bool CScriptTokenDataForwards::checkRedefinition(const std::string &Str, bool checkVarsInLetScope) {
STRING_SET_it it = varNames[LETS].find(Str);
if (it != varNames[LETS].end()) return false;
else if (checkVarsInLetScope)
if (vars_in_letscope.find(Str) != vars_in_letscope.end()) return false;
return true;
}
void CScriptTokenDataForwards::addVars( STRING_VECTOR_t Vars ) {
varNames[VARS].insert(std::move_iterator(Vars.begin()), std::move_iterator(Vars.end()));
}
std::string_view CScriptTokenDataForwards::addConsts(STRING_VECTOR_t &Consts) {
for (auto &it : Consts) {
if (!checkRedefinition(it, true)) return it;
varNames[CONSTS].insert(it);
}
return "";// varNames[CONSTS].insert(Vars.begin(), Vars.end());
}
std::string_view CScriptTokenDataForwards::addVarsInLetscope(STRING_VECTOR_t &Vars) {
for (auto &it : Vars) {
if (!checkRedefinition(it, false)) return it;
vars_in_letscope.insert(it);
}
return "";
}
std::string_view CScriptTokenDataForwards::addLets( STRING_VECTOR_t &Lets )
{
for(auto &it : Lets) {
if(!checkRedefinition(it, true)) return it;
varNames[LETS].insert(it);
}
return "";
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataLoop
//////////////////////////////////////////////////////////////////////////
CScriptTokenDataLoop::CScriptTokenDataLoop() {
type = FOR;
}
std::string CScriptTokenDataLoop::getParsableString(const std::string &IndentString/*=""*/, const std::string &Indent/*=""*/ ) {
static const char *heads[] = {"for each(", "for(", "for(", "for(", "while(", "do "};
static const char *ops[] = {" in ", " in ", " of ", "; ", "", ""};
std::string out = heads[type];
if(init.size() && type==FOR) out.append(CScriptToken::getParsableString(init));
if(type<=WHILE) out.append(CScriptToken::getParsableString(condition.begin(), condition.end()-(type>=FOR ? 0 : (type==FOR_OF ? 7 : 3))));
if(type<=FOR) out.append(ops[type]);
if(iter.size()) out.append(CScriptToken::getParsableString(iter));
out.append(") ").append(CScriptToken::getParsableString(body, IndentString, Indent));
if(type==DO)out.append(" while(").append(CScriptToken::getParsableString(condition)).append(");");
return out;
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataIf
//////////////////////////////////////////////////////////////////////////
CScriptTokenDataIf::CScriptTokenDataIf() = default;
std::string CScriptTokenDataIf::getParsableString(const std::string &IndentString/*=""*/, const std::string &Indent/*=""*/ ) {
std::string out = "if(";
std::string nl = Indent.size() ? "\n"+IndentString : " ";
out.append(CScriptToken::getParsableString(condition)).append(") ").append(CScriptToken::getParsableString(if_body, IndentString, Indent));
if(else_body.size()) {
char back = *out.rbegin();
if(back != ' ' && back != '\n') out.append(" ");
out.append("else ").append(CScriptToken::getParsableString(else_body, IndentString, Indent));
}
return out;
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataArrayComprehensionsBody
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataTry
//////////////////////////////////////////////////////////////////////////
CScriptTokenDataTry::CScriptTokenDataTry() = default;
std::string CScriptTokenDataTry::getParsableString( const std::string &IndentString/*=""*/, const std::string &Indent/*=""*/ ) {
std::string out = "try ";
std::string nl = Indent.size() ? "\n"+IndentString : " ";
out.append(CScriptToken::getParsableString(tryBlock, IndentString, Indent));
if(catchBlock.size()) {
out.append(nl).append("catch");
if(catchParameter.size()) out.append("(").append(CScriptToken::getParsableString(catchParameter)).append(")");
out.append(" ").append(CScriptToken::getParsableString(catchBlock, IndentString, Indent));
}
if(finallyBlock.size())
out.append(nl).append("finally ").append(CScriptToken::getParsableString(finallyBlock, IndentString, Indent));
return out;
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataString
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataFnc
//////////////////////////////////////////////////////////////////////////
CScriptTokenDataFnc::CScriptTokenDataFnc(int32_t Type) : type(Type), line(0) {}
std::string CScriptTokenDataFnc::getArgumentsString( bool forArrowFunction/*=false*/ ) {
std::ostringstream destination;
bool needParantheses = !forArrowFunction || arguments.size() != 1 || (arguments.size() == 1 && arguments[0].first.token == LEX_T_OBJECT_LITERAL);
if(needParantheses)
destination << "(";
if(arguments.size()) {
const char *comma = "";
for(auto &argument : arguments/*.begin(); argument!=old_arguments.end(); ++argument, comma=", "*/) {
if (argument.first.token == LEX_ID || argument.first.token == LEX_SPREAD_REST_ID) {
const char *spread = argument.first.token == LEX_SPREAD_REST_ID ? "..." : "";
destination << comma << spread << argument.first.String();
} else {
destination << comma << argument.first.Object()->getParsableString();
}
if (argument.second.size()) {
destination << " = " << CScriptToken::getParsableString(argument.second);
}
comma = ", ";
}
}
if(needParantheses)
destination << ") ";
else
destination << " ";
return destination.str();
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataObjectLiteral
//////////////////////////////////////////////////////////////////////////
CScriptTokenDataObjectLiteral::CScriptTokenDataObjectLiteral() : type(CScriptTokenDataObjectLiteral::OBJECT), destructuring(false), structuring(false) {}
std::string CScriptTokenDataObjectLiteral::getParsableString() {
std::string out = type == OBJECT ? "{ " : "[";
const char *comma = "";
for(auto &it : elements) {
out.append(comma); comma = (type <= ARRAY) ? ", " : " ";
if(it.value.empty()) continue;
if (it.isSpreadOrRest) out.append("...");
else if(type == OBJECT) out.append(getIDString(it.id)).append(" : ");
out.append(CScriptToken::getParsableString(it.value));
}
out.append(type == OBJECT ? " }" : "]");
return out;
}
void CScriptTokenDataObjectLiteral::setDestructuringMode(bool Destructuring) {
structuring = !(destructuring = Destructuring);
for(auto &it : elements) {
if (structuring && it.defaultValue.size()) {
it.value.back().token = '=';
it.value.insert(it.value.end(), std::make_move_iterator(it.defaultValue.begin()), std::make_move_iterator(it.defaultValue.end()));
it.defaultValue.clear();
}
if(it.value.size() && it.value.front().token == LEX_T_OBJECT_LITERAL) {
auto &e = it.value.front().Object();
if(e->destructuring && e->structuring)
e->setDestructuringMode(Destructuring);
}
}
}
STRING_VECTOR_t CScriptTokenDataObjectLiteral::getDestructuringVarNames() {
STRING_VECTOR_t varnames;
getDestructuringVarNames(varnames);
return varnames;
}
bool CScriptTokenDataObjectLiteral::getDestructuringVarNames(STRING_VECTOR_t &varnames) {
if (!destructuring) return false;
for (auto &it : elements) {
if (it.value.empty()) {
continue;
}
if (it.value.front().token == LEX_T_OBJECT_LITERAL) {
if (!it.value.front().Object()->getDestructuringVarNames(varnames))
return false;
} else if(it.value.size() == 2 && it.value.front().token == LEX_ID) { // size == 2 --> LEX_ID & LEX_T_END_EXPRESSION
varnames.push_back(it.value.front().String());
} else
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// CScriptTokenDataTemplateLiteral
//////////////////////////////////////////////////////////////////////////
CScriptTokenDataTemplateLiteral::CScriptTokenDataTemplateLiteral() {}
std::string CScriptTokenDataTemplateLiteral::getParsableString() {
std::string out = "`";
auto it_raw = raw.begin();
auto it_values = values.begin();
out.append(*it_raw++);
while (it_raw < raw.end()) {
out.append("${");
out.append(CScriptToken::getParsableString(*it_values++));
out.append("}");
out.append(*it_raw++);
}
out += "`";
return out;
}
// CScriptTokenDataTemplateLiteral::CScriptTokenDataTemplateLiteral(const std::string &String) {
// }
int CScriptTokenDataTemplateLiteral::parseRaw(std::string &str) {
// Zeiger für das Lesen (rp = read pointer) und Schreiben (wp = write pointer)
char *wp = str.data(); // Schreibzeiger auf den Anfang des Strings setzen
const char *rp = str.data();
const char *ep = rp + str.size(); // Endpointer für die Schleifenbegrenzung
while (rp < ep) {
if (*rp == '\r') { // Wenn ein \r (Carriage Return) gefunden wird
++rp;
if (rp < ep && *rp == '\n') {
// Falls direkt danach ein \n kommt, ersetze \r mit \n und überspringe \n
*wp++ = *rp++;
} else {
// Falls kein \n folgt, ersetze \r einfach durch \n
*wp++ = '\n';
}
continue;
}
if (*rp == '\\') { // Falls ein Escape-Zeichen gefunden wurde
++rp; // eat '\'
if (rp < ep && (*rp == '\n' || *rp == '\r')) {
while (rp < ep && (*rp == '\n' || *rp == '\r')) ++rp; // eat all '\n' and '\r'
continue;
}
switch (*rp) {
case '0': *wp++ = '\0'; break;
case 'n': *wp++ = '\n'; break;
case 'r': *wp++ = '\r'; break;
case 'a': *wp++ = '\a'; break;
case 'b': *wp++ = '\b'; break;
case 'f': *wp++ = '\f'; break;
case 't': *wp++ = '\t'; break;
case 'v': *wp++ = '\v'; break;