forked from CodenameCrew/hscript-improved
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSScript.hx
More file actions
769 lines (638 loc) · 18.2 KB
/
SScript.hx
File metadata and controls
769 lines (638 loc) · 18.2 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
package hscript;
import haxe.ds.*;
import haxe.Constraints.IMap;
import haxe.Exception;
import haxe.Timer;
import hscript.Expr;
#if sys
import sys.FileSystem;
import sys.io.File;
#end
using StringTools;
@:structInit
@:access(hscript.Interp)
@:access(hscript.Parser)
@:keepSub
class SScript {
public static var IGNORE_RETURN(default, never):Dynamic = "###SSCRIPT_IGNORE_RETURN";
public static var STOP_RETURN(default, never):Dynamic = "###SSCRIPT_STOP_RETURN";
public static var defaultTypeCheck(default, set):Null<Bool> = true;
public static var defaultDebug(default, set):Null<Bool> = #if debug true #else null #end;
public static var globalVariables:SScriptGlobalMap = new SScriptGlobalMap();
public static var global(default, null):Map<String, SScript> = [];
static var IDCount(default, null):Int = 0;
static var BlankReg(get, never):EReg;
public var customOrigin(default, set):String;
public var returnValue(default, null):Null<Dynamic> = null;
public var ID(default, null):Null<Int> = null;
public var typeCheck:Bool = false;
public var lastReportedTime(default, null):Float = -1;
public var lastReportedCallTime(default, null):Float = -1;
public var notAllowedClasses(default, null):Array<Class<Dynamic>> = [];
public var variables(get, never):Map<String, Dynamic>;
public var interp(default, null):Interp;
public var parser(default, null):Parser;
public var script(default, null):String = "";
public var active:Bool = true;
public var scriptFile(default, null):String = "";
public var traces:Bool = false;
public var debugTraces:Bool = #if debug true #else false #end;
public var parsingException(default, null):SScriptException;
public var packagePath(get, null):String = "";
@:deprecated("parsingExceptions are deprecated, use parsingException instead")
var parsingExceptions(get, never):Array<Exception>;
@:noPrivateAccess var _destroyed(default, null):Bool = false;
public function new(?scriptPath:String = "", ?preset:Bool = true, ?startExecute:Bool = true) {
var time = Timer.stamp();
if (defaultTypeCheck != null)
typeCheck = defaultTypeCheck;
if (defaultDebug != null)
debugTraces = defaultDebug;
interp = new Interp();
interp.setScr(this);
parser = new Parser();
parser.allowTypes = true;
parser.allowMetadata = true;
if (preset) {
if (debugTraces) trace('SScript constructor: calling preset()');
this.preset();
} else {
if (debugTraces) trace('SScript constructor: preset skipped');
}
for (i => k in globalVariables) {
if (i != null)
set(i, k);
}
try {
doFile(scriptPath);
if (startExecute) {
if (debugTraces) trace('SScript constructor: calling execute()');
execute();
} else {
if (debugTraces) trace('SScript constructor: execute skipped (will be called later)');
}
lastReportedTime = Timer.stamp() - time;
if (debugTraces && scriptPath != null && scriptPath.length > 0) {
if (lastReportedTime == 0)
trace('SScript instance created instantly (0s)');
else
trace('SScript instance created in ${lastReportedTime}s');
}
} catch (e:Dynamic) {
lastReportedTime = -1;
if (debugTraces) trace('SScript constructor error: $e');
}
}
public function execute():Void {
if (_destroyed) {
if (traces) trace('SScript execute: destroyed');
return;
}
if (interp == null || !active) {
if (traces) trace('SScript execute: interp null or not active');
return;
}
var origin:String = {
if (customOrigin != null && customOrigin.length > 0)
customOrigin;
else if (scriptFile != null && scriptFile.length > 0)
scriptFile;
else
"SScript";
};
if (script != null && script.length > 0) {
if (traces) trace('SScript execute: about to run script, origin=' + origin);
resetInterp();
try {
var expr:Expr = parser.parseString(script, origin);
var r = interp.execute(expr);
returnValue = r;
if (traces) trace('SScript execute: success');
} catch (e:Dynamic) {
parsingException = e;
returnValue = null;
if (traces) trace('SScript execute error: $e');
}
} else {
if (traces) trace('SScript execute: no script');
}
}
public function set(key:String, obj:Dynamic):SScript {
if (_destroyed)
return null;
if (obj != null && (obj is Class) && notAllowedClasses.contains(obj))
throw 'Tried to set ${Type.getClassName(obj)} which is not allowed.';
function setVar(key:String, obj:Dynamic):Void {
if (key == null)
return;
if (Tools.keys.contains(key))
throw '$key is a keyword, set something else';
if (!active)
return;
if (interp == null || !active) {
if (traces) {
if (interp == null)
trace("This script is unusable!");
else
trace("This script is not active!");
}
} else
interp.variables[key] = obj;
}
setVar(key, obj);
return this;
}
public function setClass(cl:Class<Dynamic>):SScript {
if (_destroyed)
return null;
if (cl == null) {
if (traces)
trace('Class cannot be null');
return null;
}
var clName:String = Type.getClassName(cl);
if (clName != null) {
var splitCl:Array<String> = clName.split('.');
if (splitCl.length > 1)
clName = splitCl[splitCl.length - 1];
set(clName, cl);
}
return this;
}
public function setClassString(cl:String):SScript {
if (_destroyed)
return null;
if (cl == null || cl.length < 1) {
if (traces)
trace('Class cannot be null');
return null;
}
var cls:Class<Dynamic> = Type.resolveClass(cl);
if (cls != null) {
if (cl.split('.').length > 1)
cl = cl.split('.')[cl.split('.').length - 1];
set(cl, cls);
}
return this;
}
public function setSpecialObject(obj:Dynamic, ?includeFunctions:Bool = true, ?exclusions:Array<String>):SScript {
if (_destroyed)
return null;
if (!active)
return this;
if (obj == null)
return this;
if (exclusions == null)
exclusions = new Array();
var types:Array<Dynamic> = [Int, String, Float, Bool, Array];
for (i in types)
if (Std.isOfType(obj, i))
throw 'Special object cannot be ${i}';
interp.specialObject = {obj: obj, includeFunctions: includeFunctions, exclusions: exclusions.copy()};
return this;
}
public function locals():Map<String, Dynamic> {
if (_destroyed)
return null;
if (!active)
return [];
var newMap:Map<String, Dynamic> = new Map();
if (interp.locals != null) {
for (i in interp.locals.keys()) {
var v = interp.locals[i];
if (v != null)
newMap[i] = v.r;
}
}
return newMap;
}
public function unset(key:String):SScript {
if (_destroyed)
return null;
if (interp == null || !active || key == null || !interp.variables.exists(key))
return null;
interp.variables.remove(key);
return this;
}
public function get(key:String):Dynamic {
if (_destroyed)
return null;
if (interp == null || !active) {
if (traces) {
if (interp == null)
trace("This script is unusable!");
else
trace("This script is not active!");
}
return null;
}
var l = locals();
if (l.exists(key))
return l[key];
return if (exists(key)) interp.variables[key] else null;
}
public function call(func:String, ?args:Array<Dynamic>):FunctionCall {
if (_destroyed)
return {
exceptions: [new SScriptException(new Exception((if (scriptFile != null && scriptFile.length > 0) scriptFile else "SScript instance") + " is destroyed."))],
calledFunction: func,
succeeded: false,
returnValue: null
};
if (!active)
return {
exceptions: [new SScriptException(new Exception((if (scriptFile != null && scriptFile.length > 0) scriptFile else "SScript instance") + " is not active."))],
calledFunction: func,
succeeded: false,
returnValue: null
};
var time:Float = Timer.stamp();
var scriptFile:String = if (scriptFile != null && scriptFile.length > 0) scriptFile else "";
var caller:FunctionCall = {
exceptions: [],
calledFunction: func,
succeeded: false,
returnValue: null
}
if (args == null)
args = new Array();
var pushedExceptions:Array<String> = new Array();
function pushException(e:String) {
if (!pushedExceptions.contains(e))
caller.exceptions.push(new SScriptException(new Exception(e)));
pushedExceptions.push(e);
}
if (func == null) {
if (traces)
trace('Function name cannot be null for $scriptFile!');
pushException('Function name cannot be null for $scriptFile!');
return caller;
}
var fun = get(func);
if (exists(func) && Type.typeof(fun) != TFunction) {
if (traces)
trace('$func is not a function');
pushException('$func is not a function');
} else if (interp == null || !exists(func)) {
if (interp == null) {
if (traces)
trace('Interpreter is null!');
pushException('Interpreter is null!');
} else {
if (traces)
trace('Function $func does not exist in $scriptFile.');
if (scriptFile != null && scriptFile.length > 1)
pushException('Function $func does not exist in $scriptFile.');
else
pushException('Function $func does not exist in SScript instance.');
}
} else {
var oldCaller = caller;
try {
var functionField:Dynamic = Reflect.callMethod(this, fun, args);
caller = {
exceptions: caller.exceptions,
calledFunction: func,
succeeded: true,
returnValue: functionField
};
} catch (e) {
caller = oldCaller;
caller.exceptions.insert(0, new SScriptException(e));
}
}
lastReportedCallTime = Timer.stamp() - time;
return caller;
}
public function clear():SScript {
if (_destroyed)
return null;
if (!active)
return this;
if (interp == null)
return this;
var importantThings:Array<String> = ['true', 'false', 'null', 'trace'];
for (i in interp.variables.keys())
if (!importantThings.contains(i))
interp.variables.remove(i);
return this;
}
public function exists(key:String):Bool {
if (_destroyed)
return false;
if (!active)
return false;
if (interp == null)
return false;
var l = locals();
if (l.exists(key))
return true;
return interp.variables.exists(key);
}
public function preset():Void {
if (_destroyed)
return;
if (!active)
return;
setClass(Date);
setClass(DateTools);
setClass(EReg);
setClass(Math);
setClass(Reflect);
setClass(Std);
setClass(SScript);
setClass(StringTools);
setClass(Type);
setClass(List);
setClass(StringBuf);
setClass(Xml);
setClass(haxe.Http);
setClass(haxe.Json);
setClass(haxe.Log);
setClass(haxe.Serializer);
setClass(haxe.Unserializer);
setClass(haxe.Timer);
#if sys
setClass(Sys);
setClass(sys.FileSystem);
setClass(sys.io.File);
setClass(sys.io.Process);
setClass(sys.io.FileInput);
setClass(sys.io.FileOutput);
#end
}
function resetInterp():Void {
if (_destroyed)
return;
if (interp == null)
return;
interp.locals = new Map();
}
function doFile(scriptPath:String):Void {
parsingException = null;
if (_destroyed)
return;
if (scriptPath == null || scriptPath.length < 1 || BlankReg.match(scriptPath)) {
ID = IDCount + 1;
IDCount++;
global[Std.string(ID)] = this;
return;
}
if (scriptPath != null && scriptPath.length > 0) {
#if sys
if (FileSystem.exists(scriptPath)) {
scriptFile = scriptPath;
script = File.getContent(scriptPath);
} else {
scriptFile = "";
script = scriptPath;
}
#else
scriptFile = "";
script = scriptPath;
#end
if (scriptFile != null && scriptFile.length > 0)
global[scriptFile] = this;
else if (script != null && script.length > 0)
global[script] = this;
}
}
public function doString(string:String, ?origin:String):SScript {
if (_destroyed)
return null;
if (!active)
return null;
if (string == null || string.length < 1 || BlankReg.match(string))
return this;
parsingException = null;
var time = Timer.stamp();
try {
var og:String = origin;
if (og != null && og.length > 0)
customOrigin = og;
if (og == null || og.length < 1)
og = customOrigin;
if (og == null || og.length < 1)
og = "SScript";
if (!active || interp == null)
return null;
resetInterp();
try {
script = string;
if (scriptFile != null && scriptFile.length > 0) {
if (ID != null)
global.remove(Std.string(ID));
global[scriptFile] = this;
} else if (script != null && script.length > 0) {
if (ID != null)
global.remove(Std.string(ID));
global[script] = this;
}
var expr:Expr = parser.parseString(script, og);
var r = interp.execute(expr);
returnValue = r;
if (traces) {
var execTime = Timer.stamp() - time;
if (execTime == 0)
trace('SScript doString executed instantly');
else
trace('SScript doString executed in ${execTime}s');
}
} catch (e:Dynamic) {
script = "";
parsingException = e;
returnValue = null;
if (traces) {
trace('SScript doString error: $e');
}
}
lastReportedTime = Timer.stamp() - time;
} catch (e:Dynamic) {
lastReportedTime = -1;
if (traces) {
trace('SScript doString fatal error: $e');
}
}
return this;
}
inline function toString():String {
if (_destroyed)
return "null";
if (scriptFile != null && scriptFile.length > 0)
return scriptFile;
return "[SScript SScript]";
}
#if (sys)
public static function listScripts(path:String, ?extensions:Array<String>):Array<SScript> {
if (!path.endsWith('/'))
path += '/';
if (extensions == null || extensions.length < 1)
extensions = ['hx'];
var list:Array<SScript> = [];
if (FileSystem.exists(path) && FileSystem.isDirectory(path)) {
var files:Array<String> = FileSystem.readDirectory(path);
for (i in files) {
var hasExtension:Bool = false;
for (l in extensions) {
if (i.endsWith(l)) {
hasExtension = true;
break;
}
}
if (hasExtension && FileSystem.exists(path + i))
list.push(new SScript(path + i));
}
}
return list;
}
#else
public static function listScripts(path:String, ?extensions:Array<String>):Array<SScript> {
return [];
}
#end
public function destroy():Void {
if (_destroyed)
return;
if (global.exists(script) && script != null && script.length > 0)
global.remove(script);
if (global.exists(scriptFile) && scriptFile != null && scriptFile.length > 0)
global.remove(scriptFile);
clear();
resetInterp();
customOrigin = null;
parser = null;
interp = null;
script = null;
scriptFile = null;
active = false;
notAllowedClasses = null;
lastReportedCallTime = -1;
lastReportedTime = -1;
ID = null;
parsingException = null;
returnValue = null;
_destroyed = true;
}
function get_variables():Map<String, Dynamic> {
if (_destroyed)
return null;
return interp.variables;
}
function get_packagePath():String {
if (_destroyed)
return null;
return packagePath;
}
static function get_BlankReg():EReg {
return ~/^[\n\r\t]$/;
}
function set_customOrigin(value:String):String {
if (_destroyed)
return null;
#if hscriptPos
@:privateAccess parser.origin = value;
#end
return customOrigin = value;
}
static function set_defaultTypeCheck(value:Null<Bool>):Null<Bool> {
for (i in global) {
i.typeCheck = value == null ? false : value;
}
return defaultTypeCheck = value;
}
static function set_defaultDebug(value:Null<Bool>):Null<Bool> {
for (i in global) {
i.debugTraces = value == null ? false : value;
}
return defaultDebug = value;
}
function get_parsingExceptions():Array<Exception> {
if (_destroyed)
return null;
if (parsingException == null)
return [];
return [parsingException.toException()];
}
}
abstract SScriptException(Exception) {
public var message(get, never):String;
public function new(exception:Exception)
this = exception;
@:from
public static function fromException(exception:Exception):SScriptException
return new SScriptException(exception);
@:to
public function toString():String
return message;
public function details():String
return this.details();
function get_message():String
return this.message;
public function toException():Exception
return this;
}
typedef SScriptGlobalMap = SScriptTypedGlobalMap<String, Dynamic>;
@:transitive
@:multiType(@:followWithAbstracts K)
abstract SScriptTypedGlobalMap<K, V>(IMap<K, V>) {
public function new();
public inline function set(key:K, value:V) {
this.set(key, value);
var key:String = cast key;
var value:Dynamic = cast value;
for (i in SScript.global) {
@:privateAccess
if (!i._destroyed)
i.set(key, value);
}
}
@:arrayAccess public inline function get(key:K)
return this.get(key);
public inline function exists(key:K)
return this.exists(key);
public inline function remove(key:K)
return this.remove(key);
public inline function keys():Iterator<K>
return this.keys();
public inline function iterator():Iterator<V>
return this.iterator();
public inline function keyValueIterator():KeyValueIterator<K, V>
return this.keyValueIterator();
public inline function copy():Map<K, V>
return cast this.copy();
public inline function toString():String
return this.toString();
public inline function clear():Void
this.clear();
@:arrayAccess @:noCompletion public inline function arrayWrite(k:K, v:V):V {
this.set(k, v);
var key:String = cast k;
var value:Dynamic = cast v;
for (i in SScript.global) {
@:privateAccess
if (!i._destroyed)
i.set(key, value);
}
return v;
}
@:to static inline function toStringMap<K:String, V>(t:IMap<K, V>):StringMap<V>
return new StringMap<V>();
@:to static inline function toIntMap<K:Int, V>(t:IMap<K, V>):IntMap<V>
return new IntMap<V>();
@:to static inline function toEnumValueMapMap<K:EnumValue, V>(t:IMap<K, V>):EnumValueMap<K, V>
return new EnumValueMap<K, V>();
@:to static inline function toObjectMap<K:{}, V>(t:IMap<K, V>):ObjectMap<K, V>
return new ObjectMap<K, V>();
@:from static inline function fromStringMap<V>(map:StringMap<V>):SScriptTypedGlobalMap<String, V>
return cast map;
@:from static inline function fromIntMap<V>(map:IntMap<V>):SScriptTypedGlobalMap<Int, V>
return cast map;
@:from static inline function fromObjectMap<K:{}, V>(map:ObjectMap<K, V>):SScriptTypedGlobalMap<K, V>
return cast map;
}
typedef FunctionCall = {
public var succeeded(default, null):Bool;
public var calledFunction(default, null):String;
public var returnValue(default, null):Null<Dynamic>;
public var exceptions(default, null):Array<SScriptException>;
}