/
Kernel.cs
1887 lines (1658 loc) · 67.4 KB
/
Kernel.cs
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
using System;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices;
namespace Niecza {
// We like to reuse continuation objects for speed - every function only
// creates one kind of continuation, but tweaks a field for exact return
// point. As such, call frames and continuations are in 1:1 correspondence
// and are unified. Functions take a current continuation and return a new
// continuation; we tail recurse with trampolines.
// Only call other functions in Continue, not in the CallableDelegate or
// equivalent!
public delegate Frame CallableDelegate(Frame caller,
Variable[] pos, Dictionary<string, Variable> named);
// Used by DynFrame to plug in code
public delegate Frame DynBlockDelegate(Frame frame);
public abstract class IP6 {
public DynMetaObject mo;
public virtual object GetSlot(string name) {
throw new InvalidOperationException("no slots in this repr");
}
public virtual void SetSlot(string name, object v) {
throw new InvalidOperationException("no slots in this repr");
}
protected Frame Fail(Frame caller, string msg) {
return Kernel.Die(caller, msg + " in class " + mo.name);
}
// Most reprs won't have a concept of type objects
public virtual bool IsDefined() { return true; }
public Frame HOW(Frame caller) {
caller.resultSlot = mo.how;
return caller;
}
// include the invocant in the positionals! it will not usually be
// this, rather a container of this
public virtual Frame InvokeMethod(Frame caller, string name,
Variable[] pos, Dictionary<string, Variable> named) {
DispatchEnt m;
//Kernel.LogNameLookup(name);
if (mo.mro_methods.TryGetValue(name, out m)) {
Frame nf = caller.MakeChild(m.outer, m.info);
nf.pos = pos;
nf.named = named;
nf.curDisp = m;
return nf;
}
return Fail(caller, "Unable to resolve method " + name);
}
public IP6 GetTypeObject() {
return mo.typeObject;
}
public string GetTypeName() {
return mo.name;
}
public bool Isa(DynMetaObject mo) {
return this.mo.HasMRO(mo);
}
public bool Does(DynMetaObject mo) {
return this.mo.HasMRO(mo);
}
public Frame Invoke(Frame c, Variable[] p,
Dictionary<string, Variable> n) {
DynMetaObject.InvokeHandler ih = mo.mro_OnInvoke;
if (ih != null) {
return ih(this, c, p, n);
} else {
Variable[] np = new Variable[p.Length + 1];
Array.Copy(p, 0, np, 1, p.Length);
np[0] = Kernel.NewROScalar(this);
return InvokeMethod(c, "INVOKE", np, n);
}
}
}
public sealed class DispatchEnt {
public DispatchEnt next;
public SubInfo info;
public Frame outer;
public IP6 ip6;
public DispatchEnt(DispatchEnt next, IP6 ip6) {
this.ip6 = ip6;
this.next = next;
DynObject d = (DynObject)ip6;
this.outer = (Frame) d.slots[0];
this.info = (SubInfo) d.slots[1];
}
}
// A Variable is the meaning of function arguments, of any subexpression
// except the targets of := and ::=.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public abstract class Variable {
public ViviHook whence;
// these should be treated as ro for the life of the variable
public DynMetaObject type;
public bool rw;
public bool islist;
public abstract IP6 Fetch();
public abstract void Store(IP6 v);
public abstract IP6 GetVar();
public static readonly Variable[] None = new Variable[0];
}
public abstract class ViviHook {
public abstract Frame Do(Frame th, Variable toviv);
}
public class SubViviHook : ViviHook {
IP6 sub;
public SubViviHook(IP6 sub) { this.sub = sub; }
public override Frame Do(Frame th, Variable toviv) {
return sub.Invoke(th, new Variable[] { toviv }, null);
}
}
public class HashViviHook : ViviHook {
IP6 hash;
string key;
public HashViviHook(IP6 hash, string key) { this.hash = hash; this.key = key; }
public override Frame Do(Frame th, Variable toviv) {
Dictionary<string,Variable> rh = (Dictionary<string,Variable>)
Kernel.UnboxAny(hash);
rh[key] = toviv;
return th;
}
}
public class ArrayViviHook : ViviHook {
IP6 ary;
int key;
public ArrayViviHook(IP6 ary, int key) { this.ary = ary; this.key = key; }
public override Frame Do(Frame th, Variable toviv) {
VarDeque vd = (VarDeque) ary.GetSlot("items");
while (vd.Count() <= key)
vd.Push(Kernel.NewRWScalar(Kernel.AnyMO, Kernel.AnyP));
vd[key] = toviv;
return th;
}
}
public sealed class SimpleVariable: Variable {
IP6 val;
public SimpleVariable(bool rw, bool islist, DynMetaObject type, ViviHook whence, IP6 val) {
this.val = val; this.whence = whence; this.rw = rw;
this.islist = islist; this.type = type;
}
public override IP6 Fetch() { return val; }
public override void Store(IP6 v) {
if (!rw) {
throw new NieczaException("Writing to readonly scalar");
}
if (!v.mo.HasMRO(type)) {
throw new NieczaException("Nominal type check failed for scalar store; got " + v.mo.name + ", needed " + type.name + " or subtype");
}
val = v;
}
public override IP6 GetVar() {
DynObject d = new DynObject(Kernel.ScalarMO);
d.slots[0] = this;
return d;
}
}
// Used to make Variable sharing explicit in some cases; will eventually be
// the only way to share a bvalue
public sealed class BValue {
public Variable v;
public BValue(Variable v) { this.v = v; }
}
// This stores all the invariant stuff about a Sub, i.e. everything
// except the outer pointer. Now distinct from protopads
public class SubInfo {
public int[] lines;
public DynBlockDelegate code;
public DynMetaObject mo;
// for inheriting hints
public SubInfo outer;
public string name;
public Dictionary<string, object> hints;
// maybe should be a hint
public LAD ltm;
public Dictionary<string, int> dylex;
// records: $start-ip, $end-ip, $type, $goto, $lid
public const int ON_NEXT = 1;
public const int ON_LAST = 2;
public const int ON_REDO = 3;
public const int ON_RETURN = 4;
public const int ON_DIE = 5;
public const int ON_SUCCEED = 6;
public const int ON_PROCEED = 7;
public const int ON_GOTO = 8;
public const int ON_NEXTDISPATCH = 9;
public int[] edata;
public string[] label_names;
private static string[] controls = new string[] { "unknown", "next",
"last", "redo", "return", "die", "succeed", "proceed", "goto",
"nextsame/nextwith" };
public static string DescribeControl(int type, Frame tgt, int lid,
string name) {
string ty = (type < controls.Length) ? controls[type] : "unknown";
if (lid >= 0) {
return ty + "(" + tgt.info.label_names[lid] + ", lexotic)";
} else if (name != null) {
return ty + "(" + name + ", dynamic)";
} else {
return ty;
}
}
public int FindControlEnt(int ip, int ty, string name, int lid) {
for (int i = 0; i < edata.Length; i+=5) {
if (ip < edata[i] || ip >= edata[i+1])
continue;
if (ty != edata[i+2])
continue;
if (lid >= 0 && lid != edata[i+4])
continue;
if (name != null && !name.Equals(label_names[edata[i+4]]))
continue;
return edata[i+3];
}
return -1;
}
public void PutHint(string name, object val) {
if (hints == null)
hints = new Dictionary<string,object>();
hints[name] = val;
}
public bool GetLocalHint<T>(string name, out T val) where T: class {
object o;
if (hints != null && hints.TryGetValue(name, out o)) {
val = o as T;
return true;
} else {
val = null;
return false;
}
}
public SubInfo(string name, int[] lines, DynBlockDelegate code,
SubInfo outer, LAD ltm, int[] edata, string[] label_names,
string[] dylexn, int[] dylexi) {
this.lines = lines;
this.code = code;
this.outer = outer;
this.ltm = ltm;
this.name = name;
this.edata = edata;
this.label_names = label_names;
if (dylexn != null) {
dylex = new Dictionary<string, int>();
for (int i = 0; i < dylexn.Length; i++)
dylex[dylexn[i]] = dylexi[i];
}
}
public SubInfo(string name, DynBlockDelegate code) :
this(name, null, code, null, null, new int[0], null, null, null) { }
}
// We need hashy frames available to properly handle BEGIN; for the time
// being, all frames will be hashy for simplicity
public class Frame: IP6 {
public Frame caller;
public Frame outer;
public SubInfo info;
// a doubly-linked list of frames being used by a given coroutine
public Frame reusable_child;
public Frame reuser;
public object resultSlot = null;
public int ip = 0;
public DynBlockDelegate code;
public Dictionary<string, object> lex;
// statistically, most subs have between 1 and 4 anonymous lexicals
public object lex0;
public object lex1;
public object lex2;
public object lex3;
public int lexi0;
public int lexi1;
public object[] lexn;
public DispatchEnt curDisp;
public RxFrame rx;
public Variable[] pos;
public Dictionary<string, Variable> named;
// after MakeSub, GatherHelper
public const int SHARED = 1;
// nextsame; on binder failure
public const int MULTIPHASE = 2;
public int flags;
public Frame(Frame caller_, Frame outer_,
SubInfo info_) {
caller = caller_;
outer = outer_;
code = info_.code;
info = info_;
mo = Kernel.CallFrameMO;
}
public Frame() { mo = Kernel.CallFrameMO; }
public Frame MakeChild(Frame outer, SubInfo info) {
if (reusable_child == null) {
reusable_child = new Frame();
reusable_child.reuser = this;
}
reusable_child.ip = 0;
reusable_child.resultSlot = null;
reusable_child.lexn = null;
reusable_child.lex = null;
reusable_child.lex0 = null;
reusable_child.lex1 = null;
reusable_child.lex2 = null;
reusable_child.lex3 = null;
reusable_child.curDisp = null;
reusable_child.caller = this;
reusable_child.outer = outer;
reusable_child.info = info;
reusable_child.code = info.code;
reusable_child.rx = null;
return reusable_child;
}
public Frame Continue() {
return code(this);
}
public Variable ExtractNamed(string n) {
Variable r;
if (named != null && named.TryGetValue(n, out r)) {
named.Remove(n);
return r;
} else {
return null;
}
}
public void MarkShared() {
if (0 == (flags & SHARED)) {
flags |= SHARED;
if (reuser != null) reuser.reusable_child = reusable_child;
if (reusable_child != null) reusable_child.reuser = reuser;
reuser = reusable_child = null;
}
}
// when control might re-enter a function
public void MarkSharedChain() {
for (Frame x = this; x != null; x = x.caller)
x.MarkShared();
}
public int ExecutingLine() {
if (info != null && info.lines != null) {
return ip >= info.lines.Length ? 0 : info.lines[ip];
} else {
return 0;
}
}
public string ExecutingFile() {
string l;
SubInfo i = info;
while (i != null) {
// possibly, using $?FILE and Fetch would be better
if (i.GetLocalHint("?file", out l))
return l;
i = i.outer;
}
return "";
}
public void SetDynamic(int ix, object v) {
switch(ix) {
case 0: lex0 = v; break;
case 1: lex1 = v; break;
case 2: lex2 = v; break;
case 3: lex3 = v; break;
default: lexn[ix-4] = v; break;
}
}
public bool TryGetDynamic(string name, out object v) {
v = null;
if (lex == null && info.dylex == null)
return false;
if (lex != null && lex.TryGetValue(name, out v))
return true;
int ix;
if (info.dylex == null || !info.dylex.TryGetValue(name, out ix))
return false;
switch(ix) {
case 0: v = lex0; break;
case 1: v = lex1; break;
case 2: v = lex2; break;
case 3: v = lex3; break;
default: v = lexn[ix-4]; break;
}
return true;
}
public Variable LexicalFind(string name) {
Frame csr = this;
while (csr != null) {
object o;
if (csr.TryGetDynamic(name, out o)) {
return (Variable)o;
}
csr = csr.outer;
}
return Kernel.NewROScalar(Kernel.AnyP);
}
private static List<string> spacey = new List<string>();
public string DepthMark() {
Frame f = this;
int ix = 0;
while (f != null) { ix++; f = f.caller; }
while (spacey.Count <= ix) { spacey.Add(new String(' ', spacey.Count * 2)); }
return spacey[ix];
}
}
public class NieczaException: Exception {
// hide clr stack trace for these
public override string ToString() { return Message; }
public NieczaException(string detail) : base(detail) {}
public NieczaException() : base() {}
}
public abstract class ContextHandler<T> {
public abstract T Get(Variable obj);
}
// TODO: find out if generic sharing is killing performance
class CtxCallMethodUnbox<T> : ContextHandler<T> {
string method;
public CtxCallMethodUnbox(string method) { this.method = method; }
public override T Get(Variable obj) {
Frame nr = new Frame(null, null, Kernel.ExitRunloopSI);
Kernel.RunCore(obj.Fetch().InvokeMethod(nr, method, new Variable[] { obj }, null));
Variable v = (Variable) nr.resultSlot;
return (T) Kernel.UnboxAny(v.Fetch());
}
}
class CtxCallMethod : ContextHandler<Variable> {
string method;
public CtxCallMethod(string method) { this.method = method; }
public override Variable Get(Variable obj) {
Frame nr = new Frame(null, null, Kernel.ExitRunloopSI);
Kernel.RunCore(obj.Fetch().InvokeMethod(nr, method, new Variable[] { obj }, null));
Variable v = (Variable) nr.resultSlot;
return v;
}
}
class CtxJustUnbox<T> : ContextHandler<T> {
public override T Get(Variable obj) {
return (T) Kernel.UnboxAny(obj.Fetch());
}
}
class CtxReturnSelf : ContextHandler<Variable> {
public override Variable Get(Variable obj) {
return Kernel.NewROScalar(obj.Fetch());
}
}
class CtxRawNativeDefined : ContextHandler<bool> {
public override bool Get(Variable obj) {
return obj.Fetch().IsDefined();
}
}
class CtxBoolNativeDefined : ContextHandler<Variable> {
public override Variable Get(Variable obj) {
return obj.Fetch().IsDefined() ? Kernel.TrueV : Kernel.FalseV;
}
}
class CtxRawNativeNum2Str : ContextHandler<string> {
public override string Get(Variable obj) {
return ((double) Kernel.UnboxAny(obj.Fetch())).ToString();
}
}
class CtxStrNativeNum2Str : ContextHandler<Variable> {
public override Variable Get(Variable obj) {
return Kernel.BoxAnyMO(((double) Kernel.UnboxAny(obj.Fetch())).ToString(), Kernel.StrMO);
}
}
// NOT IP6; these things should only be exposed through a ClassHOW-like
// façade
public class DynMetaObject {
public static readonly ContextHandler<Variable> CallStr
= new CtxCallMethod("Str");
public static readonly ContextHandler<Variable> CallBool
= new CtxCallMethod("Bool");
public static readonly ContextHandler<Variable> CallNumeric
= new CtxCallMethod("Numeric");
public static readonly ContextHandler<Variable> CallDefined
= new CtxCallMethod("defined");
public static readonly ContextHandler<string> RawCallStr
= new CtxCallMethodUnbox<string>("Str");
public static readonly ContextHandler<bool> RawCallBool
= new CtxCallMethodUnbox<bool>("Bool");
public static readonly ContextHandler<double> RawCallNumeric
= new CtxCallMethodUnbox<double>("Numeric");
public static readonly ContextHandler<bool> RawCallDefined
= new CtxCallMethodUnbox<bool>("defined");
public IP6 how;
public IP6 typeObject;
public string name;
public bool isRole;
public IP6 roleFactory;
public Dictionary<string, IP6> instCache;
// role type objects have an empty MRO cache so no methods can be
// called against them; the fallback (NYI) is to pun.
public LexerCache lexcache;
public LexerCache GetLexerCache() {
if (lexcache == null)
lexcache = new LexerCache(this);
return lexcache;
}
public delegate Frame InvokeHandler(IP6 th, Frame c,
Variable[] pos, Dictionary<string, Variable> named);
public ContextHandler<Variable> mro_Str, loc_Str, mro_Numeric,
loc_Numeric, mro_Bool, loc_Bool, mro_defined, loc_defined;
public ContextHandler<bool> mro_raw_Bool, loc_raw_Bool, mro_raw_defined,
loc_raw_defined;
public ContextHandler<string> mro_raw_Str, loc_raw_Str;
public ContextHandler<double> mro_raw_Numeric, loc_raw_Numeric;
public InvokeHandler OnInvoke;
public InvokeHandler mro_OnInvoke;
public Dictionary<string, DispatchEnt> mro_methods;
public DynMetaObject[] local_does;
public List<DynMetaObject> superclasses
= new List<DynMetaObject>();
public Dictionary<string, IP6> local
= new Dictionary<string, IP6>();
public List<KeyValuePair<string, IP6>> ord_methods
= new List<KeyValuePair<string, IP6>>();
public Dictionary<string, IP6> priv
= new Dictionary<string, IP6>();
public List<string> local_attr = new List<string>();
public Dictionary<string, int> slotMap = new Dictionary<string, int>();
public int nslots = 0;
public string[] all_attr;
private WeakReference wr_this;
// protected by static lock
private HashSet<WeakReference> subclasses = new HashSet<WeakReference>();
private static object mro_cache_lock = new object();
public int FindSlot(string name) {
//Kernel.LogNameLookup(name);
return slotMap[name];
}
public DynMetaObject[] mro;
public HashSet<DynMetaObject> isa;
public Dictionary<DynMetaObject, DynMetaObject> butCache;
public DynMetaObject(string name) {
this.name = name;
this.wr_this = new WeakReference(this);
isa = new HashSet<DynMetaObject>();
}
private void Revalidate() {
mro_OnInvoke = null;
mro_methods = new Dictionary<string,DispatchEnt>();
if (mro == null)
return;
if (isRole)
return;
for (int kx = mro.Length - 1; kx >= 0; kx--) {
DynMetaObject k = mro[kx];
foreach (KeyValuePair<string,IP6> m in k.ord_methods) {
DispatchEnt de;
mro_methods.TryGetValue(m.Key, out de);
mro_methods[m.Key] = new DispatchEnt(de, m.Value);
if (m.Key == "Numeric") {
mro_Numeric = CallNumeric;
mro_raw_Numeric = RawCallNumeric;
}
if (m.Key == "Bool") {
mro_Bool = CallBool;
mro_raw_Bool = RawCallBool;
}
if (m.Key == "Str") {
mro_Str = CallStr;
mro_raw_Str = RawCallStr;
}
if (m.Key == "defined") {
mro_defined = CallDefined;
mro_raw_defined = RawCallDefined;
}
}
if (k.OnInvoke != null)
mro_OnInvoke = k.OnInvoke;
if (k.loc_Numeric != null) mro_Numeric = k.loc_Numeric;
if (k.loc_defined != null) mro_defined = k.loc_defined;
if (k.loc_Bool != null) mro_Bool = k.loc_Bool;
if (k.loc_Str != null) mro_Str = k.loc_Str;
if (k.loc_raw_Numeric != null) mro_raw_Numeric = k.loc_raw_Numeric;
if (k.loc_raw_defined != null) mro_raw_defined = k.loc_raw_defined;
if (k.loc_raw_Bool != null) mro_raw_Bool = k.loc_raw_Bool;
if (k.loc_raw_Str != null) mro_raw_Str = k.loc_raw_Str;
}
}
private void SetMRO(DynMetaObject[] arr) {
lock(mro_cache_lock) {
if (mro != null)
foreach (DynMetaObject k in mro)
k.subclasses.Remove(wr_this);
foreach (DynMetaObject k in arr)
k.subclasses.Add(wr_this);
}
mro = arr;
isa.Clear();
foreach (DynMetaObject k in arr)
isa.Add(k);
}
~DynMetaObject() {
lock(mro_cache_lock)
if (mro != null)
foreach (DynMetaObject k in mro)
k.subclasses.Remove(wr_this);
}
public void Invalidate() {
if (mro == null)
return;
List<DynMetaObject> notify = new List<DynMetaObject>();
lock(mro_cache_lock)
foreach (WeakReference k in subclasses)
notify.Add(k.Target as DynMetaObject);
foreach (DynMetaObject k in notify)
if (k != null)
k.Revalidate();
}
public IP6 Can(string name) {
DispatchEnt m;
if (mro_methods.TryGetValue(name, out m))
return m.ip6; // TODO return an iterator
return null;
}
public Dictionary<string,DispatchEnt> AllMethods() {
return mro_methods;
}
public HashSet<IP6> AllMethodsSet() {
HashSet<IP6> r = new HashSet<IP6>();
foreach (KeyValuePair<string,DispatchEnt> kv in mro_methods)
r.Add(kv.Value.ip6);
return r;
}
public bool HasMRO(DynMetaObject m) {
int k = mro.Length;
if (k >= 20) {
return isa.Contains(m);
} else {
while (k != 0) {
if (mro[--k] == m) return true;
}
return false;
}
}
public void AddMethod(string name, IP6 code) {
local[name] = code;
ord_methods.Add(new KeyValuePair<string,IP6>(name, code));
}
public void AddPrivateMethod(string name, IP6 code) {
priv[name] = code;
}
public IP6 GetPrivateMethod(string name) {
IP6 code = priv[name];
if (code == null) { throw new NieczaException("private method lookup failed for " + name + " in class " + this.name); }
return code;
}
public void FillProtoClass(string[] attr) {
FillClass(attr, attr, new DynMetaObject[] {},
new DynMetaObject[] { this });
}
public void FillClass(string[] local_attr, string[] all_attr,
DynMetaObject[] superclasses, DynMetaObject[] mro) {
this.superclasses = new List<DynMetaObject>(superclasses);
SetMRO(mro);
this.local_attr = new List<string>(local_attr);
this.butCache = new Dictionary<DynMetaObject, DynMetaObject>();
this.all_attr = all_attr;
this.local_does = new DynMetaObject[0];
nslots = 0;
foreach (string an in all_attr) {
slotMap[an] = nslots++;
}
Invalidate();
}
public void FillRole(string[] attr, DynMetaObject[] superclasses,
DynMetaObject[] cronies) {
this.superclasses = new List<DynMetaObject>(superclasses);
this.local_attr = new List<string>(attr);
this.local_does = cronies;
this.isRole = true;
Revalidate(); // need to call directly as we aren't in any mro list
SetMRO(Kernel.AnyMO.mro);
}
public void FillParametricRole(IP6 factory) {
this.isRole = true;
this.roleFactory = factory;
this.instCache = new Dictionary<string, IP6>();
Revalidate();
SetMRO(Kernel.AnyMO.mro);
}
}
// This is quite similar to DynFrame and I wonder if I can unify them.
// These are always hashy for the same reason as Frame above
public class DynObject: IP6 {
// the slots have to support non-containerized values, because
// containers are objects now
public object[] slots;
public DynObject(DynMetaObject klass) {
this.mo = klass;
this.slots = new object[klass.nslots];
}
public override void SetSlot(string name, object obj) {
slots[mo.FindSlot(name)] = obj;
}
public override object GetSlot(string name) {
return slots[mo.FindSlot(name)];
}
public override bool IsDefined() {
return this != mo.typeObject;
}
}
// A bunch of stuff which raises big circularity issues if done in the
// setting itself.
public class Kernel {
public static DynBlockDelegate MainlineContinuation;
// Note: for classes without public .new, there's no way to get
// "interesting" user subclasses, so direct indexing is safe
public static object UnboxDO(DynObject o) {
return o.slots[0];
}
public static object UnboxAny(IP6 o) {
// TODO: Check for compatibility?
return UnboxDO((DynObject)o);
}
public static Stack<Frame> TakeReturnStack = new Stack<Frame>();
public static Frame Take(Frame th, Variable payload) {
Frame r = TakeReturnStack.Pop();
r.SetDynamic(r.info.dylex["$*nextframe"], NewROScalar(th));
r.resultSlot = payload;
th.resultSlot = payload;
return r;
}
public static Frame CoTake(Frame th, Frame from) {
TakeReturnStack.Push(th);
return from;
}
public static Frame GatherHelper(Frame th, IP6 sub) {
DynObject dyo = (DynObject) sub;
Frame n = th.MakeChild((Frame) dyo.slots[0],
(SubInfo) dyo.slots[1]);
n.MarkSharedChain();
th.resultSlot = n;
return th;
}
private static Frame SubInvoke(IP6 th, Frame caller,
Variable[] pos, Dictionary<string,Variable> named) {
DynObject dyo = ((DynObject) th);
Frame outer = (Frame) dyo.slots[0];
SubInfo info = (SubInfo) dyo.slots[1];
Frame n = caller.MakeChild(outer, info);
n.pos = pos;
n.named = named;
return n;
}
private static SubInfo SubInvokeSubSI = new SubInfo("Sub.INVOKE", SubInvokeSubC);
private static Frame SubInvokeSubC(Frame th) {
Variable[] post;
post = new Variable[th.pos.Length - 1];
Array.Copy(th.pos, 1, post, 0, th.pos.Length - 1);
return SubInvoke((DynObject)th.pos[0].Fetch(), th.caller,
post, th.named);
}
public static Frame Die(Frame caller, string msg) {
return SearchForHandler(caller, SubInfo.ON_DIE, null, -1, null,
BoxAnyMO(msg, StrMO));
}
public static Frame BindFail(Frame caller, string msg) {
// TODO: Junctional failover goes here
if ((caller.flags & Frame.MULTIPHASE) != 0) {
// TODO: Figure out how .*foo fits in here.
Variable[] p = caller.pos;
Dictionary<string,Variable> n = caller.named;
DispatchEnt de = caller.curDisp.next;
if (de == null) {
return Die(caller.caller, "Multiple dispatch failed to find a candidate");
}
caller = caller.caller.MakeChild(de.outer, de.info);
caller.pos = p;
caller.named = n;
caller.curDisp = de;
caller.flags |= Frame.MULTIPHASE;
return caller;
}
return Die(caller, msg);
}
public static Frame CheckArgEnd(Frame caller, int i, string m) {
// TODO: checking for SigCheckOnly goes here
if (i == caller.pos.Length &&
(caller.named == null || caller.named.Count == 0)) {
caller.flags &= ~Frame.MULTIPHASE;
return caller;
} else {
if (i != caller.pos.Length)
m += string.Format(", used {0} of {1} positionals",
i, caller.pos.Length);
if (caller.named != null && caller.named.Count != 0)
m += ", unused named " + JoinS(", ", caller.named.Keys);
return BindFail(caller, m);
}
}
public static IP6 SigSlurpCapture(Frame caller) {
IP6 nw = new DynObject(CaptureMO);
nw.SetSlot("positionals", caller.pos);
nw.SetSlot("named", caller.named);
caller.named = null;
return nw;
}
public static DynMetaObject AnyMO;
public static DynMetaObject CallFrameMO;
public static DynMetaObject CaptureMO;
public static DynMetaObject GatherIteratorMO;
public static DynMetaObject HashMO;
public static DynMetaObject IterCursorMO;
public static DynMetaObject ListMO;
public static DynMetaObject ArrayMO;
public static DynMetaObject MatchMO;
public static IP6 AnyP;
public static IP6 ArrayP;
public static IP6 EMPTYP;
public static IP6 HashP;
public static IP6 IteratorP;
public static readonly DynMetaObject ScalarMO;
public static readonly DynMetaObject StashMO;
public static readonly DynMetaObject SubMO;
public static readonly DynMetaObject StrMO;
public static readonly DynMetaObject NumMO;
public static readonly DynMetaObject BoolMO;
public static readonly DynMetaObject MuMO;
public static readonly IP6 StashP;
public static readonly Variable TrueV;
public static readonly Variable FalseV;
public static IP6 MakeSub(SubInfo info, Frame outer) {
DynObject n = new DynObject(info.mo ?? SubMO);
n.slots[0] = outer;
if (outer != null) outer.MarkShared();
n.slots[1] = info;
return n;
}
public static DynObject MockBox(object v) {
DynObject n = new DynObject(StrMO);
n.slots[0] = v;
return n;
}
public static Variable BoxAny(object v, IP6 proto) {
if (v == null)
return NewROScalar(proto);
if (proto == BoolMO.typeObject)
return ((bool) v) ? TrueV : FalseV;
DynObject n = new DynObject(((DynObject)proto).mo);
n.slots[0] = v;
return NewROScalar(n);
}
public static Variable BoxAnyMO(object v, DynMetaObject proto) {
if (v == null)
return NewROScalar(proto.typeObject);
if (proto == BoolMO)
return ((bool) v) ? TrueV : FalseV;
DynObject n = new DynObject(proto);
n.slots[0] = v;
return NewROScalar(n);
}
public static IP6 BoxRaw(object v, DynMetaObject proto) {
DynObject n = new DynObject(proto);
n.slots[0] = v;
return n;
}
// check whence before calling
public static Frame Vivify(Frame th, Variable v) {
ViviHook w = v.whence;
v.whence = null;
return w.Do(th, v);
}
// this exists purely to hide the return value
private static SubInfo BindSI = new SubInfo("Bind/rw-viv", BindC);
private static Frame BindC(Frame th) {
switch (th.ip) {
case 0:
return th.caller;