forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsvar.d
2971 lines (2529 loc) · 80.4 KB
/
jsvar.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
/*
FIXME:
overloads can be done as an object representing the overload set
tat opCall does the dispatch. Then other overloads can actually
be added more sanely.
FIXME:
instantiate template members when reflection with certain
arguments if marked right...
FIXME:
pointer to member functions can give a way to wrap things
we'll pass it an opaque object as this and it will unpack and call the method
we can also auto-generate getters and setters for properties with this method
and constructors, so the script can create class objects too
*/
/++
jsvar provides a D type called [var] that works similarly to the same in Javascript.
It is weakly (even weaker than JS, frequently returning null rather than throwing on
an invalid operation) and dynamically typed, but interops pretty easily with D itself:
---
var a = 10;
a ~= "20";
assert(a == "1020");
var a = function(int b, int c) { return b+c; };
// note the second set of () is because of broken @property
assert(a()(10,20) == 30);
var a = var.emptyObject;
a.foo = 30;
assert(a["foo"] == 30);
var b = json!q{
"foo":12,
"bar":{"hey":[1,2,3,"lol"]}
};
assert(b.bar.hey[1] == 2);
---
You can also use [var.fromJson], a static method, to quickly and easily
read json or [var.toJson] to write it.
Also, if you combine this with my [arsd.script] module, you get pretty
easy interop with a little scripting language that resembles a cross between
D and Javascript - just like you can write in D itself using this type.
Please note that function default arguments are NOT likely to work in the script.
You'd have to use a helper thing that I haven't written yet. opAssign can never
do it because that information is lost when it becomes a pointer. ParamDefault
is thus commented out for now.
Properties:
$(LIST
* note that @property doesn't work right in D, so the opDispatch properties
will require double parenthesis to call as functions.
* Properties inside a var itself are set specially:
obj.propName._object = new PropertyPrototype(getter, setter);
)
D structs can be turned to vars, but it is a copy.
Wrapping D native objects is coming later, the current ways suck. I really needed
properties to do them sanely at all, and now I have it. A native wrapped object will
also need to be set with _object prolly.
Author: Adam D Ruppe
History: Started in July 2013.
+/
module arsd.jsvar;
version=new_std_json;
static import std.array;
import std.traits;
import std.conv;
import std.json;
version(jsvar_throw)
/++
Variable to decide if jsvar throws on certain invalid
operations or continues on propagating null vars.
+/
bool jsvar_throw = true;
else
/// ditto
bool jsvar_throw = false;
// uda for wrapping classes
enum scriptable = "arsd_jsvar_compatible";
/*
PrototypeObject FIXME:
make undefined variables reaction overloadable in PrototypeObject, not just a switch
script FIXME:
the Expression should keep scriptFilename and lineNumber around for error messages
it should consistently throw on missing semicolons
*) in operator
*) nesting comments, `` string literals
*) opDispatch overloading
*) properties???//
a.prop on the rhs => a.prop()
a.prop on the lhs => a.prop(rhs);
if opAssign, it can just do a.prop(a.prop().opBinary!op(rhs));
But, how do we mark properties in var? Can we make them work this way in D too?
0) add global functions to the object (or at least provide a convenience function to make a pre-populated global object)
1) ensure operator precedence is sane
2) a++ would prolly be nice, and def -a
4) switches?
10) __FILE__ and __LINE__ as default function arguments should work like in D
16) stack traces on script exceptions
17) an exception type that we can create in the script
14) import???????/ it could just attach a particular object to the local scope, and the module decl just giving the local scope a name
there could be a super-global object that is the prototype of the "global" used here
then you import, and it pulls moduleGlobal.prototype = superGlobal.modulename... or soemthing.
to get the vars out in D, you'd have to be aware of this, since you pass the superglobal
hmmm maybe not worth it
though maybe to export vars there could be an explicit export namespace or something.
6) gotos? labels? labeled break/continue?
18) what about something like ruby's blocks or macros? parsing foo(arg) { code } is easy enough, but how would we use it?
var FIXME:
user defined operator overloading on objects, including opCall, opApply, and more
flesh out prototype objects for Array, String, and Function
looserOpEquals
it would be nice if delegates on native types could work
*/
static if(__VERSION__ <= 2076) {
// compatibility shims with gdc
enum JSONType {
object = JSON_TYPE.OBJECT,
null_ = JSON_TYPE.NULL,
false_ = JSON_TYPE.FALSE,
true_ = JSON_TYPE.TRUE,
integer = JSON_TYPE.INTEGER,
float_ = JSON_TYPE.FLOAT,
array = JSON_TYPE.ARRAY,
string = JSON_TYPE.STRING,
uinteger = JSON_TYPE.UINTEGER
}
}
/*
Script notes:
the one type is var. It works just like the var type in D from arsd.jsvar.
(it might be fun to try to add other types, and match D a little better here! We could allow implicit conversion to and from var, but not on the other types, they could get static checking. But for now it is only var. BTW auto is an alias for var right now)
There is no comma operator, but you can use a scope as an expression: a++, b++; can be written as {a++;b++;}
*/
version(test_script)
struct Foop {
int a = 12;
string n = "hate";
void speak() { writeln(n, " ", a); n = "love"; writeln(n, " is what it is now"); }
void speak2() { writeln("speak2 ", n, " ", a); }
}
version(test_script)
void main() {
import arsd.script;
writeln(interpret("x*x + 3*x;", var(["x":3])));
{
var a = var.emptyObject;
a.qweq = 12;
}
// the WrappedNativeObject is disgusting
// but works. sort of.
/*
Foop foop2;
var foop;
foop._object = new WrappedNativeObject!Foop(foop2);
foop.speak()();
foop.a = 25;
writeln(foop.n);
foop.speak2()();
return;
*/
import arsd.script;
struct Test {
int a = 10;
string name = "ten";
}
auto globals = var.emptyObject;
globals.lol = 100;
globals.rofl = 23;
globals.arrtest = var.emptyArray;
globals.write._function = (var _this, var[] args) {
string s;
foreach(a; args)
s ~= a.get!string;
writeln("script said: ", s);
return var(null);
};
// call D defined functions in script
globals.func = (var a, var b) { writeln("Hello, world! You are : ", a, " and ", b); };
globals.ex = () { throw new ScriptRuntimeException("test", 1); };
globals.fun = { return var({ writeln("hello inside!"); }); };
import std.file;
writeln(interpret(readText("scripttest_code.d"), globals));
globals.ten = 10.0;
globals.five = 5.0;
writeln(interpret(q{
var a = json!q{ };
a.b = json!q{ };
a.b.c = 10;
a;
}, globals));
/*
globals.minigui = json!q{};
import arsd.minigui;
globals.minigui.createWindow = {
var v;
auto mw = new MainWindow();
v._object = new OpaqueNativeObject!(MainWindow)(mw);
v.loop = { mw.loop(); };
return v;
};
*/
repl(globals);
writeln("BACK IN D!");
globals.c()(10); // call script defined functions in D (note: this runs the interpreter)
//writeln(globals._getMember("lol", false));
return;
var k,l ;
var j = json!q{
"hello": {
"data":[1,2,"giggle",4]
},
"world":20
};
writeln(j.hello.data[2]);
Test t;
var rofl = t;
writeln(rofl.name);
writeln(rofl.a);
rofl.a = "20";
rofl.name = "twenty";
t = rofl.get!Test;
writeln(t);
var a1 = 10;
a1 -= "5";
a1 /= 2;
writeln(a1);
var a = 10;
var b = 20;
a = b;
b = 30;
a += 100.2;
writeln(a);
var c = var.emptyObject;
c.a = b;
var d = c;
d.b = 50;
writeln(c.b);
writeln(d.toJson());
var e = a + b;
writeln(a, " + ", b, " = ", e);
e = function(var lol) {
writeln("hello with ",lol,"!");
return lol + 10;
};
writeln(e("15"));
if(var("ass") > 100)
writeln(var("10") / "3");
}
template json(string s) {
// ctfe doesn't support the unions std.json uses :(
//enum json = var.fromJsonObject(s);
// FIXME we should at least validate string s at compile time
var json() {
return var.fromJson("{" ~ s ~ "}");
}
}
// literals
// var a = varArray(10, "cool", 2);
// assert(a[0] == 10); assert(a[1] == "cool"); assert(a[2] == 2);
var varArray(T...)(T t) {
var a = var.emptyArray;
foreach(arg; t)
a ~= var(arg);
return a;
}
// var a = varObject("cool", 10, "bar", "baz");
// assert(a.cool == 10 && a.bar == "baz");
var varObject(T...)(T t) {
var a = var.emptyObject;
string lastString;
foreach(idx, arg; t) {
static if(idx % 2 == 0) {
lastString = arg;
} else {
assert(lastString !is null);
a[lastString] = arg;
lastString = null;
}
}
return a;
}
private double stringToNumber(string s) {
double r;
try {
r = to!double(s);
} catch (Exception e) {
r = double.nan;
}
return r;
}
private bool doubleIsInteger(double r) {
return (r == cast(long) r);
}
// helper template for operator overloading
private var _op(alias _this, alias this2, string op, T)(T t) if(op == "~") {
static if(is(T == var)) {
if(t.payloadType() == var.Type.Array)
return _op!(_this, this2, op)(t._payload._array);
else if(t.payloadType() == var.Type.String)
return _op!(_this, this2, op)(t._payload._string);
//else
//return _op!(_this, this2, op)(t.get!string);
}
if(this2.payloadType() == var.Type.Array) {
auto l = this2._payload._array;
static if(isArray!T && !isSomeString!T)
foreach(item; t)
l ~= var(item);
else
l ~= var(t);
_this._type = var.Type.Array;
_this._payload._array = l;
return _this;
} else if(this2.payloadType() == var.Type.String) {
auto l = this2._payload._string;
l ~= var(t).get!string; // is this right?
_this._type = var.Type.String;
_this._payload._string = l;
return _this;
} else {
auto l = this2.get!string;
l ~= var(t).get!string;
_this._type = var.Type.String;
_this._payload._string = l;
return _this;
}
assert(0);
}
// FIXME: maybe the bitops should be moved out to another function like ~ is
private var _op(alias _this, alias this2, string op, T)(T t) if(op != "~") {
static if(is(T == var)) {
if(t.payloadType() == var.Type.Integral)
return _op!(_this, this2, op)(t._payload._integral);
if(t.payloadType() == var.Type.Floating)
return _op!(_this, this2, op)(t._payload._floating);
if(t.payloadType() == var.Type.String)
return _op!(_this, this2, op)(t._payload._string);
throw new Exception("Attempted invalid operator `" ~ op ~ "` on variable of type " ~ to!string(t.payloadType()));
} else {
if(this2.payloadType() == var.Type.Integral) {
auto l = this2._payload._integral;
static if(isIntegral!T) {
mixin("l "~op~"= t;");
_this._type = var.Type.Integral;
_this._payload._integral = l;
return _this;
} else static if(isFloatingPoint!T) {
static if(op == "&" || op == "|" || op == "^" || op == "<<" || op == ">>" || op == ">>>") {
this2._type = var.Type.Integral;
long f = l;
mixin("f "~op~"= cast(long) t;");
_this._type = var.Type.Integral;
_this._payload._integral = f;
} else {
this2._type = var.Type.Floating;
double f = l;
mixin("f "~op~"= t;");
_this._type = var.Type.Floating;
_this._payload._floating = f;
}
return _this;
} else static if(isSomeString!T) {
auto rhs = stringToNumber(t);
if(doubleIsInteger(rhs)) {
mixin("l "~op~"= cast(long) rhs;");
_this._type = var.Type.Integral;
_this._payload._integral = l;
} else{
static if(op == "&" || op == "|" || op == "^" || op == "<<" || op == ">>" || op == ">>>") {
long f = l;
mixin("f "~op~"= cast(long) rhs;");
_this._type = var.Type.Integral;
_this._payload._integral = f;
} else {
double f = l;
mixin("f "~op~"= rhs;");
_this._type = var.Type.Floating;
_this._payload._floating = f;
}
}
return _this;
}
} else if(this2.payloadType() == var.Type.Floating) {
auto f = this._payload._floating;
static if(isIntegral!T || isFloatingPoint!T) {
static if(op == "&" || op == "|" || op == "^" || op == "<<" || op == ">>" || op == ">>>") {
long argh = cast(long) f;
mixin("argh "~op~"= cast(long) t;");
_this._type = var.Type.Integral;
_this._payload._integral = argh;
} else {
mixin("f "~op~"= t;");
_this._type = var.Type.Floating;
_this._payload._floating = f;
}
return _this;
} else static if(isSomeString!T) {
auto rhs = stringToNumber(t);
static if(op == "&" || op == "|" || op == "^" || op == "<<" || op == ">>" || op == ">>>") {
long pain = cast(long) f;
mixin("pain "~op~"= cast(long) rhs;");
_this._type = var.Type.Integral;
_this._payload._floating = pain;
} else {
mixin("f "~op~"= rhs;");
_this._type = var.Type.Floating;
_this._payload._floating = f;
}
return _this;
} else static assert(0);
} else if(this2.payloadType() == var.Type.String) {
static if(op == "&" || op == "|" || op == "^" || op == "<<" || op == ">>" || op == ">>>") {
long r = cast(long) stringToNumber(this2._payload._string);
long rhs;
} else {
double r = stringToNumber(this2._payload._string);
double rhs;
}
static if(isSomeString!T) {
rhs = cast(typeof(rhs)) stringToNumber(t);
} else {
rhs = to!(typeof(rhs))(t);
}
mixin("r " ~ op ~ "= rhs;");
static if(is(typeof(r) == double)) {
_this._type = var.Type.Floating;
_this._payload._floating = r;
} else static if(is(typeof(r) == long)) {
_this._type = var.Type.Integral;
_this._payload._integral = r;
} else static assert(0);
return _this;
} else {
// the operation is nonsensical, we should throw or ignore it
var i = 0;
return i;
}
}
assert(0);
}
///
struct var {
public this(T)(T t) {
static if(is(T == var))
this = t;
else
this.opAssign(t);
}
// used by the script interpreter... does a .dup on array, new on class if possible, otherwise copies members.
public var _copy_new() {
if(payloadType() == Type.Object) {
var cp;
if(this._payload._object !is null) {
auto po = this._payload._object.new_(null);
cp._object = po;
}
return cp;
} else if(payloadType() == Type.Array) {
var cp;
cp = this._payload._array.dup;
return cp;
} else {
return this._copy();
}
}
public var _copy() {
final switch(payloadType()) {
case Type.Integral:
case Type.Boolean:
case Type.Floating:
case Type.Function:
case Type.String:
// since strings are immutable, we can pretend they are value types too
return this; // value types don't need anything special to be copied
case Type.Array:
var cp;
cp = this._payload._array[];
return cp;
case Type.Object:
var cp;
if(this._payload._object !is null)
cp._object = this._payload._object.copy;
return cp;
}
}
/// `if(some_var)` will call this and give behavior based on the dynamic type. Shouldn't be too surprising.
public bool opCast(T:bool)() {
final switch(this._type) {
case Type.Object:
return this._payload._object !is null;
case Type.Array:
return this._payload._array.length != 0;
case Type.String:
return this._payload._string.length != 0;
case Type.Integral:
return this._payload._integral != 0;
case Type.Floating:
return this._payload._floating != 0;
case Type.Boolean:
return this._payload._boolean;
case Type.Function:
return this._payload._function !is null;
}
}
/// You can foreach over a var.
public int opApply(scope int delegate(ref var) dg) {
foreach(i, item; this)
if(auto result = dg(item))
return result;
return 0;
}
/// ditto
public int opApply(scope int delegate(var, ref var) dg) {
if(this.payloadType() == Type.Array) {
foreach(i, ref v; this._payload._array)
if(auto result = dg(var(i), v))
return result;
} else if(this.payloadType() == Type.Object && this._payload._object !is null) {
// FIXME: if it offers input range primitives, we should use them
// FIXME: user defined opApply on the object
foreach(k, ref v; this._payload._object)
if(auto result = dg(var(k), v))
return result;
} else if(this.payloadType() == Type.String) {
// this is to prevent us from allocating a new string on each character, hopefully limiting that massively
static immutable string chars = makeAscii!();
foreach(i, dchar c; this._payload._string) {
var lol = "";
if(c < 128)
lol._payload._string = chars[c .. c + 1];
else
lol._payload._string = to!string(""d ~ c); // blargh, how slow can we go?
if(auto result = dg(var(i), lol))
return result;
}
}
// throw invalid foreach aggregate
return 0;
}
/// Alias for [get]. e.g. `string s = cast(string) v;`
public T opCast(T)() {
return this.get!T;
}
/// Calls [get] for a type automatically. `int a; var b; b.putInto(a);` will auto-convert to `int`.
public auto ref putInto(T)(ref T t) {
return t = this.get!T;
}
/++
Assigns a value to the var. It will do necessary implicit conversions
and wrapping.
You can make a method `toArsdJsvar` on your own objects to override this
default. It should return a [var].
History:
On April 20, 2020, I changed the default mode for class assignment
to [wrapNativeObject]. Previously it was [wrapOpaquely].
With the new [wrapNativeObject] behavior, you can mark methods
@[scriptable] to expose them to the script.
+/
public var opAssign(T)(T t) if(!is(T == var)) {
static if(__traits(compiles, this = t.toArsdJsvar())) {
static if(__traits(compiles, t is null)) {
if(t is null)
this = null;
else
this = t.toArsdJsvar();
} else
this = t.toArsdJsvar();
} else static if(is(T : PrototypeObject)) {
// support direct assignment of pre-made implementation objects
// so prewrapped stuff can be easily passed.
this._type = Type.Object;
this._payload._object = t;
} else static if(is(T == enum)) {
this._type = Type.String;
this._payload._string = to!string(t);
} else static if(isFloatingPoint!T) {
this._type = Type.Floating;
this._payload._floating = t;
} else static if(isIntegral!T) {
this._type = Type.Integral;
this._payload._integral = t;
} else static if(isCallable!T) {
this._type = Type.Function;
static if(is(T == typeof(this._payload._function))) {
this._payload._function = t;
} else
this._payload._function = delegate var(var _this, var[] args) {
var ret;
ParameterTypeTuple!T fargs;
// default args? nope they can't work cuz it is assigning a function pointer by here. alas.
enum lol = static_foreach(fargs.length, 1, -1,
`t(`,``,` < args.length ? args[`,`].get!(typeof(fargs[`,`])) : typeof(fargs[`,`]).init,`,`)`);
//`t(`,``,` < args.length ? args[`,`].get!(typeof(fargs[`,`])) : ParamDefault!(T, `,`)(),`,`)`);
/+
foreach(idx, a; fargs) {
if(idx == args.length)
break;
cast(Unqual!(typeof(a))) fargs[idx] = args[idx].get!(typeof(a));
}
+/
static if(is(ReturnType!t == void)) {
//t(fargs);
mixin(lol ~ ";");
} else {
//ret = t(fargs);
ret = mixin(lol);
}
return ret;
};
} else static if(isSomeString!T) {
this._type = Type.String;
this._payload._string = to!string(t);
} else static if(is(T == class) || is(T == interface)) {
if(t !is null && (cast(Object) t) is null)
throw new Exception("Unsupported class or interface");
this._type = Type.Object;
this._payload._object = t is null ? null : wrapNativeObject(t);
} else static if(.isScriptableOpaque!T) {
// auto-wrap other classes with reference semantics
this._type = Type.Object;
this._payload._object = wrapOpaquely(t);
} else static if(is(T == struct) || isAssociativeArray!T) {
// copy structs and assoc arrays by value into a var object
this._type = Type.Object;
auto obj = new PrototypeObject();
this._payload._object = obj;
static if(is(T == struct))
foreach(member; __traits(allMembers, T)) {
static if(__traits(compiles, __traits(getMember, t, member))) {
static if(is(typeof(__traits(getMember, t, member)) == function)) {
// skipping these because the delegate we get isn't going to work anyway; the object may be dead and certainly won't be updated
//this[member] = &__traits(getMember, proxyObject, member);
// but for simple toString, I'll allow it by recreating the object on demand
// and then calling the original function. (I might be able to do that for more but
// idk, just doing simple thing first)
static if(member == "toString" && is(typeof(&__traits(getMember, t, member)) == string delegate())) {
this[member]._function = delegate(var _this, var[] args) {
auto val = _this.get!T;
return var(val.toString());
};
}
} else static if(is(typeof(__traits(getMember, t, member)))) {
static if(!is(typeof(__traits(getMember, t, member)) == void))
this[member] = __traits(getMember, t, member);
}
}
} else {
// assoc array
foreach(l, v; t) {
this[var(l)] = var(v);
}
}
} else static if(isArray!T) {
this._type = Type.Array;
var[] arr;
arr.length = t.length;
static if(!is(T == void[])) // we can't append a void array but it is nice to support x = [];
foreach(i, item; t)
arr[i] = var(item);
this._payload._array = arr;
} else static if(is(T == bool)) {
this._type = Type.Boolean;
this._payload._boolean = t;
} else static if(isSomeChar!T) {
this._type = Type.String;
this._payload._string = "";
import std.utf;
char[4] ugh;
auto size = encode(ugh, t);
this._payload._string = ugh[0..size].idup;
}// else static assert(0, "unsupported type");
return this;
}
public size_t opDollar() {
return this.length().get!size_t;
}
public var opOpAssign(string op, T)(T t) {
if(payloadType() == Type.Object) {
if(auto pt = cast(PropertyPrototype) this._payload._object) {
auto propValue = pt.get;
auto result = propValue.opOpAssign!(op)(t);
pt.set(result);
return result;
} else if(this._payload._object !is null) {
var* operator = this._payload._object._peekMember("opOpAssign", true);
if(operator !is null && operator._type == Type.Function)
return operator.call(this, op, t);
}
}
return _op!(this, this, op, T)(t);
}
public var opUnary(string op : "-")() {
static assert(op == "-");
final switch(payloadType()) {
case Type.Object:
case Type.Array:
case Type.Boolean:
case Type.String:
case Type.Function:
assert(0); // FIXME
//break;
case Type.Integral:
return var(-this.get!long);
case Type.Floating:
return var(-this.get!double);
}
}
public var opBinary(string op, T)(T t) {
var n;
if(payloadType() == Type.Object) {
if(this._payload._object is null)
return var(null);
var* operator = this._payload._object._peekMember("opBinary", true);
if(operator !is null && operator._type == Type.Function) {
return operator.call(this, op, t);
}
}
return _op!(n, this, op, T)(t);
}
public var opBinaryRight(string op, T)(T s) {
return var(s).opBinary!op(this);
}
// this in foo
public var* opBinary(string op : "in", T)(T s) {
var rhs = var(s);
return rhs.opBinaryRight!"in"(this);
}
// foo in this
public var* opBinaryRight(string op : "in", T)(T s) {
// this needs to be an object
if(this._object is null)
return null;
return var(s).get!string in this._object._properties;
}
public var apply(var _this, var[] args) {
if(this.payloadType() == Type.Function) {
if(this._payload._function is null) {
if(jsvar_throw)
throw new DynamicTypeException(this, Type.Function);
else
return var(null);
}
return this._payload._function(_this, args);
} else if(this.payloadType() == Type.Object) {
if(this._payload._object is null) {
if(jsvar_throw)
throw new DynamicTypeException(this, Type.Function);
else
return var(null);
}
var* operator = this._payload._object._peekMember("opCall", true);
if(operator !is null && operator._type == Type.Function)
return operator.apply(_this, args);
}
if(this.payloadType() == Type.Integral || this.payloadType() == Type.Floating) {
if(args.length)
return var(this.get!double * args[0].get!double);
else
return this;
} else if(jsvar_throw) {
throw new DynamicTypeException(this, Type.Function);
}
//return this;
return var(null);
}
public var call(T...)(var _this, T t) {
var[] args;
foreach(a; t) {
args ~= var(a);
}
return this.apply(_this, args);
}
public var opCall(T...)(T t) {
return this.call(this, t);
}
/*
public var applyWithMagicLocals(var _this, var[] args, var[string] magicLocals) {
}
*/
public string toString() {
return this.get!string;
}
public T getWno(T)() {
if(payloadType == Type.Object) {
if(auto wno = cast(WrappedNativeObject) this._payload._object) {
auto no = cast(T) wno.getObject();
if(no !is null)
return no;
}
}
return null;
}
/++
Gets the var converted to type `T` as best it can. `T` may be constructed
from `T.fromJsVar`, or through type conversions (coercing as needed). If
`T` happens to be a struct, it will automatically introspect to convert
the var object member-by-member.
History:
On April 21, 2020, I changed the behavior of
---
var a = null;
string b = a.get!string;
---
Previously, `b == "null"`, which would print the word
when writeln'd. Now, `b is null`, which prints the empty string,
which is a bit less user-friendly, but more consistent with
converting to/from D strings in general.
If you are printing, you can check `a.get!string is null` and print
null at that point if you like.
I also wrote the first draft of this documentation at that time,
even though the function has been public since the beginning.
On January 1, 2021, I changed `get!some_struct` to call properties
on the var, if a member looks like a function or object, to try to
get plain-old-data out. Since the functions are only ever put there
by you or by you allowing script, I don't feel too bad about it, but
it still might not be ideal for all circumstances, so idk if I'll leave
it this way or not.
One thing it helps for though is taking scripted subclasses back into D
structs, since the parent class thing is likely to be virtual properties.
And having that just work in argument lists is really cool...
Search function for the comment "property getter support" to see the impl.
+/
public T get(T)() if(!is(T == void)) {
static if(is(T == var)) {
return this;
} else static if(__traits(compiles, T.fromJsVar(var.init))) {
return T.fromJsVar(this);
} else static if(__traits(compiles, T(this))) {
return T(this);
} else static if(__traits(compiles, new T(this))) {
return new T(this);
} else
final switch(payloadType) {
case Type.Boolean:
static if(is(T == bool))
return this._payload._boolean;
else static if(isFloatingPoint!T || isIntegral!T)
return cast(T) (this._payload._boolean ? 1 : 0); // the cast is for enums, I don't like this so FIXME
else static if(isSomeString!T)
return to!T(this._payload._boolean ? "true" : "false");
else
return T.init;