/
Kernel.cs
890 lines (779 loc) · 31.1 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
using System;
using System.Collections.Generic;
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 interface IP6 {
Frame Invoke(Frame caller, Variable[] pos,
Dictionary<string, Variable> named);
// include the invocant in the positionals! it will not usually be
// this, rather a container of this
Frame InvokeMethod(Frame caller, string name,
Variable[] pos, Dictionary<string, Variable> named);
Frame GetAttribute(Frame caller, string name);
//public Frame WHERE(Frame caller);
Frame HOW(Frame caller);
// These exist as a concession to circularity - FETCH as a completely
// ordinary method could not work under the current calling convention.
Frame Fetch(Frame caller);
Frame Store(Frame caller, IP6 thing);
}
// TODO: update this comment
// Variables are things which can produce LValues, and can also bind
// LValues. They hold LValues and may or may not be bindable. Variables
// also tend to contextualize stuff put into them.
//
// Coercions are not used on binding unless necessary.
//
// Variables also have type constraints, that's how %foo and @foo differ...
// A LValue is the meaning of function arguments, of any subexpression
// except the targets of := and .VAR.
//
// They come in two flavors. Scalary lvalues hold a container, which
// can do FETCH and STORE. Listy lvalues FETCH as the container itself,
// and STORE as a method to the container.
//
// List->scalar context: create a simple container holding the list's
// object, but !islist. Read only.
//
// Scalar->list: bind islist, must be Iterable. Bind it same rwness.
public class Variable {
public bool bvalue;
public bool rw;
public bool islist;
// If non-null, then this lv is, or at one time was, the result of
// an autovivifying access, but has not yet committed to becoming
// real or becoming undef. We call these virtual containers; they
// exist only in flight (resultSlots) and in parcel contexts.
public IP6 whence;
public IP6 container;
public Variable(bool bvalue, bool rw, bool islist, IP6 whence,
IP6 container) {
this.bvalue = bvalue;
this.whence = whence;
this.container = container;
this.rw = rw;
this.islist = islist;
}
}
// 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 readonly Frame caller;
public readonly Frame outer;
public Frame proto;
public object resultSlot = null;
public int ip = 0;
public readonly DynBlockDelegate code;
public readonly Dictionary<string, object> lex
= new Dictionary<string, object>();
public Variable[] pos;
public Dictionary<string, Variable> named;
public Frame(Frame outer_) : this(null, outer_, null) {}
public Frame(Frame caller_, Frame outer_,
DynBlockDelegate code_) {
caller = caller_;
outer = outer_;
code = code_;
}
public Frame Continue() {
return code(this);
}
public Frame GetAttribute(Frame c, string name) {
c.resultSlot = lex[name];
return c;
}
public Frame Invoke(Frame c, Variable[] p,
Dictionary<string, Variable> n) {
return Kernel.Die(c, "Tried to invoke a Frame");
}
// FIXME A horrible hack, code duplication and doesn't support FETCH etc
public Frame InvokeMethod(Frame caller, string name,
Variable[] pos, Dictionary<string, Variable> named) {
IP6 m;
foreach (DynMetaObject k in Kernel.CallFrameMO.mro) {
if (k.local.TryGetValue(name, out m)) {
return m.Invoke(caller, pos, named);
}
}
return Kernel.Die(caller, "Unable to resolve method " + name);
}
public Frame Fetch(Frame c) {
return Kernel.Die(c, "Method FETCH not defined on Frame");
}
public Frame Store(Frame c, IP6 o) {
return Kernel.Die(c, "Method STORE not defined on Frame");
}
public Frame HOW(Frame c) {
c.resultSlot = Kernel.CallFrameMO.how;
return c;
}
public int ExecutingLine() {
object l;
if (((proto != null) ? proto.lex : lex).
TryGetValue("?lines", out l)) {
int[] rl = (int[])l;
return ip >= rl.Length ? 0 : rl[ip];
} else {
return 0;
}
}
public string ExecutingFile() {
object l;
if (((proto != null) ? proto.lex : lex).
TryGetValue("?files", out l)) {
string[] rl = (string[])l;
return ip >= rl.Length ? "" : rl[ip];
} else {
return "";
}
}
public Variable LexicalFind(string name) {
Frame csr = this;
while (csr != null) {
object o;
if (csr.lex.TryGetValue(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];
}
}
// NOT IP6; these things should only be exposed through a ClassHOW-like
// façade
public class DynMetaObject {
public IP6 how;
public IP6 typeObject;
public string name;
public delegate Frame InvokeHandler(DynObject th, Frame c,
Variable[] pos, Dictionary<string, Variable> named);
public delegate Frame FetchHandler(DynObject th, Frame c);
public delegate Frame StoreHandler(DynObject th, Frame c, IP6 n);
public InvokeHandler OnInvoke;
public FetchHandler OnFetch;
public StoreHandler OnStore;
public List<DynMetaObject> superclasses
= new List<DynMetaObject>();
public Dictionary<string, IP6> local
= new Dictionary<string, IP6>();
public Dictionary<string, IP6> local_attr
= new Dictionary<string, IP6>();
public List<DynMetaObject> mro;
public HashSet<DynMetaObject> isa;
public DynMetaObject(string name) {
this.name = name;
this.mro = new List<DynMetaObject>();
mro.Add(this);
isa = new HashSet<DynMetaObject>();
isa.Add(this);
}
public bool HasMRO(DynMetaObject m) {
return isa.Contains(m);
}
public void BuildC3MRO() {
List<List<DynMetaObject>> toMerge = new List<List<DynMetaObject>>();
mro = new List<DynMetaObject>();
isa = new HashSet<DynMetaObject>();
toMerge.Add(new List<DynMetaObject>());
toMerge[0].Add(this);
foreach (DynMetaObject dmo in superclasses) {
toMerge[0].Add(dmo);
toMerge.Add(new List<DynMetaObject>(dmo.mro));
}
while (true) {
top:
foreach (List<DynMetaObject> h in toMerge) {
if (h.Count == 0) {
continue; // next CANDIDATE
}
DynMetaObject cand = h[0];
foreach (List<DynMetaObject> bs in toMerge) {
if (bs.Count == 0) {
continue; // next BLOCKER
}
if (bs[0] == cand) {
continue;
}
if (bs.Contains(cand)) {
goto blocked;
}
}
// no reason not to immediately put this, and by loop
// order the C3 condition is kept
mro.Add(cand);
isa.Add(cand);
foreach (List<DynMetaObject> l in toMerge) {
l.Remove(cand);
}
goto top;
blocked:
;
}
foreach (List<DynMetaObject> l in toMerge) {
if (l.Count != 0) {
// should refactor this to use a real p6exception
throw new Exception("C3 MRO inconsistency detected");
}
}
return;
}
}
}
// 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 Dictionary<string, object> slots
= new Dictionary<string, object>();
public DynMetaObject klass;
public DynObject(DynMetaObject klass) {
this.klass = klass;
}
private Frame Fail(Frame caller, string msg) {
return Kernel.Die(caller, msg + " in class " + klass.name);
}
public Frame InvokeMethod(Frame caller, string name,
Variable[] pos, Dictionary<string, Variable> named) {
IP6 m;
foreach (DynMetaObject k in klass.mro) {
if (k.local.TryGetValue(name, out m)) {
return m.Invoke(caller, pos, named);
}
}
return Fail(caller, "Unable to resolve method " + name);
}
public Frame GetAttribute(Frame caller, string name) {
if (slots == null) {
return Fail(caller, "Attempted to access slot " + name +
" via a protoobject");
}
caller.resultSlot = slots[name];
return caller;
}
public Frame HOW(Frame caller) {
caller.resultSlot = klass.how;
return caller;
}
public Frame Invoke(Frame c, Variable[] p,
Dictionary<string, Variable> n) {
if (klass.OnInvoke != null) {
return klass.OnInvoke(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 Frame Fetch(Frame c) {
if (klass.OnFetch != null) {
return klass.OnFetch(this, c);
} else {
return InvokeMethod(c, "FETCH", new Variable[1] {
Kernel.NewROScalar(this) }, null);
}
}
public Frame Store(Frame c, IP6 o) {
if (klass.OnStore != null) {
return klass.OnStore(this, c, o);
} else {
return InvokeMethod(c, "STORE", new Variable[2] {
Kernel.NewROScalar(this), Kernel.NewROScalar(o) },
null);
}
}
}
// Allows native CLR objects to be treated as Perl 6 data. They don't
// currently support any operations; you'll need to use CLR code to work
// with them.
public class CLRImportObject : IP6 {
public readonly object val;
public CLRImportObject(object val_) { val = val_; }
public Frame GetAttribute(Frame c, string nm) {
return Kernel.Die(c, "Attribute " + nm +
" not available on CLRImportObject");
}
public Frame Invoke(Frame c, Variable[] p,
Dictionary<string, Variable> n) {
return Kernel.Die(c, "Tried to invoke a CLRImportObject");
}
public Frame InvokeMethod(Frame c, string nm, Variable[] p,
Dictionary<string, Variable> n) {
return Kernel.Die(c, "Method " + nm +
" not defined on CLRImportObject");
}
public Frame Fetch(Frame c) {
return Kernel.Die(c, "Method FETCH not defined on CLRImportObject");
}
public Frame Store(Frame c, IP6 o) {
return Kernel.Die(c, "Method STORE not defined on CLRImportObject");
}
public Frame HOW(Frame c) {
//TODO
return Kernel.Die(c, "No metaobject available for CLRImportObject");
}
}
// A bunch of stuff which raises big circularity issues if done in the
// setting itself.
public class Kernel {
public static DynBlockDelegate MainlineContinuation;
private static object UnboxDO(DynObject o) {
return o.slots["value"];
}
private static Frame SCFetch(DynObject th, Frame caller) {
caller.resultSlot = UnboxDO(th);
return caller;
}
private static Frame SCStore(DynObject th, Frame caller, IP6 nv) {
th.slots["value"] = nv;
return caller;
}
private static Frame SubCloneC(Frame th) {
DynObject a, b;
Frame c;
switch (th.ip) {
case 0:
th.ip = 1;
return th.pos[0].container.Fetch(th);
case 1:
th.lex["s0"] = th.resultSlot;
th.ip = 2;
return th.pos[1].container.Fetch(th);
case 2:
a = (DynObject) th.lex["s0"];
c = (Frame) th.resultSlot;
b = new DynObject(a.klass);
b.slots = new Dictionary<string,object>(a.slots);
b.slots["outer"] = c;
th.caller.resultSlot = NewROScalar(b);
return th.caller;
default:
return Kernel.Die(th, "invalid IP");
}
}
public static Frame TakeReturnFrame;
public static Frame Take(Frame th, Variable payload) {
Frame r = TakeReturnFrame;
TakeReturnFrame = null;
r.lex["$nextframe"] = NewROScalar(th);
r.resultSlot = payload;
th.resultSlot = payload;
return r;
}
public static Frame CoTake(Frame th, Frame from) {
TakeReturnFrame = th;
return from;
}
public static Frame GatherHelper(Frame th, IP6 sub) {
DynObject dyo = (DynObject) sub;
Frame n = new Frame(th,
(Frame) dyo.slots["outer"],
(DynBlockDelegate) dyo.slots["code"]);
n.proto = (Frame) dyo.slots["proto"];
th.resultSlot = n;
return th;
}
private static Frame SubInvoke(DynObject th, Frame caller,
Variable[] pos, Dictionary<string,Variable> named) {
Frame proto = (Frame) th.slots["proto"];
Frame outer = (Frame) th.slots["outer"];
DynBlockDelegate code = (DynBlockDelegate) th.slots["code"];
Frame n = new Frame(caller, outer, code);
n.proto = proto;
n.pos = pos;
n.named = named;
return n;
}
private static Frame SubInvokeSubC(Frame th) {
Variable[] post;
switch (th.ip) {
case 0:
th.ip = 1;
return th.pos[0].container.Fetch(th);
default:
post = new Variable[th.pos.Length - 1];
Array.Copy(th.pos, 1, post, 0, th.pos.Length - 1);
return SubInvoke((DynObject)th.resultSlot, th.caller,
post, th.named);
}
}
public static Frame Die(Frame caller, string msg) {
// TODO: Unbreak p6exceptions
throw new Exception(msg);
//Frame f = new Frame(caller, null, new DynBlockDelegate(ThrowC));
//f.pos = new LValue[1] { new LValue(true, false, new CLRImportObject(msg)) };
//f.named = null;
//return f;
}
public static readonly DynMetaObject SubMO;
public static readonly DynMetaObject ScalarMO;
public static bool TraceCont;
public static IP6 MakeSub(DynBlockDelegate code, Frame proto,
Frame outer) {
DynObject n = new DynObject(SubMO);
n.slots["outer"] = outer;
n.slots["code"] = code;
n.slots["proto"] = proto;
return n;
}
public static Variable BoxAny(object v, IP6 proto) {
DynObject n = new DynObject(((DynObject)proto).klass);
n.slots["value"] = v;
return NewROScalar(n);
}
public static object UnboxAny(IP6 o) {
// TODO: Check for compatibility?
return UnboxDO((DynObject)o);
}
public static IP6 MakeSC(IP6 inside) {
DynObject n = new DynObject(ScalarMO);
n.slots["value"] = inside;
return n;
}
// check whence before calling
public static Frame Vivify(Frame th, Variable v) {
IP6 w = v.whence;
v.whence = null;
return w.Invoke(th, new Variable[1] { v }, null);
}
private static Frame BindC(Frame th) {
switch (th.ip) {
case 0:
// autovivify rhs if needed
if (th.pos[1].whence == null || ((bool)th.lex["ro"]))
goto case 1;
th.ip = 1;
return Vivify(th, th.pos[1]);
case 1:
if (th.pos[0].whence == null)
goto case 2;
th.ip = 2;
return Vivify(th, th.pos[0]);
case 2:
if (!th.pos[0].islist || th.pos[1].islist)
goto case 4;
th.ip = 3;
return th.pos[1].container.Fetch(th);
case 3:
// having to fetch because of a $ -> @ conversion
th.pos[0].container = (IP6) th.resultSlot;
th.pos[0].rw = true;
return th.caller;
case 4:
th.pos[0].container = th.pos[1].container;
th.pos[0].rw = th.pos[1].rw && !((bool)th.lex["ro"]);
if (th.pos[1].islist && !th.pos[0].islist) {
th.pos[0].rw = false;
th.pos[0].container = MakeSC(th.pos[0].container);
}
return th.caller;
default:
throw new Exception("IP invalid");
}
}
public static Frame Bind(Frame th, Variable lhs, Variable rhs,
bool ro, bool forcerw) {
// TODO: need exceptions for forcerw to be used
Frame n;
// fast path
if (lhs.islist == rhs.islist &&
(ro || rhs.whence == null) &&
(lhs.whence == null)) {
lhs.container = rhs.container;
lhs.rw = !ro && rhs.rw;
return th;
}
n = new Frame(th, null, new DynBlockDelegate(BindC));
n.pos = new Variable[2] { lhs, rhs };
n.lex["ro"] = ro;
return n;
}
// This isn't just a fetch and a store...
private static Frame AssignC(Frame th) {
switch (th.ip) {
case 0:
if (th.pos[0].whence == null)
goto case 1;
th.ip = 1;
return Vivify(th, th.pos[0]);
case 1:
if (!th.pos[0].rw) {
throw new Exception("assigning to readonly value");
}
if (th.pos[0].islist) {
return th.pos[0].container.InvokeMethod(th.caller,
"LISTSTORE", th.pos, null);
} else {
if (th.pos[1].islist) {
return th.pos[0].container.Store(th.caller,
th.pos[1].container);
} else {
th.ip = 2;
return th.pos[1].container.Fetch(th);
}
}
case 2:
return th.pos[0].container.Store(th.caller,
(IP6)th.resultSlot);
default:
throw new Exception("invalid IP");
}
}
public static Frame Assign(Frame th, Variable lhs, Variable rhs) {
Frame n = new Frame(th, null,
new DynBlockDelegate(AssignC));
n.pos = new Variable[2] { lhs, rhs };
return n;
}
public static Frame Fetch(Frame th, Variable vr) {
if (vr.islist) {
th.resultSlot = vr.container;
return th;
} else {
return vr.container.Fetch(th);
}
}
// ro, not rebindable
public static Variable NewROScalar(IP6 obj) {
return new Variable(false, false, false, null, MakeSC(obj));
}
public static Variable NewRWScalar(IP6 obj) {
return new Variable(true, true, false, null, MakeSC(obj));
}
public static Variable NewRWListVar(IP6 container) {
return new Variable(true, true, true, null, container);
}
public static List<Variable> SlurpyHelper(Frame th, int from) {
List<Variable> lv = new List<Variable>();
for (int i = from; i < th.pos.Length; i++) {
lv.Add(th.pos[i]);
}
return lv;
}
public static Variable ContextHelper(Frame th, string name) {
object rt;
while (th != null) {
if (th.lex.TryGetValue(name, out rt)) {
return (Variable)rt;
}
th = th.caller;
}
name = name.Remove(1,1);
Dictionary<string,Variable> gstash = (Dictionary<string,Variable>)
(((CLRImportObject)GlobalO).val);
Variable v;
if (gstash.TryGetValue(name, out v)) {
return v;
} else {
return PackageLookup(ProcessO, name);
}
}
public static Variable DefaultNew(IP6 proto) {
DynObject n = new DynObject(((DynObject)proto).klass);
List<DynMetaObject> mro = n.klass.mro;
for (int i = mro.Count - 1; i >= 0; i--) {
foreach (string s in mro[i].local_attr.Keys) {
n.slots[s] = NewRWScalar(AnyP);
}
}
return NewROScalar(n);
}
public static IP6 AnyP;
public static IP6 ArrayP;
public static IP6 StrP = new DynObject(null);
public static DynMetaObject CallFrameMO;
public static Variable PackageLookup(IP6 parent, string name) {
Dictionary<string,Variable> stash = (Dictionary<string,Variable>)
(((CLRImportObject)parent).val);
Variable v;
if (stash.TryGetValue(name, out v)) {
return v;
} else if (name.EndsWith("::")) {
Dictionary<string,Variable> newstash =
new Dictionary<string,Variable>();
newstash["PARENT::"] = NewROScalar(parent);
return (stash[name] = NewROScalar(
new CLRImportObject(newstash)));
} else {
// TODO: @foo, %foo
return (stash[name] = NewRWScalar(AnyP));
}
}
public static void RunLoop(DynBlockDelegate boot) {
Kernel.TraceCont = (Environment.GetEnvironmentVariable("NIECZA_TRACE") != null);
Frame root_f = new Frame(null, null, boot);
Frame current = root_f;
while (current != null) {
try {
current = current.Continue();
} catch (Exception ex) {
ExceptionPacket ep = new FatalException(
new CLRImportObject(ex));
current = ep.SearchForHandler(current);
}
}
}
// XXX should be per-unit
public static Variable Global;
public static IP6 GlobalO;
public static Variable Process;
public static IP6 ProcessO;
static Kernel() {
SubMO = new DynMetaObject("Sub");
SubMO.OnInvoke = new DynMetaObject.InvokeHandler(SubInvoke);
SubMO.local["clone"] = MakeSub(new DynBlockDelegate(SubCloneC),
null, null);
SubMO.local["INVOKE"] = MakeSub(new DynBlockDelegate(SubInvokeSubC),
null, null);
ScalarMO = new DynMetaObject("Scalar");
ScalarMO.OnFetch = new DynMetaObject.FetchHandler(SCFetch);
ScalarMO.OnStore = new DynMetaObject.StoreHandler(SCStore);
GlobalO = new CLRImportObject(new Dictionary<string,Variable>());
Global = NewROScalar(GlobalO);
ProcessO = new CLRImportObject(new Dictionary<string,Variable>());
Process = NewROScalar(ProcessO);
}
}
public abstract class ExceptionPacket {
public Frame bot;
public Frame top;
public abstract bool Filter(Frame cand);
// for setting $!
public abstract IP6 Payload();
// CATCH vs CONTROL
public abstract bool IsFatal();
public abstract Frame Process(Frame target);
// stage 2!
public Frame Unwind(Frame caller) {
while (top != bot) {
Frame pop = bot;
bot = bot.caller;
object o;
if (pop.proto.lex.TryGetValue("!unwind", out o)) {
Frame n = new Frame(bot, bot, (DynBlockDelegate) o);
n.proto = (Frame) pop.proto.lex["!unwindp"];
n.lex["!reunwind"] = this;
return n;
}
}
return bot;
}
public Frame SearchForHandler(Frame caller) {
if (bot == null) { // first call
bot = top = caller;
}
string key = IsFatal() ? "!ehcatch" : "!ehcontrol";
while (top != null) {
Frame test = top;
if (test.proto != null) { test = test.proto; }
object o;
if (test.lex.TryGetValue(key, out o)) {
Frame fn = new Frame(bot, top, (DynBlockDelegate) o);
fn.proto = (Frame) test.lex[key + "p"];
fn.lex["!rethrow"] = this;
return fn;
}
if (top.lex.ContainsKey("!rethrow")) {
// this is an active exception handling frame! skip
// the corresponding handler
top = top.outer.caller;
} else {
if (Filter(top)) {
return Process(top);
}
top = top.caller;
}
}
Unhandled();
return null;
}
// This *probably* ought to be handled in Perl 6 code, using .Str,
// but we're now at a very low bootstrap level;
private void Unhandled() {
IP6 p = Payload();
CLRImportObject cp = p as CLRImportObject;
DynObject dp = p as DynObject;
Exception e = (cp != null) ? (cp.val as Exception) : null;
string s = (dp != null && dp.slots.ContainsKey("value")) ?
(dp.slots["value"] as string) : null;
if (e != null) {
// Wrapped CLR exception; has a message, and inner frames
s = e.ToString();
} else if (s == null) {
s = "(no message available)";
}
Console.Error.WriteLine("Unhandled exception: " + s);
Frame c;
for (c = bot; c != null; c = c.caller) {
Console.Error.WriteLine(" at {0} line {1}",
c.ExecutingFile(), c.ExecutingLine());
}
Environment.Exit(1);
}
}
// no payload; you should have already poked the right value into a
// result slot somewhere. ip = 0 means immediate return (leave)
public class LexoticControlException : ExceptionPacket {
public Frame target;
public int ip;
public LexoticControlException(Frame target, int ip) {
this.target = target;
this.ip = ip;
}
public override bool Filter(Frame cand) { return cand == target; }
public override IP6 Payload() { return Kernel.AnyP; } // XXX
public override bool IsFatal() { return false; }
public override Frame Process(Frame t) {
if (ip != 0) {
t.ip = ip;
}
return t;
}
}
public class FatalException : ExceptionPacket {
public IP6 payload;
public FatalException(IP6 payload) {
this.payload = payload;
}
// can only be explicitly caught
public override bool Filter(Frame cand) { return false; }
public override bool IsFatal() { return true; }
public override IP6 Payload() { return payload; }
public override Frame Process(Frame t) { return t; }
}
}
// The root setting
public class NULL {
public static Niecza.Frame Environment = null;
public static Niecza.IP6 Installer = Niecza.Kernel.MakeSub(
new Niecza.DynBlockDelegate(MAIN), null, null);
private static Niecza.Frame MAIN(Niecza.Frame th) {
switch (th.ip) {
case 0:
th.ip = 1;
return Niecza.Kernel.Fetch(th, th.pos[0]);
default:
return ((Niecza.IP6)th.resultSlot).Invoke(th.caller,
new Niecza.Variable[0] {}, null);
}
}
public static void Initialize() {}
}