forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.d
3799 lines (3147 loc) · 107 KB
/
script.d
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
// dmd -g -ofscripttest -unittest -main script.d jsvar.d && ./scripttest
/*
FIXME: fix `(new A()).b`
FIXME: i kinda do want a catch type filter e.g. catch(Exception f)
and perhaps overloads
For type annotations, maybe it can statically match later, but right now
it just forbids any assignment to that variable that isn't that type.
I'll have to define int, float, etc though as basic types.
FIXME: I also kinda want implicit construction of structs at times.
REPL plan:
easy movement to/from a real editor
can edit a specific function
repl is a different set of globals
maybe ctrl+enter to execute vs insert another line
write state to file
read state from file
state consists of all variables and source to functions.
maybe need @retained for a variable that is meant to keep
its value between loads?
ddoc????
udas?!?!?!
Steal Ruby's [regex, capture] maybe
and the => operator too
I kinda like the javascript foo`blargh` template literals too.
++ and -- are not implemented.
*/
/++
A small script interpreter that builds on [arsd.jsvar] to be easily embedded inside and to have has easy
two-way interop with the host D program. The script language it implements is based on a hybrid of D and Javascript.
The type the language uses is based directly on [var] from [arsd.jsvar].
The interpreter is slightly buggy and poorly documented, but the basic functionality works well and much of
your existing knowledge from Javascript will carry over, making it hopefully easy to use right out of the box.
See the [#examples] to quickly get the feel of the script language as well as the interop.
I haven't benchmarked it, but I expect it is pretty slow. My goal is to see what is possible for easy interoperability
with dynamic functionality and D rather than speed.
$(TIP
A goal of this language is to blur the line between D and script, but
in the examples below, which are generated from D unit tests,
the non-italics code is D, and the italics is the script. Notice
how it is a string passed to the [interpret] function.
In some smaller, stand-alone code samples, there will be a tag "adrscript"
in the upper right of the box to indicate it is script. Otherwise, it
is D.
)
Installation_instructions:
This script interpreter is contained entirely in two files: jsvar.d and script.d. Download both of them
and add them to your project. Then, `import arsd.script;`, declare and populate a `var globals = var.emptyObject;`,
and `interpret("some code", globals);` in D.
There's nothing else to it, no complicated build, no external dependencies.
$(CONSOLE
$ wget https://raw.githubusercontent.com/adamdruppe/arsd/master/script.d
$ wget https://raw.githubusercontent.com/adamdruppe/arsd/master/jsvar.d
$ dmd yourfile.d script.d jsvar.d
)
Script_features:
OVERVIEW
$(LIST
* Can subclass D objects in script. See [http://dpldocs.info/this-week-in-d/Blog.Posted_2020_04_27.html#subclasses-in-script
* easy interop with D thanks to arsd.jsvar. When interpreting, pass a var object to use as globals.
This object also contains the global state when interpretation is done.
* mostly familiar syntax, hybrid of D and Javascript
* simple implementation is moderately small and fairly easy to hack on (though it gets messier by the day), but it isn't made for speed.
)
SPECIFICS
$(LIST
// * Allows identifiers-with-dashes. To do subtraction, put spaces around the minus sign.
* Allows identifiers starting with a dollar sign.
* string literals come in "foo" or 'foo', like Javascript, or `raw string` like D. Also come as “nested “double quotes” are an option!”
* double quoted string literals can do Ruby-style interpolation: "Hello, #{name}".
* mixin aka eval (does it at runtime, so more like eval than mixin, but I want it to look like D)
* scope guards, like in D
* Built-in assert() which prints its source and its arguments
* try/catch/finally/throw
You can use try as an expression without any following catch to return the exception:
```adrscript
var a = try throw "exception";; // the double ; is because one closes the try, the second closes the var
// a is now the thrown exception
```
* for/while/foreach
* D style operators: +-/* on all numeric types, ~ on strings and arrays, |&^ on integers.
Operators can coerce types as needed: 10 ~ "hey" == "10hey". 10 + "3" == 13.
Any math, except bitwise math, with a floating point component returns a floating point component, but pure int math is done as ints (unlike Javascript btw).
Any bitwise math coerces to int.
So you can do some type coercion like this:
```adrscript
a = a|0; // forces to int
a = "" ~ a; // forces to string
a = a+0.0; // coerces to float
```
Though casting is probably better.
* Type coercion via cast, similarly to D.
```adrscript
var a = "12";
a.typeof == "String";
a = cast(int) a;
a.typeof == "Integral";
a == 12;
```
Supported types for casting to: int/long (both actually an alias for long, because of how var works), float/double/real, string, char/dchar (these return *integral* types), and arrays, int[], string[], and float[].
This forwards directly to the D function var.opCast.
* some operator overloading on objects, passing opBinary(op, rhs), length, and perhaps others through like they would be in D.
opIndex(name)
opIndexAssign(value, name) // same order as D, might some day support [n1, n2] => (value, n1, n2)
obj.__prop("name", value); // bypasses operator overloading, useful for use inside the opIndexAssign especially
Note: if opIndex is not overloaded, getting a non-existent member will actually add it to the member. This might be a bug but is needed right now in the D impl for nice chaining. Or is it? FIXME
FIXME: it doesn't do opIndex with multiple args.
* if/else
* array slicing, but note that slices are rvalues currently
* variables must start with A-Z, a-z, _, or $, then must be [A-Za-z0-9_]*.
(The $ can also stand alone, and this is a special thing when slicing, so you probably shouldn't use it at all.).
Variable names that start with __ are reserved and you shouldn't use them.
* int, float, string, array, bool, and `#{}` (previously known as `json!q{}` aka object) literals
* var.prototype, var.typeof. prototype works more like Mozilla's __proto__ than standard javascript prototype.
* the `|>` pipeline operator
* classes:
```adrscript
// inheritance works
class Foo : bar {
// constructors, D style
this(var a) { ctor.... }
// static vars go on the auto created prototype
static var b = 10;
// instance vars go on this instance itself
var instancevar = 20;
// "virtual" functions can be overridden kinda like you expect in D, though there is no override keyword
function virt() {
b = 30; // lexical scoping is supported for static variables and functions
// but be sure to use this. as a prefix for any class defined instance variables in here
this.instancevar = 10;
}
}
var foo = new Foo(12);
foo.newFunc = function() { this.derived = 0; }; // this is ok too, and scoping, including 'this', works like in Javascript
```
You can also use 'new' on another object to get a copy of it.
* return, break, continue, but currently cannot do labeled breaks and continues
* __FILE__, __LINE__, but currently not as default arguments for D behavior (they always evaluate at the definition point)
* most everything are expressions, though note this is pretty buggy! But as a consequence:
for(var a = 0, b = 0; a < 10; a+=1, b+=1) {}
won't work but this will:
for(var a = 0, b = 0; a < 10; {a+=1; b+=1}) {}
You can encase things in {} anywhere instead of a comma operator, and it works kinda similarly.
{} creates a new scope inside it and returns the last value evaluated.
* functions:
var fn = function(args...) expr;
or
function fn(args....) expr;
Special function local variables:
_arguments = var[] of the arguments passed
_thisfunc = reference to the function itself
this = reference to the object on which it is being called - note this is like Javascript, not D.
args can say var if you want, but don't have to
default arguments supported in any position
when calling, you can use the default keyword to use the default value in any position
* macros:
A macro is defined just like a function, except with the
macro keyword instead of the function keyword. The difference
is a macro must interpret its own arguments - it is passed
AST objects instead of values. Still a WIP.
)
Todo_list:
I also have a wishlist here that I may do in the future, but don't expect them any time soon.
FIXME: maybe some kind of splat operator too. choose([1,2,3]...) expands to choose(1,2,3)
make sure superclass ctors are called
FIXME: prettier stack trace when sent to D
FIXME: support more escape things in strings like \n, \t etc.
FIXME: add easy to use premade packages for the global object.
FIXME: the debugger statement from javascript might be cool to throw in too.
FIXME: add continuations or something too - actually doing it with fibers works pretty well
FIXME: Also ability to get source code for function something so you can mixin.
FIXME: add COM support on Windows ????
Might be nice:
varargs
lambdas - maybe without function keyword and the x => foo syntax from D.
Author: Adam D Ruppe
History:
September 1, 2020: added overloading for functions and type matching in `catch` blocks among other bug fixes
April 28, 2020: added `#{}` as an alternative to the `json!q{}` syntax for object literals. Also fixed unary `!` operator.
April 26, 2020: added `switch`, fixed precedence bug, fixed doc issues and added some unittests
Started writing it in July 2013. Yes, a basic precedence issue was there for almost SEVEN YEARS. You can use this as a toy but please don't use it for anything too serious, it really is very poorly written and not intelligently designed at all.
+/
module arsd.script;
/++
This example shows the basics of how to interact with the script.
The string enclosed in `q{ .. }` is the script language source.
The [var] type comes from [arsd.jsvar] and provides a dynamic type
to D. It is the same type used in the script language and is weakly
typed, providing operator overloads to work with many D types seamlessly.
However, if you do need to convert it to a static type, such as if passing
to a function, you can use `get!T` to get a static type out of it.
+/
unittest {
var globals = var.emptyObject;
globals.x = 25; // we can set variables on the global object
globals.name = "script.d"; // of various types
// and we can make native functions available to the script
globals.sum = (int a, int b) {
return a + b;
};
// This is the source code of the script. It is similar
// to javascript with pieces borrowed from D, so should
// be pretty familiar.
string scriptSource = q{
function foo() {
return 13;
}
var a = foo() + 12;
assert(a == 25);
// you can also access the D globals from the script
assert(x == 25);
assert(name == "script.d");
// as well as call D functions set via globals:
assert(sum(5, 6) == 11);
// I will also set a function to call from D
function bar(str) {
// unlike Javascript though, we use the D style
// concatenation operator.
return str ~ " concatenation";
}
};
// once you have the globals set up, you call the interpreter
// with one simple function.
interpret(scriptSource, globals);
// finally, globals defined from the script are accessible here too:
// however, notice the two sets of parenthesis: the first is because
// @property is broken in D. The second set calls the function and you
// can pass values to it.
assert(globals.foo()() == 13);
assert(globals.bar()("test") == "test concatenation");
// this shows how to convert the var back to a D static type.
int x = globals.x.get!int;
}
/++
$(H3 Macros)
Macros are like functions, but instead of evaluating their arguments at
the call site and passing value, the AST nodes are passed right in. Calling
the node evaluates the argument and yields the result (this is similar to
to `lazy` parameters in D), and they also have methods like `toSourceCode`,
`type`, and `interpolate`, which forwards to the given string.
The language also supports macros and custom interpolation functions. This
example shows an interpolation string being passed to a macro and used
with a custom interpolation string.
You might use this to encode interpolated things or something like that.
+/
unittest {
var globals = var.emptyObject;
interpret(q{
macro test(x) {
return x.interpolate(function(str) {
return str ~ "test";
});
}
var a = "cool";
assert(test("hey #{a}") == "hey cooltest");
}, globals);
}
/++
$(H3 Classes demo)
See also: [arsd.jsvar.subclassable] for more interop with D classes.
+/
unittest {
var globals = var.emptyObject;
interpret(q{
class Base {
function foo() { return "Base"; }
function set() { this.a = 10; }
function get() { return this.a; } // this MUST be used for instance variables though as they do not exist in static lookup
function test() { return foo(); } // I did NOT use `this` here which means it does STATIC lookup!
// kinda like mixin templates in D lol.
var a = 5;
static var b = 10; // static vars are attached to the class specifically
}
class Child : Base {
function foo() {
assert(super.foo() == "Base");
return "Child";
};
function set() { this.a = 7; }
function get2() { return this.a; }
var a = 9;
}
var c = new Child();
assert(c.foo() == "Child");
assert(c.test() == "Base"); // static lookup of methods if you don't use `this`
/*
// these would pass in D, but do NOT pass here because of dynamic variable lookup in script.
assert(c.get() == 5);
assert(c.get2() == 9);
c.set();
assert(c.get() == 5); // parent instance is separate
assert(c.get2() == 7);
*/
// showing the shared vars now.... I personally prefer the D way but meh, this lang
// is an unholy cross of D and Javascript so that means it sucks sometimes.
assert(c.get() == c.get2());
c.set();
assert(c.get2() == 7);
assert(c.get() == c.get2());
// super, on the other hand, must always be looked up statically, or else this
// next example with infinite recurse and smash the stack.
class Third : Child { }
var t = new Third();
assert(t.foo() == "Child");
}, globals);
}
/++
$(H3 Properties from D)
Note that it is not possible yet to define a property function from the script language.
+/
unittest {
static class Test {
// the @scriptable is required to make it accessible
@scriptable int a;
@scriptable @property int ro() { return 30; }
int _b = 20;
@scriptable @property int b() { return _b; }
@scriptable @property int b(int val) { return _b = val; }
}
Test test = new Test;
test.a = 15;
var globals = var.emptyObject;
globals.test = test;
// but once it is @scriptable, both read and write works from here:
interpret(q{
assert(test.a == 15);
test.a = 10;
assert(test.a == 10);
assert(test.ro == 30); // @property functions from D wrapped too
test.ro = 40;
assert(test.ro == 30); // setting it does nothing though
assert(test.b == 20); // reader still works if read/write available too
test.b = 25;
assert(test.b == 25); // writer action reflected
// however other opAssign operators are not implemented correctly on properties at this time so this fails!
//test.b *= 2;
//assert(test.b == 50);
}, globals);
// and update seen back in D
assert(test.a == 10); // on the original native object
assert(test.b == 25);
assert(globals.test.a == 10); // and via the var accessor for member var
assert(globals.test.b == 25); // as well as @property func
}
public import arsd.jsvar;
import std.stdio;
import std.traits;
import std.conv;
import std.json;
import std.array;
import std.range;
/* **************************************
script to follow
****************************************/
/++
A base class for exceptions that can never be caught by scripts;
throwing it from a function called from a script is guaranteed to
bubble all the way up to your [interpret] call..
(scripts can also never catch Error btw)
History:
Added on April 24, 2020 (v7.3.0)
+/
class NonScriptCatchableException : Exception {
import std.exception;
///
mixin basicExceptionCtors;
}
//class TEST : Throwable {this() { super("lol"); }}
/// Thrown on script syntax errors and the sort.
class ScriptCompileException : Exception {
string s;
int lineNumber;
this(string msg, string s, int lineNumber, string file = __FILE__, size_t line = __LINE__) {
this.s = s;
this.lineNumber = lineNumber;
super(to!string(lineNumber) ~ ": " ~ msg, file, line);
}
}
/// Thrown on things like interpretation failures.
class ScriptRuntimeException : Exception {
string s;
int lineNumber;
this(string msg, string s, int lineNumber, string file = __FILE__, size_t line = __LINE__) {
this.s = s;
this.lineNumber = lineNumber;
super(to!string(lineNumber) ~ ": " ~ msg, file, line);
}
}
/// This represents an exception thrown by `throw x;` inside the script as it is interpreted.
class ScriptException : Exception {
///
var payload;
///
ScriptLocation loc;
///
ScriptLocation[] callStack;
this(var payload, ScriptLocation loc, string file = __FILE__, size_t line = __LINE__) {
this.payload = payload;
if(loc.scriptFilename.length == 0)
loc.scriptFilename = "user_script";
this.loc = loc;
super(loc.scriptFilename ~ "@" ~ to!string(loc.lineNumber) ~ ": " ~ to!string(payload), file, line);
}
/*
override string toString() {
return loc.scriptFilename ~ "@" ~ to!string(loc.lineNumber) ~ ": " ~ payload.get!string ~ to!string(callStack);
}
*/
// might be nice to take a D exception and put a script stack trace in there too......
// also need toString to show the callStack
}
struct ScriptToken {
enum Type { identifier, keyword, symbol, string, int_number, float_number }
Type type;
string str;
string scriptFilename;
int lineNumber;
string wasSpecial;
}
// these need to be ordered from longest to shortest
// some of these aren't actually used, like struct and goto right now, but I want them reserved for later
private enum string[] keywords = [
"function", "continue",
"__FILE__", "__LINE__", // these two are special to the lexer
"foreach", "json!q{", "default", "finally",
"return", "static", "struct", "import", "module", "assert", "switch",
"while", "catch", "throw", "scope", "break", "class", "false", "mixin", "macro", "super",
// "this" is just treated as just a magic identifier.....
"auto", // provided as an alias for var right now, may change later
"null", "else", "true", "eval", "goto", "enum", "case", "cast",
"var", "for", "try", "new",
"if", "do",
];
private enum string[] symbols = [
">>>", // FIXME
"//", "/*", "/+",
"&&", "||",
"+=", "-=", "*=", "/=", "~=", "==", "<=", ">=","!=", "%=",
"&=", "|=", "^=",
"#{",
"..",
"<<", ">>", // FIXME
"|>",
"=>", // FIXME
"?", ".",",",";",":",
"[", "]", "{", "}", "(", ")",
"&", "|", "^",
"+", "-", "*", "/", "=", "<", ">","~","!","%"
];
// we need reference semantics on this all the time
class TokenStream(TextStream) {
TextStream textStream;
string text;
int lineNumber = 1;
string scriptFilename;
void advance(ptrdiff_t size) {
foreach(i; 0 .. size) {
if(text.empty)
break;
if(text[0] == '\n')
lineNumber ++;
text = text[1 .. $];
// text.popFront(); // don't want this because it pops too much trying to do its own UTF-8, which we already handled!
}
}
this(TextStream ts, string fn) {
textStream = ts;
scriptFilename = fn;
text = textStream.front;
popFront;
}
ScriptToken next;
// FIXME: might be worth changing this so i can peek far enough ahead to do () => expr lambdas.
ScriptToken peek;
bool peeked;
void pushFront(ScriptToken f) {
peek = f;
peeked = true;
}
ScriptToken front() {
if(peeked)
return peek;
else
return next;
}
bool empty() {
advanceSkips();
return text.length == 0 && textStream.empty && !peeked;
}
int skipNext;
void advanceSkips() {
if(skipNext) {
skipNext--;
popFront();
}
}
void popFront() {
if(peeked) {
peeked = false;
return;
}
assert(!empty);
mainLoop:
while(text.length) {
ScriptToken token;
token.lineNumber = lineNumber;
token.scriptFilename = scriptFilename;
if(text[0] == ' ' || text[0] == '\t' || text[0] == '\n' || text[0] == '\r') {
advance(1);
continue;
} else if(text[0] >= '0' && text[0] <= '9') {
int pos;
bool sawDot;
while(pos < text.length && ((text[pos] >= '0' && text[pos] <= '9') || text[pos] == '.')) {
if(text[pos] == '.') {
if(sawDot)
break;
else
sawDot = true;
}
pos++;
}
if(text[pos - 1] == '.') {
// This is something like "1.x", which is *not* a floating literal; it is UFCS on an int
sawDot = false;
pos --;
}
token.type = sawDot ? ScriptToken.Type.float_number : ScriptToken.Type.int_number;
token.str = text[0 .. pos];
advance(pos);
} else if((text[0] >= 'a' && text[0] <= 'z') || (text[0] == '_') || (text[0] >= 'A' && text[0] <= 'Z') || text[0] == '$') {
bool found = false;
foreach(keyword; keywords)
if(text.length >= keyword.length && text[0 .. keyword.length] == keyword &&
// making sure this isn't an identifier that starts with a keyword
(text.length == keyword.length || !(
(
(text[keyword.length] >= '0' && text[keyword.length] <= '9') ||
(text[keyword.length] >= 'a' && text[keyword.length] <= 'z') ||
(text[keyword.length] == '_') ||
(text[keyword.length] >= 'A' && text[keyword.length] <= 'Z')
)
)))
{
found = true;
if(keyword == "__FILE__") {
token.type = ScriptToken.Type.string;
token.str = to!string(token.scriptFilename);
token.wasSpecial = keyword;
} else if(keyword == "__LINE__") {
token.type = ScriptToken.Type.int_number;
token.str = to!string(token.lineNumber);
token.wasSpecial = keyword;
} else {
token.type = ScriptToken.Type.keyword;
// auto is done as an alias to var in the lexer just so D habits work there too
if(keyword == "auto") {
token.str = "var";
token.wasSpecial = keyword;
} else
token.str = keyword;
}
advance(keyword.length);
break;
}
if(!found) {
token.type = ScriptToken.Type.identifier;
int pos;
if(text[0] == '$')
pos++;
while(pos < text.length
&& ((text[pos] >= 'a' && text[pos] <= 'z') ||
(text[pos] == '_') ||
//(pos != 0 && text[pos] == '-') || // allow mid-identifier dashes for this-kind-of-name. For subtraction, add a space.
(text[pos] >= 'A' && text[pos] <= 'Z') ||
(text[pos] >= '0' && text[pos] <= '9')))
{
pos++;
}
token.str = text[0 .. pos];
advance(pos);
}
} else if(text[0] == '"' || text[0] == '\'' || text[0] == '`' ||
// Also supporting double curly quoted strings: “foo” which nest. This is the utf 8 coding:
(text.length >= 3 && text[0] == 0xe2 && text[1] == 0x80 && text[2] == 0x9c))
{
char end = text[0]; // support single quote and double quote strings the same
int openCurlyQuoteCount = (end == 0xe2) ? 1 : 0;
bool escapingAllowed = end != '`'; // `` strings are raw, they don't support escapes. the others do.
token.type = ScriptToken.Type.string;
int pos = openCurlyQuoteCount ? 3 : 1; // skip the opening dchar
int started = pos;
bool escaped = false;
bool mustCopy = false;
bool allowInterpolation = text[0] == '"';
bool atEnd() {
if(pos == text.length)
return false;
if(openCurlyQuoteCount) {
if(openCurlyQuoteCount == 1)
return (pos + 3 <= text.length && text[pos] == 0xe2 && text[pos+1] == 0x80 && text[pos+2] == 0x9d); // ”
else // greater than one means we nest
return false;
} else
return text[pos] == end;
}
bool interpolationDetected = false;
bool inInterpolate = false;
int interpolateCount = 0;
while(pos < text.length && (escaped || inInterpolate || !atEnd())) {
if(inInterpolate) {
if(text[pos] == '{')
interpolateCount++;
else if(text[pos] == '}') {
interpolateCount--;
if(interpolateCount == 0)
inInterpolate = false;
}
pos++;
continue;
}
if(escaped) {
mustCopy = true;
escaped = false;
} else {
if(text[pos] == '\\' && escapingAllowed)
escaped = true;
if(allowInterpolation && text[pos] == '#' && pos + 1 < text.length && text[pos + 1] == '{') {
interpolationDetected = true;
inInterpolate = true;
}
if(openCurlyQuoteCount) {
// also need to count curly quotes to support nesting
if(pos + 3 <= text.length && text[pos+0] == 0xe2 && text[pos+1] == 0x80 && text[pos+2] == 0x9c) // “
openCurlyQuoteCount++;
if(pos + 3 <= text.length && text[pos+0] == 0xe2 && text[pos+1] == 0x80 && text[pos+2] == 0x9d) // ”
openCurlyQuoteCount--;
}
}
pos++;
}
if(pos == text.length && (escaped || inInterpolate || !atEnd()))
throw new ScriptCompileException("Unclosed string literal", token.scriptFilename, token.lineNumber);
if(mustCopy) {
// there must be something escaped in there, so we need
// to copy it and properly handle those cases
string copy;
copy.reserve(pos + 4);
escaped = false;
foreach(idx, dchar ch; text[started .. pos]) {
if(escaped) {
escaped = false;
switch(ch) {
case '\\': copy ~= "\\"; break;
case 'n': copy ~= "\n"; break;
case 'r': copy ~= "\r"; break;
case 'a': copy ~= "\a"; break;
case 't': copy ~= "\t"; break;
case '#': copy ~= "#"; break;
case '"': copy ~= "\""; break;
case '\'': copy ~= "'"; break;
default:
throw new ScriptCompileException("Unknown escape char " ~ cast(char) ch, token.scriptFilename, token.lineNumber);
}
continue;
} else if(ch == '\\') {
escaped = true;
continue;
}
copy ~= ch;
}
token.str = copy;
} else {
token.str = text[started .. pos];
}
if(interpolationDetected)
token.wasSpecial = "\"";
advance(pos + ((end == 0xe2) ? 3 : 1)); // skip the closing " too
} else {
// let's check all symbols
bool found = false;
foreach(symbol; symbols)
if(text.length >= symbol.length && text[0 .. symbol.length] == symbol) {
if(symbol == "//") {
// one line comment
int pos = 0;
while(pos < text.length && text[pos] != '\n' && text[0] != '\r')
pos++;
advance(pos);
continue mainLoop;
} else if(symbol == "/*") {
int pos = 0;
while(pos + 1 < text.length && text[pos..pos+2] != "*/")
pos++;
if(pos + 1 == text.length)
throw new ScriptCompileException("unclosed /* */ comment", token.scriptFilename, lineNumber);
advance(pos + 2);
continue mainLoop;
} else if(symbol == "/+") {
int open = 0;
int pos = 0;
while(pos + 1 < text.length) {
if(text[pos..pos+2] == "/+") {
open++;
pos++;
} else if(text[pos..pos+2] == "+/") {
open--;
pos++;
if(open == 0)
break;
}
pos++;
}
if(pos + 1 == text.length)
throw new ScriptCompileException("unclosed /+ +/ comment", token.scriptFilename, lineNumber);
advance(pos + 1);
continue mainLoop;
}
// FIXME: documentation comments
found = true;
token.type = ScriptToken.Type.symbol;
token.str = symbol;
advance(symbol.length);
break;
}
if(!found) {
// FIXME: make sure this gives a valid utf-8 sequence
throw new ScriptCompileException("unknown token " ~ text[0], token.scriptFilename, lineNumber);
}
}
next = token;
return;
}
textStream.popFront();
if(!textStream.empty()) {
text = textStream.front;
goto mainLoop;
}
return;
}
}
TokenStream!TextStream lexScript(TextStream)(TextStream textStream, string scriptFilename) if(is(ElementType!TextStream == string)) {
return new TokenStream!TextStream(textStream, scriptFilename);
}
class MacroPrototype : PrototypeObject {
var func;
// macros are basically functions that get special treatment for their arguments
// they are passed as AST objects instead of interpreted
// calling an AST object will interpret it in the script
this(var func) {
this.func = func;
this._properties["opCall"] = (var _this, var[] args) {
return func.apply(_this, args);
};
}
}
alias helper(alias T) = T;
// alternative to virtual function for converting the expression objects to script objects
void addChildElementsOfExpressionToScriptExpressionObject(ClassInfo c, Expression _thisin, PrototypeObject sc, ref var obj) {
foreach(itemName; __traits(allMembers, mixin(__MODULE__)))
static if(__traits(compiles, __traits(getMember, mixin(__MODULE__), itemName))) {
alias Class = helper!(__traits(getMember, mixin(__MODULE__), itemName));
static if(is(Class : Expression)) if(c == typeid(Class)) {
auto _this = cast(Class) _thisin;
foreach(memberName; __traits(allMembers, Class)) {
alias member = helper!(__traits(getMember, Class, memberName));
static if(is(typeof(member) : Expression)) {
auto lol = __traits(getMember, _this, memberName);
if(lol is null)
obj[memberName] = null;
else
obj[memberName] = lol.toScriptExpressionObject(sc);
}
static if(is(typeof(member) : Expression[])) {
obj[memberName] = var.emptyArray;
foreach(m; __traits(getMember, _this, memberName))
if(m !is null)
obj[memberName] ~= m.toScriptExpressionObject(sc);
else
obj[memberName] ~= null;
}
static if(is(typeof(member) : string) || is(typeof(member) : long) || is(typeof(member) : real) || is(typeof(member) : bool)) {
obj[memberName] = __traits(getMember, _this, memberName);
}
}
}
}
}
struct InterpretResult {
var value;
PrototypeObject sc;
enum FlowControl { Normal, Return, Continue, Break, Goto }
FlowControl flowControl;
string flowControlDetails; // which label
}
class Expression {
abstract InterpretResult interpret(PrototypeObject sc);
// this returns an AST object that can be inspected and possibly altered
// by the script. Calling the returned object will interpret the object in
// the original scope passed
var toScriptExpressionObject(PrototypeObject sc) {
var obj = var.emptyObject;
obj["type"] = typeid(this).name;
obj["toSourceCode"] = (var _this, var[] args) {
Expression e = this;
return var(e.toString());
};
obj["opCall"] = (var _this, var[] args) {
Expression e = this;
// FIXME: if they changed the properties in the
// script, we should update them here too.
return e.interpret(sc).value;
};
obj["interpolate"] = (var _this, var[] args) {
StringLiteralExpression e = cast(StringLiteralExpression) this;
if(!e)
return var(null);
return e.interpolate(args.length ? args[0] : var(null), sc);
};
// adding structure is going to be a little bit magical
// I could have done this with a virtual function, but I'm lazy.
addChildElementsOfExpressionToScriptExpressionObject(typeid(this), this, sc, obj);
return obj;
}
string toInterpretedString(PrototypeObject sc) {
return toString();
}