-
Notifications
You must be signed in to change notification settings - Fork 15
/
Kernel.cs
4944 lines (4436 loc) · 188 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.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Niecza.CLRBackend;
using Niecza.Serialization;
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.
// Used by DynFrame to plug in code
public delegate Frame DynBlockDelegate(Frame frame);
public sealed class DispatchEnt {
public DispatchEnt next;
public SubInfo info;
public Frame outer;
public P6any ip6;
public DispatchEnt() {}
public DispatchEnt(DispatchEnt next, P6any ip6) {
this.ip6 = ip6;
this.next = next;
P6opaque d = (P6opaque)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 : IFreeze {
public ViviHook whence;
// these should be treated as ro for the life of the variable
public STable type;
public bool rw;
public bool islist;
public abstract P6any Fetch();
public abstract void Store(P6any v);
public abstract Variable GetVar();
const int S_RO = 0;
const int S_LIST = 1;
const int S_RW = 2;
const int S_VIV = 3;
public abstract void Freeze(FreezeBuffer fb);
internal void BaseFreeze(FreezeBuffer fb, SerializationCode code) {
fb.Byte((byte)((int)code + (islist ? S_LIST :
!rw ? S_RO : whence == null ? S_RW : S_VIV)));
if (whence != null) fb.ObjRef(whence);
if (rw) fb.ObjRef(type);
}
// note: callers need to make sure type is set up properly if null
public Variable() { }
internal Variable(ThawBuffer tb, int subcode) {
switch (subcode) {
default: break;
case S_RO:
// rw = false islist = false whence = null type = null
break;
case S_LIST:
islist = true;
break;
case S_VIV:
whence = (ViviHook) tb.ObjRef();
goto case S_RW;
case S_RW:
rw = true;
type = (STable) tb.ObjRef();
break;
}
}
public static readonly Variable[] None = new Variable[0];
}
public abstract class ViviHook : IFreeze {
public abstract void Freeze(FreezeBuffer fb);
public abstract void Do(Variable toviv);
}
public class SubViviHook : ViviHook {
P6any sub;
public SubViviHook(P6any sub) { this.sub = sub; }
public override void Do(Variable toviv) {
Kernel.RunInferior(sub.Invoke(Kernel.GetInferiorRoot(),
new Variable[] { toviv }, null));
}
public override void Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.SubViviHook);
fb.ObjRef(sub);
}
internal static SubViviHook Thaw(ThawBuffer tb) {
return new SubViviHook((P6any)tb.ObjRef());
}
}
public class HashViviHook : ViviHook {
P6any hash;
string key;
public HashViviHook(P6any hash, string key) { this.hash = hash; this.key = key; }
public override void Do(Variable toviv) {
VarHash rh = Kernel.UnboxAny<VarHash>(hash);
rh[key] = toviv;
}
public override void Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.HashViviHook);
fb.ObjRef(hash);
fb.String(key);
}
internal static IFreeze Thaw(ThawBuffer tb) {
return new HashViviHook((P6any)tb.ObjRef(), tb.String());
}
}
public class NewHashViviHook : ViviHook {
Variable hashv;
string key;
public NewHashViviHook(Variable hashv, string key) { this.hashv = hashv; this.key = key; }
public override void Do(Variable toviv) {
VarHash rh = new VarHash();
rh[key] = toviv;
hashv.Store(Kernel.BoxRaw(rh, Kernel.HashMO));
}
public override void Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.NewHashViviHook);
fb.ObjRef(hashv);
fb.String(key);
}
internal static IFreeze Thaw(ThawBuffer tb) {
return new NewHashViviHook((Variable)tb.ObjRef(), tb.String());
}
}
public class ArrayViviHook : ViviHook {
P6any ary;
int key;
public ArrayViviHook(P6any ary, int key) { this.ary = ary; this.key = key; }
public override void Do(Variable toviv) {
VarDeque vd = (VarDeque) ary.GetSlot("items");
while (vd.Count() <= key)
vd.Push(Kernel.NewTypedScalar(null));
vd[key] = toviv;
}
public override void Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.ArrayViviHook);
fb.ObjRef(ary);
fb.Int(key);
}
internal static IFreeze Thaw(ThawBuffer tb) {
return new ArrayViviHook((P6any)tb.ObjRef(), tb.Int());
}
}
public class NewArrayViviHook : ViviHook {
Variable ary;
int key;
public NewArrayViviHook(Variable ary, int key) { this.ary = ary; this.key = key; }
public override void Do(Variable toviv) {
VarDeque vd = new VarDeque();
while (vd.Count() <= key)
vd.Push(Kernel.NewTypedScalar(null));
vd[key] = toviv;
P6opaque d = new P6opaque(Kernel.ArrayMO);
d.slots[0] = vd;
d.slots[1] = new VarDeque();
ary.Store(d);
}
public override void Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.NewArrayViviHook);
fb.ObjRef(ary);
fb.Int(key);
}
internal static IFreeze Thaw(ThawBuffer tb) {
return new NewArrayViviHook((Variable)tb.ObjRef(), tb.Int());
}
}
public sealed class SimpleVariable: Variable {
P6any val;
public SimpleVariable(bool rw, bool islist, STable type, ViviHook whence, P6any val) {
this.val = val; this.whence = whence; this.rw = rw;
this.islist = islist; this.type = type;
}
public override P6any Fetch() { return val; }
public override void Store(P6any v) {
if (!rw) {
throw new NieczaException("Writing to readonly scalar");
}
if (v == Kernel.NilP) {
v = type.initObject;
}
if (!v.Does(type)) {
throw new NieczaException("Nominal type check failed for scalar store; got " + v.mo.name + ", needed " + type.name + " or subtype");
}
if (whence != null) {
ViviHook vh = whence;
whence = null;
vh.Do(this);
}
val = v;
}
public override Variable GetVar() {
return Kernel.BoxAnyMO<Variable>(this, Kernel.ScalarMO);
}
public override void Freeze(FreezeBuffer fb) {
BaseFreeze(fb, SerializationCode.SimpleVariable);
fb.ObjRef(val);
}
}
public sealed class TiedVariable: Variable {
P6any fetch;
P6any store;
public TiedVariable(STable type, P6any whsub, P6any fetch, P6any store) {
this.fetch = fetch;
this.store = store;
this.whence = whsub.IsDefined() ? new SubViviHook(whsub) : null;
this.rw = true;
this.type = type;
}
public override P6any Fetch() {
Variable vr = Kernel.RunInferior(fetch.Invoke(
Kernel.GetInferiorRoot(), None, null));
P6any vl = vr.Fetch();
if (!vl.Does(type))
throw new NieczaException("Tied variable of type " + type +
" returned value of type " + vl.mo.name + " instead");
return vl;
}
public override void Store(P6any v) {
if (whence != null) {
ViviHook vh = whence;
whence = null;
vh.Do(this);
}
Kernel.RunInferior(store.Invoke(Kernel.GetInferiorRoot(),
new Variable[] { Kernel.NewROScalar(v) }, null));
}
public override Variable GetVar() {
return Kernel.BoxAnyMO<Variable>(this, Kernel.ScalarMO);
}
public override void Freeze(FreezeBuffer fb) { throw new NotImplementedException(); }
}
// 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; }
}
public class StashEnt : IFreeze {
public Variable v;
public string file;
public int line;
void IFreeze.Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.StashEnt);
fb.ObjRef(v);
fb.String(file);
fb.Int(line);
}
internal static StashEnt Thaw(ThawBuffer tb) {
StashEnt r = new StashEnt();
r.v = (Variable)tb.ObjRef();
r.file = tb.String();
r.line = tb.Int();
return r;
}
}
public sealed class RuntimeUnit : IFreeze {
public string name, filename, modtime, asm_name, dll_name;
public Dictionary<string, StashEnt> globals;
public SubInfo mainline, bottom;
public bool is_mainish;
public Type type;
// used during construction only
public List<SubInfo> our_subs;
public AssemblyBuilder asm_builder;
public ModuleBuilder mod_builder;
public TypeBuilder type_builder;
public List<KeyValuePair<int,STable>> stubbed_stashes;
public Dictionary<object, FieldBuilder> constants;
internal Dictionary<string, CpsOp> val_constants;
public int nextid;
class IdentityComparer : IEqualityComparer<object> {
public int GetHashCode(object o) {
return RuntimeHelpers.GetHashCode(o);
}
public new bool Equals(object a, object b) {
return a == b;
}
}
public RuntimeUnit(string name, string filename, string modtime,
string obj_dir, bool main, bool runnow) {
this.name = name;
this.filename = filename;
this.modtime = modtime;
this.globals = new Dictionary<string,StashEnt>();
this.stubbed_stashes = new List<KeyValuePair<int,STable>>();
this.is_mainish = main;
if (name == "CORE")
Kernel.CreateBasicTypes();
this.asm_name = name.Replace("::", ".");
this.dll_name = asm_name + (main ? ".exe" : ".dll");
this.asm_builder = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName(asm_name),
(runnow ? AssemblyBuilderAccess.RunAndSave :
AssemblyBuilderAccess.Save), obj_dir);
//mod_builder = runnow ? asm_builder.DefineDynamicModule(asm_name) :
// asm_builder.DefineDynamicModule(asm_name, filename);
mod_builder = asm_builder.DefineDynamicModule(asm_name, dll_name);
type_builder = mod_builder.DefineType(asm_name,
TypeAttributes.Public | TypeAttributes.Sealed |
TypeAttributes.Abstract | TypeAttributes.Class |
TypeAttributes.BeforeFieldInit);
constants = new Dictionary<object,FieldBuilder>(new IdentityComparer());
val_constants = new Dictionary<string,CpsOp>();
our_subs = new List<SubInfo>();
}
public void PrepareEval() {
NamProcessor[] ths = new NamProcessor[our_subs.Count];
for (int i = 0; i < ths.Length; i++) {
SubInfo z = our_subs[i];
if (Config.CGVerbose > 0)
Console.WriteLine("generating code for: {0}", z.name);
ths[i] = new NamProcessor(
new CpsBuilder(this, "C" + i + z.name, true), z);
ths[i].MakeBody(Reader.Read(z.nam_str, z.nam_refs));
}
type = type_builder.CreateType();
asm_builder.Save(dll_name);
foreach (KeyValuePair<object, FieldBuilder> kv in constants)
type.GetField(kv.Value.Name).SetValue(null, kv.Key);
for (int i = 0; i < ths.Length; i++) {
ths[i].FillSubInfo(type);
if ((our_subs[i].special & SUB_IS_UNSAFE) != 0)
Kernel.CheckUnsafe(our_subs[i]);
}
if (Environment.GetEnvironmentVariable("NIECZA_DEFER_TRACE") != null) {
Kernel.TraceFlags = Kernel.TRACE_CUR;
Kernel.TraceCount = Kernel.TraceFreq = 1;
}
Kernel.FirePhasers(Kernel.PHASER_UNIT_INIT, false);
Kernel.FirePhasers(Kernel.PHASER_INIT, false);
}
internal CpsOp TypeConstant(STable s) {
return RefConstant(s == null ? "" : s.name, s, Tokens.STable);
}
internal CpsOp SubConstant(SubInfo s) {
return RefConstant(s == null ? "" : s.name, s, Tokens.SubInfo);
}
internal CpsOp RefConstant(string name, object val, Type nty) {
if (val == null)
return CpsOp.Null(nty);
FieldBuilder fi;
if (!constants.TryGetValue(val, out fi))
constants[val] = fi = NewField(name, val is Variable ? typeof(Variable) : val.GetType());
return CpsOp.IsConst(CpsOp.GetSField(fi));
}
internal CpsOp ValConstant(string desc, object val) {
CpsOp r;
if (!val_constants.TryGetValue(desc, out r))
val_constants[desc] = r =
RefConstant(desc.Substring(0, desc.Length > 20 ? 20 : desc.Length), val, null);
return r;
}
internal CpsOp VarConstStr(string s) {
return ValConstant('S' + s, Builtins.MakeStr(s));
}
internal CpsOp VarConstNum(double n) {
char[] c = new char[5];
c[0] = 'N';
long b = BitConverter.DoubleToInt64Bits(n);
c[1] = (char)(b);
c[2] = (char)(b >> 16);
c[3] = (char)(b >> 32);
c[4] = (char)(b >> 48);
return ValConstant(new string(c), Builtins.MakeFloat(n));
}
public Variable ExactNum(int numbase, string digits) {
BigInteger num = BigInteger.Zero;
BigInteger den = BigInteger.Zero;
bool neg = false;
foreach (char d in digits) {
if (d == '-') neg = true;
if (d == '_') continue;
if (d == '.') {
if (den != BigInteger.Zero)
throw new Exception("two dots in " + digits);
den = BigInteger.One;
continue;
}
int digval;
if (d >= '0' && d <= '9') { digval = d - '0'; }
else if (d >= 'a' && d <= 'z') { digval = d + 10 - 'a'; }
else if (d >= 'A' && d <= 'Z') { digval = d + 10 - 'A'; }
else { throw new Exception("invalid digit in " + digits); }
if (digval >= numbase) { throw new Exception("out of range digit in " + digits); }
num *= numbase;
den *= numbase;
num += digval;
}
if (neg) num = -num;
if (num == BigInteger.Zero && den.Sign > 0)
den = BigInteger.One;
if (den > BigInteger.One) {
BigInteger g = BigInteger.GreatestCommonDivisor(num, den);
if (g != BigInteger.One) {
num /= g;
den /= g;
}
}
ulong sden;
if (!den.AsUInt64(out sden)) {
return Builtins.MakeFloat((double)num / (double)den);
}
if (sden == 0)
return Builtins.MakeInt(num);
return Builtins.MakeFixRat(num, sden);
}
internal CpsOp VarConstExact(int bas, string digs) {
return ValConstant("X" + bas + ',' + digs, ExactNum(bas, digs));
}
internal CpsOp CCConst(int[] cc) {
StringBuilder code = new StringBuilder("CC");
foreach (int x in cc) {
code.Append((char)x);
code.Append((char)(x>>16));
}
return ValConstant(code.ToString(), new CC(cc));
}
internal CpsOp StringListConst(string[] sl) {
StringBuilder code = new StringBuilder("SL");
foreach (string s in sl) {
code.Append((char)(s.Length >> 16));
code.Append((char)(s.Length));
code.Append(s);
}
return ValConstant(code.ToString(), sl);
}
internal CpsOp CCListConst(int[][] ccl) {
StringBuilder code = new StringBuilder("CL");
foreach (int[] cc in ccl) {
code.Append((char)(cc.Length >> 16));
code.Append((char)(cc.Length));
foreach (int x in cc) {
code.Append((char)x);
code.Append((char)(x>>16));
}
}
CC[] buf = new CC[ccl.Length];
for (int i = 0; i < buf.Length; i++) buf[i] = new CC(ccl[i]);
return ValConstant(code.ToString(), buf);
}
internal CpsOp AltInfoConst(CgContext cx, object lads, string dba, string[] labels) {
throw new NotImplementedException(); // TODO: redesign needed
}
internal FieldBuilder NewField(string name, Type ty) {
string fname = name;
int i = 1;
while (type_builder.GetField(fname) != null)
fname = name + (i++);
return type_builder.DefineField(fname, ty, FieldAttributes.Public |
FieldAttributes.Static);
}
public static Variable MakeAppropriateVar(string name) {
if (name.Length >= 1 && name[0] == '@')
return Kernel.CreateArray();
if (name.Length >= 1 && name[0] == '%')
return Kernel.CreateHash();
return Kernel.NewTypedScalar(null);
}
public static string NsMerge(string who, string name,
ref StashEnt nse, StashEnt ose) {
P6any nseo = nse.v.Fetch();
P6any oseo = ose.v.Fetch();
bool nseod = nseo.IsDefined();
bool oseod = oseo.IsDefined();
// lowest priority are empty common symbols
if (nse.v.rw && !nseod) {
nse = ose;
return null;
}
if (ose.v.rw && !oseod) {
return null;
}
// no conflict if items are identical
if (!ose.v.rw && !nse.v.rw && oseo == nseo) {
nse = ose;
return null;
}
// no conflict if items are simple packages with the same who
if (!ose.v.rw && !oseod && oseo.mo.mo.isPackage &&
!nse.v.rw && !nseod && nseo.mo.mo.isPackage &&
oseo.mo.who.Isa(Kernel.StashMO) &&
nseo.mo.who.Isa(Kernel.StashMO) &&
Kernel.UnboxAny<string>(oseo.mo.who) ==
Kernel.UnboxAny<string>(nseo.mo.who)) {
nse = ose;
return null;
}
return "Two definitions found for symbol "+who+"::"+name+"\n\n" +
" first at "+ose.file+" line "+ose.line+"\n" +
" second at "+nse.file+" line "+nse.line;
}
public string NsBind(string who, string name, Variable var,
string file, int line) {
string key = (char)who.Length + who + name;
StashEnt nse = new StashEnt();
if (var == null)
var = MakeAppropriateVar(name);
nse.v = var;
nse.file = file;
nse.line = line;
StashEnt ose;
string err = null;
if (globals.TryGetValue(key, out ose))
err = NsMerge(who, name, ref nse, ose);
if (err != null) return err;
globals[key] = nse;
return null;
}
public const int SUB_RUN_ONCE = 1;
public const int MAKE_PROTOPAD = 2;
public const int SUB_HAS_TYPE = 4;
public const int SUB_IS_UNSAFE = 8;
public const int SUB_IS_PARAM_ROLE = 16;
public const int SUB_MAINLINE = 32;
public const int SUB_TRANSPARENT = 64;
public const int SUB_INLINED = 128;
public const int SUB_CANNOT_INLINE = 256;
public const int SUB_RETURN_PASS = 512;
void IFreeze.Freeze(FreezeBuffer fb) {
fb.Byte((byte)SerializationCode.RuntimeUnit);
fb.String(name);
fb.String(filename);
fb.String(modtime);
fb.String(asm_name);
fb.String(dll_name);
fb.Int(globals.Count);
foreach (KeyValuePair<string, StashEnt> kv in globals) {
fb.String(kv.Key);
fb.ObjRef(kv.Value);
}
fb.ObjRef(mainline);
fb.ObjRef(bottom);
fb.Byte((byte)(is_mainish ? 1 : 0));
}
}
public class LeaveHook {
public LeaveHook next;
public P6any thunk;
public int type;
public const int KEEP = 1;
public const int UNDO = 2;
public const int DIE = 4;
public const int POST = 7;
}
public abstract class LexInfo {
public SubInfo owner;
public string name;
public string file;
public int line;
public int pos;
public abstract void Init(Frame f);
public abstract object Get(Frame f);
public virtual void Set(Frame f, object to) {
throw new NieczaException("Variable cannot be bound");
}
internal virtual ClrOp SetCode(int up, ClrOp head) {
throw new Exception("Lexicals of type " + this + " cannot be bound");
}
internal abstract ClrOp GetCode(int up);
// names that are forced to dynamism for quick access
public static bool IsDynamicName(string name) {
if (name == "$_" || name == "$/" || name == "$!") return true;
if (name.Length < 2) return false;
if (name[0] == '*' || name[0] == '?') return true;
if (name[1] == '*' || name[1] == '?') return true;
return false;
}
public virtual void BindFields() {}
public virtual int SigIndex() { return -1; }
}
public abstract class LIVarish : LexInfo {
public int index;
public LIVarish() { }
public override int SigIndex() { return index; }
public override void BindFields() {
index = owner.num_lex_slots++;
if (owner.protopad != null) {
int osz = owner.protopad.lexn == null ? 0 : owner.protopad.lexn.Length;
if (owner.num_lex_slots > 10 + osz)
Array.Resize(ref owner.protopad.lexn, owner.num_lex_slots * 2 - 10);
}
}
public override object Get(Frame f) {
return f.GetDynamic(index);
}
public override void Set(Frame f, object to) {
f.SetDynamic(index, to);
}
internal override ClrOp GetCode(int up) {
if ((owner.special & RuntimeUnit.SUB_RUN_ONCE) != 0) {
return new ClrUnboxAny(Tokens.Variable,
new ClrMethodCall(false, Tokens.Frame.GetMethod("GetDynamic"),
Backend.currentUnit.RefConstant(
owner.name, owner.protopad, typeof(Frame)).head,
new ClrIntLiteral(typeof(int), index)));
//return new ClrProtoGet(index,
// Backend.currentUnit.RefConstant(
// owner.name, owner.protopad, typeof(Frame)).head);
}
return new ClrPadGet(up, index);
}
internal override ClrOp SetCode(int up, ClrOp to) {
if ((owner.special & RuntimeUnit.SUB_RUN_ONCE) != 0)
return new ClrProtoSet(index,
Backend.currentUnit.RefConstant(
owner.name, owner.protopad, typeof(Frame)).head, to);
return new ClrPadSet(up, index, to);
}
}
// TODO: Provide some way to cache a StashEnt once the currentGlobals
// stops changing
public class LICommon : LexInfo {
public readonly string hkey;
public LICommon(string hkey) { this.hkey = hkey; }
public override void Init(Frame f) { }
internal string Stash() { return hkey.Substring(1, (int)hkey[0]); }
internal string VarName() { return hkey.Substring(1 + (int)hkey[0]); }
public override object Get(Frame f) {
return Kernel.currentGlobals[hkey].v;
}
public override void Set(Frame f, object to) {
Kernel.currentGlobals[hkey].v = (Variable)to;
}
internal override ClrOp GetCode(int up) {
return new ClrMethodCall(false, Tokens.Kernel_GetGlobal,
new ClrStringLiteral(hkey));
}
internal override ClrOp SetCode(int up, ClrOp to) {
return new ClrMethodCall(false, Tokens.Kernel_BindGlobal,
new ClrStringLiteral(hkey), to);
}
}
public class LIHint : LexInfo {
public BValue var;
public LIHint() { }
public override void Init(Frame f) { }
public override void BindFields() {
var = new BValue(null);
}
public override object Get(Frame f) { return var.v; }
public override void Set(Frame f, object to) { var.v = (Variable)to; }
internal override ClrOp GetCode(int up) {
return new ClrGetField(Tokens.BValue_v,
Backend.currentUnit.RefConstant(name, var, null).head);
}
internal override ClrOp SetCode(int up, ClrOp to) {
return new ClrSetField(Tokens.BValue_v,
Backend.currentUnit.RefConstant(name, var, null).head, to);
}
}
public class LISub : LIVarish {
public SubInfo def;
public LISub(SubInfo def) { this.def = def; }
public override void Init(Frame f) {
Set(f, Kernel.NewROScalar(def.protosub));
}
}
public class LISimple : LIVarish {
public const int NOINIT = 1;
public const int ROINIT = 2;
public const int DEFOUTER = 4;
public const int LIST = 8;
public const int HASH = 16;
public int flags;
public STable type;
public LISimple(int flags, STable type) {
this.flags = flags;
this.type = type;
}
public override void Init(Frame f) {
if ((flags & NOINIT) != 0)
return;
if ((flags & ROINIT) != 0)
Set(f, Kernel.AnyMO.typeVar);
else if ((flags & DEFOUTER) != 0)
Set(f, f.info.GetOuterTopic(f));
else if ((flags & LIST) != 0)
Set(f, Kernel.CreateArray());
else if ((flags & HASH) != 0)
Set(f, Kernel.CreateHash());
else
Set(f, Kernel.NewTypedScalar(type));
}
}
public class LILabel : LIVarish {
public override void Init(Frame f) {
Set(f, Kernel.NewLabelVar(f, name));
}
}
public class LIDispatch : LIVarish {
public override void Init(Frame f) {
throw new Exception("MMD NYI");
}
}
public class LIAlias : LexInfo {
public string to;
public LIAlias(string to) { this.to = to; }
public override void Init(Frame f) { }
object Common(Frame f, bool set, object bind) {
Frame cr = f;
LexInfo li = null;
while (cr.info.dylex == null ||
!cr.info.dylex.TryGetValue(to, out li))
cr = cr.outer;
if (!set) return li.Get(cr);
else { li.Set(cr, bind); return null; }
}
public override object Get(Frame f) { return Common(f,false,null); }
public override void Set(Frame f, object bind) { Common(f,true,bind); }
internal override ClrOp GetCode(int up) {
LexInfo real;
SubInfo sc = owner;
while (!sc.dylex.TryGetValue(to, out real)) {
sc = sc.outer;
up++;
}
return real.GetCode(up);
}
internal override ClrOp SetCode(int up, ClrOp bind) {
LexInfo real;
SubInfo sc = owner;
while (!sc.dylex.TryGetValue(to, out real)) {
sc = sc.outer;
up++;
}
return real.SetCode(up, bind);
}
}
public class LIPackage : LexInfo {
public STable pkg;
public LIPackage(STable pkg) { this.pkg = pkg; }
public override object Get(Frame f) { return pkg.typeVar; }
public override void Init(Frame f) { }
internal override ClrOp GetCode(int up) {
return Backend.currentUnit.RefConstant(pkg.name + "V",
pkg.typeVar, typeof(Variable)).head;
}
}
// This stores all the invariant stuff about a Sub, i.e. everything
// except the outer pointer. Now distinct from protopads
//
// Actually not quite *in*variant; some of this stuff has to be
// changed, but it's rare by construction. We don't want to be
// like Rakudo/Parrot where simple sub cloning requires copying
// 100s of bytes.
public class SubInfo : IFreeze {
// Essential call functions
public DynBlockDelegate code;
public int nspill;
public int[] sig_i;
public object[] sig_r;
// Basic metadata
public int[] lines;
public Dictionary<string, LexInfo> dylex;
public uint dylex_filter; // (32,1) Bloom on hash code
// References to related objects
public SubInfo outer;
public P6any protosub;
public Frame protopad;
public RuntimeUnit unit;
public STable mo;
// Standard metadata
public string name;
// maybe should be a hint
public LAD ltm;
public int special;
public int phaser;
public STable cur_pkg, methodof, body_of, in_class;
public string outervar;
public int outer_topic_rank;
public int outer_topic_key;
public int self_key;
public SubInfo catch_, control;
public class UsedInScopeInfo {
public string file;
public int line;
public int levels;
public string orig_file;
public int orig_line;
}
public Dictionary<string,UsedInScopeInfo> used_in_scope;
public int num_lex_slots;
// if this is non-null, compilation is being delayed
public string nam_str;
public object[] nam_refs;
// Used for closing runtime-generated SubInfo over values used
// For vtable wrappers: 0 = unboxed, 1 = boxed
// For dispatch routines, 0 = parameter list
public object param0, param1;
public List<SubInfo> children = new List<SubInfo>();
public Dictionary<string,object[]> extend;
// No instance fields past this point
public const int SIG_I_RECORD = 3;
public const int SIG_I_FLAGS = 0;
public const int SIG_I_SLOT = 1;
public const int SIG_I_NNAMES = 2;
// R records are variable size, but contain canonical name,
// usable names (in order), default SubInfo (if present),
// type STable (if present)
// Value processing
public const int SIG_F_HASTYPE = 1; // else Kernel.AnyMO
public const int SIG_F_MULTI_IGNORED = 16384;
// Value binding
public const int SIG_F_READWRITE = 2;
public const int SIG_F_RWTRANS = 8;
public const int SIG_F_BINDLIST = 16;
public const int SIG_F_INVOCANT = 8192;
public const int SIG_F_IS_COPY = 32768;
public const int SIG_F_IS_LIST = 65536;
public const int SIG_F_IS_HASH = 131072;
// Value source
public const int SIG_F_HASDEFAULT = 32;
public const int SIG_F_OPTIONAL = 64;
public const int SIG_F_DEFOUTER = 4096;
public const int SIG_F_POSITIONAL = 128;
public const int SIG_F_SLURPY_POS = 256;
public const int SIG_F_SLURPY_NAM = 512;
public const int SIG_F_SLURPY_CAP = 1024;
public const int SIG_F_SLURPY_PCL = 2048;
public const uint FILTER_SALT = 0x9e3779b9;
// 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 const int ON_VARLOOKUP = 10;
public const int ON_WARNING = 11;
// ON_VARLOOKUP is kinda special, it's not used for exceptions
// but rather for $*FOO and the like; goto = the variable index
public int[] edata;
public string[] label_names;
private static string[] controls = new string[] { "unknown", "next",
"last", "redo", "return", "die", "succeed", "proceed", "goto",
"nextsame/nextwith", "varlookup", "warning" };
public static string DescribeControl(int type, Frame tgt,
string name) {
string ty = (type < controls.Length) ? controls[type] : "unknown";
if (name != null) {
return ty + "(" + name + (tgt != null ? ", lexotic)" : ", dynamic)");
} else {
return ty;
}
}
public int GetInlineSlot(int ip, string name, int depth) {
int end = 0;
// ON_VARLOOKUP nodes are created in a set of 0 or more,
// followed by a nameless one that marks the depth.
// Find the correct end-node for the passed depth
while (end < edata.Length) {
if (edata[end+2] == ON_VARLOOKUP && edata[end+4] < 0 &&
edata[end+3] == depth && ip >= edata[end] &&
ip < edata[end+1])
break;
end += 5;
}
if (end == edata.Length) return -1;
while (true) {
end -= 5;