-
Notifications
You must be signed in to change notification settings - Fork 88
/
TinyJS.cpp
executable file
·2190 lines (2030 loc) · 68.2 KB
/
TinyJS.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
/*
* TinyJS
*
* A single-file Javascript-alike engine
*
* Authored By Gordon Williams <[email protected]>
*
* Copyright (C) 2009 Pur3 Ltd
*
* 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.
*/
/* Version 0.1 : (gw) First published on Google Code
Version 0.11 : Making sure the 'root' variable never changes
'symbol_base' added for the current base of the sybmbol table
Version 0.12 : Added findChildOrCreate, changed string passing to use references
Fixed broken string encoding in getJSString()
Removed getInitCode and added getJSON instead
Added nil
Added rough JSON parsing
Improved example app
Version 0.13 : Added tokenEnd/tokenLastEnd to lexer to avoid parsing whitespace
Ability to define functions without names
Can now do "var mine = function(a,b) { ... };"
Slightly better 'trace' function
Added findChildOrCreateByPath function
Added simple test suite
Added skipping of blocks when not executing
Version 0.14 : Added parsing of more number types
Added parsing of string defined with '
Changed nil to null as per spec, added 'undefined'
Now set variables with the correct scope, and treat unknown
as 'undefined' rather than failing
Added proper (I hope) handling of null and undefined
Added === check
Version 0.15 : Fix for possible memory leaks
Version 0.16 : Removal of un-needed findRecursive calls
symbol_base removed and replaced with 'scopes' stack
Added reference counting a proper tree structure
(Allowing pass by reference)
Allowed JSON output to output IDs, not strings
Added get/set for array indices
Changed Callbacks to include user data pointer
Added some support for objects
Added more Java-esque builtin functions
Version 0.17 : Now we don't deepCopy the parent object of the class
Added JSON.stringify and eval()
Nicer JSON indenting
Fixed function output in JSON
Added evaluateComplex
Fixed some reentrancy issues with evaluate/execute
Version 0.18 : Fixed some issues with code being executed when it shouldn't
Version 0.19 : Added array.length
Changed '__parent' to 'prototype' to bring it more in line with javascript
Version 0.20 : Added '%' operator
Version 0.21 : Added array type
String.length() no more - now String.length
Added extra constructors to reduce confusion
Fixed checks against undefined
Version 0.22 : First part of ardi's changes:
sprintf -> sprintf_s
extra tokens parsed
array memory leak fixed
Fixed memory leak in evaluateComplex
Fixed memory leak in FOR loops
Fixed memory leak for unary minus
Version 0.23 : Allowed evaluate[Complex] to take in semi-colon separated
statements and then only return the value from the last one.
Also checks to make sure *everything* was parsed.
Ints + doubles are now stored in binary form (faster + more precise)
Version 0.24 : More useful error for maths ops
Don't dump everything on a match error.
Version 0.25 : Better string escaping
Version 0.26 : Add CScriptVar::equals
Add built-in array functions
Version 0.27 : Added OZLB's TinyJS.setVariable (with some tweaks)
Added OZLB's Maths Functions
Version 0.28 : Ternary operator
Rudimentary call stack on error
Added String Character functions
Added shift operators
Version 0.29 : Added new object via functions
Fixed getString() for double on some platforms
Version 0.30 : Rlyeh Mario's patch for Math Functions on VC++
Version 0.31 : Add exec() to TinyJS functions
Now print quoted JSON that can be read by PHP/Python parsers
Fixed postfix increment operator
Version 0.32 : Fixed Math.randInt on 32 bit PCs, where it was broken
Version 0.33 : Fixed Memory leak + brokenness on === comparison
NOTE:
Constructing an array with an initial length 'Array(5)' doesn't work
Recursive loops of data such as a.foo = a; fail to be garbage collected
length variable cannot be set
The postfix increment operator returns the current value, not the previous as it should.
There is no prefix increment operator
Arrays are implemented as a linked list - hence a lookup time is O(n)
TODO:
Utility va-args style function in TinyJS for executing a function directly
Merge the parsing of expressions/statements so eval("statement") works like we'd expect.
Move 'shift' implementation into mathsOp
*/
#include "TinyJS.h"
#include <assert.h>
#define ASSERT(X) assert(X)
/* Frees the given link IF it isn't owned by anything else */
#define CLEAN(x) { CScriptVarLink *__v = x; if (__v && !__v->owned) { delete __v; } }
/* Create a LINK to point to VAR and free the old link.
* BUT this is more clever - it tries to keep the old link if it's not owned to save allocations */
#define CREATE_LINK(LINK, VAR) { if (!LINK || LINK->owned) LINK = new CScriptVarLink(VAR); else LINK->replaceWith(VAR); }
#include <string>
#include <string.h>
#include <sstream>
#include <cstdlib>
#include <stdio.h>
using namespace std;
#ifdef _WIN32
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif
#endif
#ifdef __GNUC__
#define vsprintf_s vsnprintf
#define sprintf_s snprintf
#define _strdup strdup
#endif
// ----------------------------------------------------------------------------------- Memory Debug
#define DEBUG_MEMORY 0
#if DEBUG_MEMORY
vector<CScriptVar*> allocatedVars;
vector<CScriptVarLink*> allocatedLinks;
void mark_allocated(CScriptVar *v) {
allocatedVars.push_back(v);
}
void mark_deallocated(CScriptVar *v) {
for (size_t i=0;i<allocatedVars.size();i++) {
if (allocatedVars[i] == v) {
allocatedVars.erase(allocatedVars.begin()+i);
break;
}
}
}
void mark_allocated(CScriptVarLink *v) {
allocatedLinks.push_back(v);
}
void mark_deallocated(CScriptVarLink *v) {
for (size_t i=0;i<allocatedLinks.size();i++) {
if (allocatedLinks[i] == v) {
allocatedLinks.erase(allocatedLinks.begin()+i);
break;
}
}
}
void show_allocated() {
for (size_t i=0;i<allocatedVars.size();i++) {
printf("ALLOCATED, %d refs\n", allocatedVars[i]->getRefs());
allocatedVars[i]->trace(" ");
}
for (size_t i=0;i<allocatedLinks.size();i++) {
printf("ALLOCATED LINK %s, allocated[%d] to \n", allocatedLinks[i]->name.c_str(), allocatedLinks[i]->var->getRefs());
allocatedLinks[i]->var->trace(" ");
}
allocatedVars.clear();
allocatedLinks.clear();
}
#endif
// ----------------------------------------------------------------------------------- Utils
bool isWhitespace(char ch) {
return (ch==' ') || (ch=='\t') || (ch=='\n') || (ch=='\r');
}
bool isNumeric(char ch) {
return (ch>='0') && (ch<='9');
}
bool isNumber(const string &str) {
for (size_t i=0;i<str.size();i++)
if (!isNumeric(str[i])) return false;
return true;
}
bool isHexadecimal(char ch) {
return ((ch>='0') && (ch<='9')) ||
((ch>='a') && (ch<='f')) ||
((ch>='A') && (ch<='F'));
}
bool isAlpha(char ch) {
return ((ch>='a') && (ch<='z')) || ((ch>='A') && (ch<='Z')) || ch=='_';
}
bool isIDString(const char *s) {
if (!isAlpha(*s))
return false;
while (*s) {
if (!(isAlpha(*s) || isNumeric(*s)))
return false;
s++;
}
return true;
}
void replace(string &str, char textFrom, const char *textTo) {
int sLen = strlen(textTo);
size_t p = str.find(textFrom);
while (p != string::npos) {
str = str.substr(0, p) + textTo + str.substr(p+1);
p = str.find(textFrom, p+sLen);
}
}
/// convert the given string into a quoted string suitable for javascript
std::string getJSString(const std::string &str) {
std::string nStr = str;
for (size_t i=0;i<nStr.size();i++) {
const char *replaceWith = "";
bool replace = true;
switch (nStr[i]) {
case '\\': replaceWith = "\\\\"; break;
case '\n': replaceWith = "\\n"; break;
case '\r': replaceWith = "\\r"; break;
case '\a': replaceWith = "\\a"; break;
case '"': replaceWith = "\\\""; break;
default: {
int nCh = ((int)nStr[i]) &0xFF;
if (nCh<32 || nCh>127) {
char buffer[5];
sprintf_s(buffer, 5, "\\x%02X", nCh);
replaceWith = buffer;
} else replace=false;
}
}
if (replace) {
nStr = nStr.substr(0, i) + replaceWith + nStr.substr(i+1);
i += strlen(replaceWith)-1;
}
}
return "\"" + nStr + "\"";
}
/** Is the string alphanumeric */
bool isAlphaNum(const std::string &str) {
if (str.size()==0) return true;
if (!isAlpha(str[0])) return false;
for (size_t i=0;i<str.size();i++)
if (!(isAlpha(str[i]) || isNumeric(str[i])))
return false;
return true;
}
// ----------------------------------------------------------------------------------- CSCRIPTEXCEPTION
CScriptException::CScriptException(const string &exceptionText) {
text = exceptionText;
}
// ----------------------------------------------------------------------------------- CSCRIPTLEX
CScriptLex::CScriptLex(const string &input) {
data = _strdup(input.c_str());
dataOwned = true;
dataStart = 0;
dataEnd = strlen(data);
reset();
}
CScriptLex::CScriptLex(CScriptLex *owner, int startChar, int endChar) {
data = owner->data;
dataOwned = false;
dataStart = startChar;
dataEnd = endChar;
reset();
}
CScriptLex::~CScriptLex(void)
{
if (dataOwned)
free((void*)data);
}
void CScriptLex::reset() {
dataPos = dataStart;
tokenStart = 0;
tokenEnd = 0;
tokenLastEnd = 0;
tk = 0;
tkStr = "";
getNextCh();
getNextCh();
getNextToken();
}
void CScriptLex::match(int expected_tk) {
if (tk!=expected_tk) {
ostringstream errorString;
errorString << "Got " << getTokenStr(tk) << " expected " << getTokenStr(expected_tk)
<< " at " << getPosition(tokenStart);
throw new CScriptException(errorString.str());
}
getNextToken();
}
string CScriptLex::getTokenStr(int token) {
if (token>32 && token<128) {
char buf[4] = "' '";
buf[1] = (char)token;
return buf;
}
switch (token) {
case LEX_EOF : return "EOF";
case LEX_ID : return "ID";
case LEX_INT : return "INT";
case LEX_FLOAT : return "FLOAT";
case LEX_STR : return "STRING";
case LEX_EQUAL : return "==";
case LEX_TYPEEQUAL : return "===";
case LEX_NEQUAL : return "!=";
case LEX_NTYPEEQUAL : return "!==";
case LEX_LEQUAL : return "<=";
case LEX_LSHIFT : return "<<";
case LEX_LSHIFTEQUAL : return "<<=";
case LEX_GEQUAL : return ">=";
case LEX_RSHIFT : return ">>";
case LEX_RSHIFTUNSIGNED : return ">>";
case LEX_RSHIFTEQUAL : return ">>=";
case LEX_PLUSEQUAL : return "+=";
case LEX_MINUSEQUAL : return "-=";
case LEX_PLUSPLUS : return "++";
case LEX_MINUSMINUS : return "--";
case LEX_ANDEQUAL : return "&=";
case LEX_ANDAND : return "&&";
case LEX_OREQUAL : return "|=";
case LEX_OROR : return "||";
case LEX_XOREQUAL : return "^=";
// reserved words
case LEX_R_IF : return "if";
case LEX_R_ELSE : return "else";
case LEX_R_DO : return "do";
case LEX_R_WHILE : return "while";
case LEX_R_FOR : return "for";
case LEX_R_BREAK : return "break";
case LEX_R_CONTINUE : return "continue";
case LEX_R_FUNCTION : return "function";
case LEX_R_RETURN : return "return";
case LEX_R_VAR : return "var";
case LEX_R_TRUE : return "true";
case LEX_R_FALSE : return "false";
case LEX_R_NULL : return "null";
case LEX_R_UNDEFINED : return "undefined";
case LEX_R_NEW : return "new";
}
ostringstream msg;
msg << "?[" << token << "]";
return msg.str();
}
void CScriptLex::getNextCh() {
currCh = nextCh;
if (dataPos < dataEnd)
nextCh = data[dataPos];
else
nextCh = 0;
dataPos++;
}
void CScriptLex::getNextToken() {
tk = LEX_EOF;
tkStr.clear();
while (currCh && isWhitespace(currCh)) getNextCh();
// newline comments
if (currCh=='/' && nextCh=='/') {
while (currCh && currCh!='\n') getNextCh();
getNextCh();
getNextToken();
return;
}
// block comments
if (currCh=='/' && nextCh=='*') {
while (currCh && (currCh!='*' || nextCh!='/')) getNextCh();
getNextCh();
getNextCh();
getNextToken();
return;
}
// record beginning of this token
tokenStart = dataPos-2;
// tokens
if (isAlpha(currCh)) { // IDs
while (isAlpha(currCh) || isNumeric(currCh)) {
tkStr += currCh;
getNextCh();
}
tk = LEX_ID;
if (tkStr=="if") tk = LEX_R_IF;
else if (tkStr=="else") tk = LEX_R_ELSE;
else if (tkStr=="do") tk = LEX_R_DO;
else if (tkStr=="while") tk = LEX_R_WHILE;
else if (tkStr=="for") tk = LEX_R_FOR;
else if (tkStr=="break") tk = LEX_R_BREAK;
else if (tkStr=="continue") tk = LEX_R_CONTINUE;
else if (tkStr=="function") tk = LEX_R_FUNCTION;
else if (tkStr=="return") tk = LEX_R_RETURN;
else if (tkStr=="var") tk = LEX_R_VAR;
else if (tkStr=="true") tk = LEX_R_TRUE;
else if (tkStr=="false") tk = LEX_R_FALSE;
else if (tkStr=="null") tk = LEX_R_NULL;
else if (tkStr=="undefined") tk = LEX_R_UNDEFINED;
else if (tkStr=="new") tk = LEX_R_NEW;
} else if (isNumeric(currCh)) { // Numbers
bool isHex = false;
if (currCh=='0') { tkStr += currCh; getNextCh(); }
if (currCh=='x') {
isHex = true;
tkStr += currCh; getNextCh();
}
tk = LEX_INT;
while (isNumeric(currCh) || (isHex && isHexadecimal(currCh))) {
tkStr += currCh;
getNextCh();
}
if (!isHex && currCh=='.') {
tk = LEX_FLOAT;
tkStr += '.';
getNextCh();
while (isNumeric(currCh)) {
tkStr += currCh;
getNextCh();
}
}
// do fancy e-style floating point
if (!isHex && (currCh=='e'||currCh=='E')) {
tk = LEX_FLOAT;
tkStr += currCh; getNextCh();
if (currCh=='-') { tkStr += currCh; getNextCh(); }
while (isNumeric(currCh)) {
tkStr += currCh; getNextCh();
}
}
} else if (currCh=='"') {
// strings...
getNextCh();
while (currCh && currCh!='"') {
if (currCh == '\\') {
getNextCh();
switch (currCh) {
case 'n' : tkStr += '\n'; break;
case '"' : tkStr += '"'; break;
case '\\' : tkStr += '\\'; break;
default: tkStr += currCh;
}
} else {
tkStr += currCh;
}
getNextCh();
}
getNextCh();
tk = LEX_STR;
} else if (currCh=='\'') {
// strings again...
getNextCh();
while (currCh && currCh!='\'') {
if (currCh == '\\') {
getNextCh();
switch (currCh) {
case 'n' : tkStr += '\n'; break;
case 'a' : tkStr += '\a'; break;
case 'r' : tkStr += '\r'; break;
case 't' : tkStr += '\t'; break;
case '\'' : tkStr += '\''; break;
case '\\' : tkStr += '\\'; break;
case 'x' : { // hex digits
char buf[3] = "??";
getNextCh(); buf[0] = currCh;
getNextCh(); buf[1] = currCh;
tkStr += (char)strtol(buf,0,16);
} break;
default: if (currCh>='0' && currCh<='7') {
// octal digits
char buf[4] = "???";
buf[0] = currCh;
getNextCh(); buf[1] = currCh;
getNextCh(); buf[2] = currCh;
tkStr += (char)strtol(buf,0,8);
} else
tkStr += currCh;
}
} else {
tkStr += currCh;
}
getNextCh();
}
getNextCh();
tk = LEX_STR;
} else {
// single chars
tk = currCh;
if (currCh) getNextCh();
if (tk=='=' && currCh=='=') { // ==
tk = LEX_EQUAL;
getNextCh();
if (currCh=='=') { // ===
tk = LEX_TYPEEQUAL;
getNextCh();
}
} else if (tk=='!' && currCh=='=') { // !=
tk = LEX_NEQUAL;
getNextCh();
if (currCh=='=') { // !==
tk = LEX_NTYPEEQUAL;
getNextCh();
}
} else if (tk=='<' && currCh=='=') {
tk = LEX_LEQUAL;
getNextCh();
} else if (tk=='<' && currCh=='<') {
tk = LEX_LSHIFT;
getNextCh();
if (currCh=='=') { // <<=
tk = LEX_LSHIFTEQUAL;
getNextCh();
}
} else if (tk=='>' && currCh=='=') {
tk = LEX_GEQUAL;
getNextCh();
} else if (tk=='>' && currCh=='>') {
tk = LEX_RSHIFT;
getNextCh();
if (currCh=='=') { // >>=
tk = LEX_RSHIFTEQUAL;
getNextCh();
} else if (currCh=='>') { // >>>
tk = LEX_RSHIFTUNSIGNED;
getNextCh();
}
} else if (tk=='+' && currCh=='=') {
tk = LEX_PLUSEQUAL;
getNextCh();
} else if (tk=='-' && currCh=='=') {
tk = LEX_MINUSEQUAL;
getNextCh();
} else if (tk=='+' && currCh=='+') {
tk = LEX_PLUSPLUS;
getNextCh();
} else if (tk=='-' && currCh=='-') {
tk = LEX_MINUSMINUS;
getNextCh();
} else if (tk=='&' && currCh=='=') {
tk = LEX_ANDEQUAL;
getNextCh();
} else if (tk=='&' && currCh=='&') {
tk = LEX_ANDAND;
getNextCh();
} else if (tk=='|' && currCh=='=') {
tk = LEX_OREQUAL;
getNextCh();
} else if (tk=='|' && currCh=='|') {
tk = LEX_OROR;
getNextCh();
} else if (tk=='^' && currCh=='=') {
tk = LEX_XOREQUAL;
getNextCh();
}
}
/* This isn't quite right yet */
tokenLastEnd = tokenEnd;
tokenEnd = dataPos-3;
}
string CScriptLex::getSubString(int lastPosition) {
int lastCharIdx = tokenLastEnd+1;
if (lastCharIdx < dataEnd) {
/* save a memory alloc by using our data array to create the
substring */
char old = data[lastCharIdx];
data[lastCharIdx] = 0;
std::string value = &data[lastPosition];
data[lastCharIdx] = old;
return value;
} else {
return std::string(&data[lastPosition]);
}
}
CScriptLex *CScriptLex::getSubLex(int lastPosition) {
int lastCharIdx = tokenLastEnd+1;
if (lastCharIdx < dataEnd)
return new CScriptLex(this, lastPosition, lastCharIdx);
else
return new CScriptLex(this, lastPosition, dataEnd );
}
string CScriptLex::getPosition(int pos) {
if (pos<0) pos=tokenLastEnd;
int line = 1,col = 1;
for (int i=0;i<pos;i++) {
char ch;
if (i < dataEnd)
ch = data[i];
else
ch = 0;
col++;
if (ch=='\n') {
line++;
col = 0;
}
}
char buf[256];
sprintf_s(buf, 256, "(line: %d, col: %d)", line, col);
return buf;
}
// ----------------------------------------------------------------------------------- CSCRIPTVARLINK
CScriptVarLink::CScriptVarLink(CScriptVar *var, const std::string &name) {
#if DEBUG_MEMORY
mark_allocated(this);
#endif
this->name = name;
this->nextSibling = 0;
this->prevSibling = 0;
this->var = var->ref();
this->owned = false;
}
CScriptVarLink::CScriptVarLink(const CScriptVarLink &link) {
// Copy constructor
#if DEBUG_MEMORY
mark_allocated(this);
#endif
this->name = link.name;
this->nextSibling = 0;
this->prevSibling = 0;
this->var = link.var->ref();
this->owned = false;
}
CScriptVarLink::~CScriptVarLink() {
#if DEBUG_MEMORY
mark_deallocated(this);
#endif
var->unref();
}
void CScriptVarLink::replaceWith(CScriptVar *newVar) {
CScriptVar *oldVar = var;
var = newVar->ref();
oldVar->unref();
}
void CScriptVarLink::replaceWith(CScriptVarLink *newVar) {
if (newVar)
replaceWith(newVar->var);
else
replaceWith(new CScriptVar());
}
int CScriptVarLink::getIntName() {
return atoi(name.c_str());
}
void CScriptVarLink::setIntName(int n) {
char sIdx[64];
sprintf_s(sIdx, sizeof(sIdx), "%d", n);
name = sIdx;
}
// ----------------------------------------------------------------------------------- CSCRIPTVAR
CScriptVar::CScriptVar() {
refs = 0;
#if DEBUG_MEMORY
mark_allocated(this);
#endif
init();
flags = SCRIPTVAR_UNDEFINED;
}
CScriptVar::CScriptVar(const string &str) {
refs = 0;
#if DEBUG_MEMORY
mark_allocated(this);
#endif
init();
flags = SCRIPTVAR_STRING;
data = str;
}
CScriptVar::CScriptVar(const string &varData, int varFlags) {
refs = 0;
#if DEBUG_MEMORY
mark_allocated(this);
#endif
init();
flags = varFlags;
if (varFlags & SCRIPTVAR_INTEGER) {
intData = strtol(varData.c_str(),0,0);
} else if (varFlags & SCRIPTVAR_DOUBLE) {
doubleData = strtod(varData.c_str(),0);
} else
data = varData;
}
CScriptVar::CScriptVar(double val) {
refs = 0;
#if DEBUG_MEMORY
mark_allocated(this);
#endif
init();
setDouble(val);
}
CScriptVar::CScriptVar(int val) {
refs = 0;
#if DEBUG_MEMORY
mark_allocated(this);
#endif
init();
setInt(val);
}
CScriptVar::~CScriptVar(void) {
#if DEBUG_MEMORY
mark_deallocated(this);
#endif
removeAllChildren();
}
void CScriptVar::init() {
firstChild = 0;
lastChild = 0;
flags = 0;
jsCallback = 0;
jsCallbackUserData = 0;
data = TINYJS_BLANK_DATA;
intData = 0;
doubleData = 0;
}
CScriptVar *CScriptVar::getReturnVar() {
return getParameter(TINYJS_RETURN_VAR);
}
void CScriptVar::setReturnVar(CScriptVar *var) {
findChildOrCreate(TINYJS_RETURN_VAR)->replaceWith(var);
}
CScriptVar *CScriptVar::getParameter(const std::string &name) {
return findChildOrCreate(name)->var;
}
CScriptVarLink *CScriptVar::findChild(const string &childName) {
CScriptVarLink *v = firstChild;
while (v) {
if (v->name.compare(childName)==0)
return v;
v = v->nextSibling;
}
return 0;
}
CScriptVarLink *CScriptVar::findChildOrCreate(const string &childName, int varFlags) {
CScriptVarLink *l = findChild(childName);
if (l) return l;
return addChild(childName, new CScriptVar(TINYJS_BLANK_DATA, varFlags));
}
CScriptVarLink *CScriptVar::findChildOrCreateByPath(const std::string &path) {
size_t p = path.find('.');
if (p == string::npos)
return findChildOrCreate(path);
return findChildOrCreate(path.substr(0,p), SCRIPTVAR_OBJECT)->var->
findChildOrCreateByPath(path.substr(p+1));
}
CScriptVarLink *CScriptVar::addChild(const std::string &childName, CScriptVar *child) {
if (isUndefined()) {
flags = SCRIPTVAR_OBJECT;
}
// if no child supplied, create one
if (!child)
child = new CScriptVar();
CScriptVarLink *link = new CScriptVarLink(child, childName);
link->owned = true;
if (lastChild) {
lastChild->nextSibling = link;
link->prevSibling = lastChild;
lastChild = link;
} else {
firstChild = link;
lastChild = link;
}
return link;
}
CScriptVarLink *CScriptVar::addChildNoDup(const std::string &childName, CScriptVar *child) {
// if no child supplied, create one
if (!child)
child = new CScriptVar();
CScriptVarLink *v = findChild(childName);
if (v) {
v->replaceWith(child);
} else {
v = addChild(childName, child);
}
return v;
}
void CScriptVar::removeChild(CScriptVar *child) {
CScriptVarLink *link = firstChild;
while (link) {
if (link->var == child)
break;
link = link->nextSibling;
}
ASSERT(link);
removeLink(link);
}
void CScriptVar::removeLink(CScriptVarLink *link) {
if (!link) return;
if (link->nextSibling)
link->nextSibling->prevSibling = link->prevSibling;
if (link->prevSibling)
link->prevSibling->nextSibling = link->nextSibling;
if (lastChild == link)
lastChild = link->prevSibling;
if (firstChild == link)
firstChild = link->nextSibling;
delete link;
}
void CScriptVar::removeAllChildren() {
CScriptVarLink *c = firstChild;
while (c) {
CScriptVarLink *t = c->nextSibling;
delete c;
c = t;
}
firstChild = 0;
lastChild = 0;
}
CScriptVar *CScriptVar::getArrayIndex(int idx) {
char sIdx[64];
sprintf_s(sIdx, sizeof(sIdx), "%d", idx);
CScriptVarLink *link = findChild(sIdx);
if (link) return link->var;
else return new CScriptVar(TINYJS_BLANK_DATA, SCRIPTVAR_NULL); // undefined
}
void CScriptVar::setArrayIndex(int idx, CScriptVar *value) {
char sIdx[64];
sprintf_s(sIdx, sizeof(sIdx), "%d", idx);
CScriptVarLink *link = findChild(sIdx);
if (link) {
if (value->isUndefined())
removeLink(link);
else
link->replaceWith(value);
} else {
if (!value->isUndefined())
addChild(sIdx, value);
}
}
int CScriptVar::getArrayLength() {
int highest = -1;
if (!isArray()) return 0;
CScriptVarLink *link = firstChild;
while (link) {
if (isNumber(link->name)) {
int val = atoi(link->name.c_str());
if (val > highest) highest = val;
}
link = link->nextSibling;
}
return highest+1;
}
int CScriptVar::getChildren() {
int n = 0;
CScriptVarLink *link = firstChild;
while (link) {
n++;
link = link->nextSibling;
}
return n;
}
int CScriptVar::getInt() {
/* strtol understands about hex and octal */
if (isInt()) return intData;
if (isNull()) return 0;
if (isUndefined()) return 0;
if (isDouble()) return (int)doubleData;
return 0;
}
double CScriptVar::getDouble() {
if (isDouble()) return doubleData;
if (isInt()) return intData;
if (isNull()) return 0;
if (isUndefined()) return 0;
return 0; /* or NaN? */
}
const string &CScriptVar::getString() {
/* Because we can't return a string that is generated on demand.
* I should really just use char* :) */
static string s_null = "null";
static string s_undefined = "undefined";
if (isInt()) {
char buffer[32];
sprintf_s(buffer, sizeof(buffer), "%ld", intData);
data = buffer;
return data;
}
if (isDouble()) {
char buffer[32];
sprintf_s(buffer, sizeof(buffer), "%f", doubleData);
data = buffer;
return data;
}
if (isNull()) return s_null;
if (isUndefined()) return s_undefined;
// are we just a string here?
return data;
}
void CScriptVar::setInt(int val) {
flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_INTEGER;
intData = val;
doubleData = 0;
data = TINYJS_BLANK_DATA;
}
void CScriptVar::setDouble(double val) {
flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_DOUBLE;
doubleData = val;
intData = 0;
data = TINYJS_BLANK_DATA;
}
void CScriptVar::setString(const string &str) {
// name sure it's not still a number or integer
flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_STRING;
data = str;
intData = 0;
doubleData = 0;
}
void CScriptVar::setUndefined() {
// name sure it's not still a number or integer
flags = (flags&~SCRIPTVAR_VARTYPEMASK) | SCRIPTVAR_UNDEFINED;