-
Notifications
You must be signed in to change notification settings - Fork 15
/
CLRBackend.cs
3649 lines (3297 loc) · 155 KB
/
CLRBackend.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
// This is the new CLR backend. The old one generated C# from Perl, which
// was slow and gave us the limitations of C#; this one aims to be faster.
// Also, by making the Perl code emit a portable format, it makes future
// portability work easier.
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Niecza;
namespace Niecza.CLRBackend {
// The portable format is a subset of JSON, and is current read
// into a matching internal form.
sealed class JScalar {
string text;
double val;
bool has_val;
public JScalar(string txt) { text = txt; }
public string str { get { return text; } }
public double num {
get {
if (has_val) return val;
val = double.Parse(text);
has_val = true;
return val;
}
}
public static string[] SA(int cut, object x) {
object[] arr = (object[]) x;
string[] r = new string[ arr.Length - cut ];
for (int i = 0; i < r.Length; i++)
r[i] = ((JScalar)arr[i+cut]).str;
return r;
}
public static int[] IA(int cut, object x) {
object[] arr = (object[]) x;
int[] r = new int[ arr.Length - cut ];
for (int i = 0; i < r.Length; i++)
r[i] = (int)((JScalar)arr[i+cut]).num;
return r;
}
public static bool B(object x) {
string s = S(x);
if (s == "1") return true;
if (s == "0" || s == "") return false;
throw new ArgumentException(s);
}
public static int I(object x) { return (int)((JScalar)x).num; }
public static string S(object x) { return x == null ? null : ((JScalar)x).str; }
public override string ToString() { return text; }
}
class Reader {
static char GetHexQuad(string s, int ix) {
int acc = 0;
for (int i = 0; i < 4; i++) {
acc <<= 4;
int ch = (int)s[ix+i];
acc += (ch>=(int)'a'&&ch<=(int)'f') ? (ch + 10 - (int)'a') :
(ch>=(int)'A'&&ch<=(int)'F') ? (ch + 10 - (int)'A') :
(ch - (int)'0');
}
return (char)acc;
}
public static object Read(string input) {
int ix = 0;
List<List<object>> containers = new List<List<object>>();
char i;
StringBuilder sb;
while (true) {
i = input[ix];
if (i == '\t' || i == ' ' || i == '\r' || i == '\n' ||
i == ',') {
ix++;
continue;
}
if (i == '[') {
containers.Add(new List<object>());
ix++;
continue;
}
if (i == ']') {
object[] r = containers[containers.Count - 1].ToArray();
containers.RemoveAt(containers.Count - 1);
if (containers.Count == 0) return r;
containers[containers.Count - 1].Add(r);
ix++;
continue;
}
if (i == 'n' && input.Length >= ix + 4 &&
input[ix+1] == 'u' && input[ix+2] == 'l' &&
input[ix+3] == 'l') {
containers[containers.Count - 1].Add(null);
ix += 4;
continue;
}
if (i == '"') {
sb = new StringBuilder();
ix++;
while (true) {
i = input[ix];
if (i == '\\') {
switch (input[ix+1]) {
case '/': i = '/'; break;
case '\\': i = '\\'; break;
case 't': i = '\t'; break;
case 'r': i = '\r'; break;
case 'n': i = '\n'; break;
case 'f': i = '\f'; break;
case 'b': i = '\b'; break;
case 'u': i = GetHexQuad(input, ix+2); ix += 4; break;
}
ix += 2;
sb.Append(i);
} else if (i == '"') {
break;
} else {
sb.Append(i);
ix++;
}
}
ix++;
containers[containers.Count - 1].Add(new JScalar(sb.ToString()));
continue;
}
sb = new StringBuilder();
while (true) {
i = input[ix];
if (i == ',' || i == '\r' || i == '\t' || i == '\n' ||
i == ' ' || i == ']')
break;
sb.Append(i);
ix++;
}
containers[containers.Count - 1].Add(new JScalar(sb.ToString()));
}
}
}
// Because this is the *CLR* backend's Unit object, it's always
// associated with either an Assembly or an AssemblyBuilder.
class Unit {
public readonly Xref mainline_ref;
public readonly string name;
public readonly object[] log;
public readonly string setting;
public readonly Xref bottom_ref;
public readonly object[] xref;
public readonly object[] tdeps;
public readonly Dictionary<string, Package> exp_pkg;
public Assembly clrAssembly;
public Type clrType;
public Unit(object[] from) {
mainline_ref = new Xref(from[0] as object[]);
name = ((JScalar) from[1]).str;
log = from[2] as object[];
setting = from[3] == null ? null : ((JScalar) from[3]).str;
bottom_ref = Xref.from(from[4] as object[]);
xref = from[5] as object[];
exp_pkg = new Dictionary<string,Package>();
for (int i = 0; i < xref.Length; i++) {
if (xref[i] == null) continue;
object[] xr = (object[]) xref[i];
if (xr.Length > 7) {
xref[i] = new StaticSub(this, xr);
} else {
xref[i] = Package.From(xr);
(xref[i] as Package).NoteExports(exp_pkg);
}
}
tdeps = from[6] as object[];
}
public void BindDepends() {
foreach (object x in tdeps) {
string n = ((JScalar)(((object[]) x)[0])).str;
if (n == name) continue;
Unit o = CLRBackend.GetUnit(n);
foreach (KeyValuePair<string,Package> kv in o.exp_pkg)
exp_pkg[kv.Key] = kv.Value;
}
}
public void VisitSubsPostorder(Action<int,StaticSub> cb) {
DoVisitSubsPostorder(mainline_ref.index, cb);
}
public void VisitSubsPreorder(Action<int,StaticSub> cb) {
DoVisitSubsPreorder(mainline_ref.index, cb);
}
public void VisitPackages(Action<int,Package> cb) {
for (int i = 0; i < xref.Length; i++) {
Package p = xref[i] as Package;
if (p != null)
cb(i, p);
}
}
private void DoVisitSubsPostorder(int ix, Action<int,StaticSub> cb) {
StaticSub s = xref[ix] as StaticSub;
foreach (int z in s.zyg)
DoVisitSubsPostorder(z, cb);
cb(ix,s);
}
private void DoVisitSubsPreorder(int ix, Action<int,StaticSub> cb) {
StaticSub s = xref[ix] as StaticSub;
cb(ix,s);
foreach (int z in s.zyg)
DoVisitSubsPreorder(z, cb);
}
public Package GetPackage(string[] strs, int f, int l) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < l; i++) {
string rxes = strs[i+f];
sb.Append((char)(rxes.Length >> 16));
sb.Append((char)(rxes.Length & 0xFFFF));
sb.Append(rxes);
}
Package p;
exp_pkg.TryGetValue(sb.ToString(), out p);
return p;
}
public Package GetCorePackage(string name) {
StaticSub r = (StaticSub) (bottom_ref ?? mainline_ref).Resolve();
return r.GetCorePackage(name);
}
public static string SharedName(char type, int ix, string name) {
StringBuilder sb = new StringBuilder();
sb.Append(type);
sb.Append(ix);
sb.Append('_');
foreach (char c in name) {
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')) {
sb.Append(c);
} else if (c == '_') {
sb.Append("__");
} else if (c <= (char)255) {
sb.AppendFormat("_{0:X2}", (int)c);
} else {
sb.AppendFormat("_U{0:X4}", (int)c);
}
}
return sb.ToString();
}
public void BindFields(Func<string,Type,FieldInfo> binder) {
VisitSubsPostorder(delegate(int ix, StaticSub sub) {
sub.BindFields(ix, binder);
});
VisitPackages(delegate(int ix, Package pkg) {
pkg.BindFields(ix, binder);
});
}
}
class Xref {
public readonly string unit;
public readonly int index;
public readonly string name;
public static Xref from(object[] x) {
return (x == null) ? null : new Xref(x);
}
public Xref(object[] from) : this(from, 0) {}
public Xref(object[] from, int ofs) {
unit = ((JScalar)from[ofs+0]).str;
index = (int)((JScalar)from[ofs+1]).num;
name = ((JScalar)from[ofs+2]).str;
}
public object Resolve() { return CLRBackend.Resolve(this); }
}
class Package {
public readonly string name;
public readonly string type;
public readonly object[] exports;
public Package(object[] p) {
type = ((JScalar)p[0]).str;
name = ((JScalar)p[1]).str;
exports = (object[]) p[2];
}
internal void NoteExports(Dictionary<string,Package> dp) {
foreach (object x in exports) {
object[] rx = (object[]) x;
StringBuilder sb = new StringBuilder();
foreach (object rxe in rx) {
string rxes = ((JScalar) rxe).str;
sb.Append((char)(rxes.Length >> 16));
sb.Append((char)(rxes.Length & 0xFFFF));
sb.Append(rxes);
}
dp[sb.ToString()] = this;
}
}
public virtual void BindFields(int ix,
Func<string,Type,FieldInfo> binder) { }
public static Package From(object[] p) {
string type = ((JScalar)p[0]).str;
if (type == "parametricrole")
return new ParametricRole(p);
else if (type == "role")
return new Role(p);
else if (type == "class")
return new Class(p);
else if (type == "grammar")
return new Grammar(p);
else if (type == "module")
return new Module(p);
else if (type == "package")
return new Package(p);
else
throw new Exception("unknown package type " + p);
}
}
class Module: Package {
public Module(object[] p) : base(p) { }
}
class ModuleWithTypeObject: Module {
public FieldInfo typeObject;
public FieldInfo typeVar;
public FieldInfo metaObject;
public override void BindFields(int ix,
Func<string,Type,FieldInfo> binder) {
typeObject = binder(Unit.SharedName('T', ix, name), Tokens.IP6);
typeVar = binder(Unit.SharedName('V', ix, name), Tokens.Variable);
metaObject = binder(Unit.SharedName('M', ix, name), Tokens.DynMetaObject);
}
public ModuleWithTypeObject(object[] p) : base(p) { }
}
class Class: ModuleWithTypeObject {
public readonly string[] attributes;
public readonly object[] methods;
public readonly object[] superclasses;
public readonly object[] linearized_mro;
public Class(object[] p) : base(p) {
attributes = JScalar.SA(0, p[3]);
methods = p[4] as object[];
superclasses = p[5] as object[];
linearized_mro = p[6] as object[];
}
}
class Grammar: Class {
public Grammar(object[] p) : base(p) { }
}
class Role: ModuleWithTypeObject {
public readonly string[] attributes;
public readonly object[] methods;
public readonly object[] superclasses;
public Role(object[] p) : base(p) {
attributes = JScalar.SA(0,p[3]);
methods = p[4] as object[];
superclasses = p[5] as object[];
}
}
class ParametricRole: ModuleWithTypeObject {
public readonly object[] attributes;
public readonly object[] methods;
public readonly object[] superclasses;
public ParametricRole(object[] p) : base(p) {
attributes = p[3] as object[];
methods = p[4] as object[];
superclasses = p[5] as object[];
}
}
class StaticSub {
public const int RUN_ONCE = 1;
public const int SPAD_EXISTS = 2;
public const int GATHER_HACK = 4;
public const int STRONG_USED = 8;
public const int RETURNABLE = 16;
public const int AUGMENTING = 32;
public readonly string name;
public readonly Unit unit;
public readonly Xref outer;
public readonly int flags;
public readonly int[] zyg;
public readonly object parametric_role_hack;
public readonly object augment_hack;
public readonly int is_phaser;
public readonly Xref body_of;
public readonly Xref in_class;
public readonly string[] cur_pkg;
public readonly string sclass;
public readonly object ltm;
public readonly object[] exports;
public readonly object sig;
public readonly List<KeyValuePair<string,Lexical>> lexicals;
public readonly Dictionary<string,Lexical> l_lexicals;
public readonly object body;
public FieldInfo protosub;
public FieldInfo subinfo;
public FieldInfo protopad;
public int nlexn;
public StaticSub(Unit unit, object[] s) {
this.unit = unit;
name = ((JScalar)s[0]).str;
outer = Xref.from(s[1] as object[]);
flags = (int) ((JScalar)s[2]).num;
object[] r_zyg = s[3] as object[];
parametric_role_hack = s[4];
augment_hack = s[5];
is_phaser = s[6] == null ? -1 : (int) ((JScalar) s[6]).num;
body_of = Xref.from(s[7] as object[]);
in_class = Xref.from(s[8] as object[]);
object[] r_cur_pkg = s[9] as object[];
sclass = ((JScalar)s[10]).str;
ltm = s[11];
exports = (object[]) s[12];
sig = s[13];
zyg = new int[ r_zyg.Length ];
for (int i = 0; i < r_zyg.Length; i++)
zyg[i] = (int) ((JScalar) r_zyg[i]).num;
cur_pkg = new string[ r_cur_pkg.Length ];
for (int i = 0; i < r_cur_pkg.Length; i++)
cur_pkg[i] = ((JScalar) r_cur_pkg[i]).str;
object[] r_lexicals = s[14] as object[];
body = s[15];
lexicals = new List<KeyValuePair<string,Lexical>>();
l_lexicals = new Dictionary<string,Lexical>();
for (int i = 0; i < r_lexicals.Length; i++) {
object[] bl = r_lexicals[i] as object[];
string lname = ((JScalar)bl[0]).str;
string type = ((JScalar)bl[1]).str;
Lexical obj = null;
if (type == "simple") {
obj = new LexSimple(bl);
} else if (type == "common") {
obj = new LexCommon(bl);
} else if (type == "sub") {
obj = new LexSub(bl);
} else if (type == "alias") {
obj = new LexAlias(bl);
} else if (type == "stash") {
obj = new LexStash(unit, bl);
} else {
throw new Exception("unknown lex type " + type);
}
lexicals.Add(new KeyValuePair<string,Lexical>(lname, obj));
l_lexicals[lname] = obj;
}
}
public bool IsCore() {
string s = unit.name;
return (s == "SAFE" || s == "CORE");
}
public void BindFields(int ix, Func<string,Type,FieldInfo> binder) {
subinfo = binder(Unit.SharedName('I', ix, name), Tokens.SubInfo);
if ((flags & SPAD_EXISTS) != 0)
protopad = binder(Unit.SharedName('P', ix, name), Tokens.Frame);
if (outer == null || (((StaticSub)outer.Resolve()).flags
& SPAD_EXISTS) != 0)
protosub = binder(Unit.SharedName('S', ix, name), Tokens.IP6);
nlexn = 0;
for (int i = 0; i < lexicals.Count; i++)
lexicals[i].Value.BindFields(ix, i, this,
lexicals[i].Key, binder);
}
public Package GetCorePackage(string name) {
StaticSub csr = this;
while (csr.unit.name != "SAFE" && csr.unit.name != "CORE")
csr = (StaticSub) csr.outer.Resolve();
while (!csr.l_lexicals.ContainsKey(name))
csr = (StaticSub) csr.outer.Resolve();
LexStash lx = (LexStash)csr.l_lexicals[name];
return unit.GetPackage(lx.path, 0, lx.path.Length);
}
}
abstract class Lexical {
public virtual void BindFields(int six, int lix, StaticSub sub,
string name, Func<string,Type,FieldInfo> binder) { }
public virtual ClrOp SetCode(int up, ClrOp head) {
throw new Exception("Lexicals of type " + this + " cannot be bound");
}
public abstract ClrOp GetCode(int up);
public static bool IsDynamicName(string name) {
if (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;
}
}
class LexVarish : Lexical {
public int index;
public FieldInfo stg;
public override ClrOp GetCode(int up) {
return (index >= 0) ? (ClrOp)new ClrPadGet(up, index)
: new ClrGetSField(stg);
}
public override ClrOp SetCode(int up, ClrOp to) {
return (index >= 0) ? (ClrOp)new ClrPadSet(up, index, to)
: new ClrSetSField(stg, to);
}
public override void BindFields(int six, int lix, StaticSub sub,
string name, Func<string,Type,FieldInfo> binder) {
if (IsDynamicName(name) || (sub.flags & StaticSub.RUN_ONCE) == 0) {
index = sub.nlexn++;
} else {
index = -1;
stg = binder(Unit.SharedName('L', six, name), Tokens.Variable);
sub.nlexn++;
}
}
}
class LexSimple : LexVarish {
public const int NOINIT = 4;
public const int LIST = 2;
public const int HASH = 1;
public readonly int flags;
public LexSimple(object[] l) {
flags = (int)((JScalar)l[2]).num;
}
}
class LexCommon : Lexical {
public readonly string[] path;
public FieldInfo stg;
public LexCommon(object[] l) {
path = new string[l.Length - 2];
for (int i = 2; i < l.Length; i++)
path[i-2] = ((JScalar)l[i]).str;
}
public override ClrOp GetCode(int up) {
return new ClrGetField(Tokens.BValue_v,
new ClrGetSField(stg));
}
public override ClrOp SetCode(int up, ClrOp to) {
return new ClrSetField(Tokens.BValue_v,
new ClrGetSField(stg), to);
}
public override void BindFields(int six, int lix, StaticSub sub,
string name, Func<string,Type,FieldInfo> binder) {
stg = binder(Unit.SharedName('B', six, name), Tokens.BValue);
}
}
class LexSub : LexVarish {
public readonly Xref def;
public LexSub(object[] l) {
def = new Xref(l, 2);
}
}
class LexAlias : Lexical {
public readonly string to;
public LexAlias(object[] l) {
to = ((JScalar)l[2]).str;
}
public override ClrOp GetCode(int up) { throw new NotImplementedException(); }
}
class LexStash : Lexical {
public readonly Unit unit;
public readonly string[] path;
public Package GetPackage() {
return unit.GetPackage(path, 0, path.Length);
}
public override ClrOp GetCode(int up) {
ModuleWithTypeObject p = GetPackage() as ModuleWithTypeObject;
if (p == null) {
return new ClrMethodCall(false, Tokens.Kernel_NewROScalar,
new ClrOp[] { new ClrGetSField(Tokens.Kernel_AnyP) });
}
return new ClrMethodCall(false, Tokens.Kernel_NewROScalar,
new ClrOp[] { new ClrGetSField(p.typeObject) });
}
public LexStash(Unit u, object[] l) {
unit = u;
path = new string[l.Length - 2];
for (int i = 0; i < path.Length; i++)
path[i] = ((JScalar)l[i+2]).str;
}
}
// Extra info needed beyond what ILGenerator alone provides. Note
// that switch generation is done in another pass.
class CgContext {
public ILGenerator il;
public TypeBuilder tb;
public int next_case;
public Label[] cases;
public int num_cases;
public Dictionary<string,int> named_cases
= new Dictionary<string,int>();
public Dictionary<string,Label> named_labels
= new Dictionary<string,Label>();
public string[] let_names = new string[0];
public Type[] let_types = new Type[0];
public LocalBuilder ospill, pspill, nspill;
public List<int> lineStack = new List<int>();
public List<int> lineBuffer = new List<int>();
public List<int> ehspanBuffer = new List<int>();
public List<string> ehlabelBuffer = new List<string>();
public void make_ospill() {
if (ospill == null)
ospill = il.DeclareLocal(Tokens.Variable);
}
public void save_line() {
lineBuffer.Add(lineStack.Count == 0 ? 0 : lineStack[lineStack.Count - 1]);
}
[ThreadStatic] private static int next_array;
public void EmitIntArray(int[] vec) {
EmitInt(vec.Length);
// the mono JIT checks for this exact sequence
il.Emit(OpCodes.Newarr, Tokens.Int32);
if (vec.Length != 0) {
byte[] buf = new byte[vec.Length * 4];
int r = 0;
for (int i = 0; i < vec.Length; i++) {
uint d = (uint) vec[i];
buf[r++] = (byte)((d >> 0) & 0xFF);
buf[r++] = (byte)((d >> 8) & 0xFF);
buf[r++] = (byte)((d >> 16) & 0xFF);
buf[r++] = (byte)((d >> 24) & 0xFF);
}
FieldBuilder fb = tb.DefineInitializedData(
"A" + (next_array++), buf, 0);
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Ldtoken, fb);
il.Emit(OpCodes.Call, typeof(System.Runtime.CompilerServices.RuntimeHelpers).GetMethod("InitializeArray"));
}
}
// logic stolen from mcs
public void EmitInt(int i) {
switch (i) {
case -1: il.Emit(OpCodes.Ldc_I4_M1); break;
case 0: il.Emit(OpCodes.Ldc_I4_0); break;
case 1: il.Emit(OpCodes.Ldc_I4_1); break;
case 2: il.Emit(OpCodes.Ldc_I4_2); break;
case 3: il.Emit(OpCodes.Ldc_I4_3); break;
case 4: il.Emit(OpCodes.Ldc_I4_4); break;
case 5: il.Emit(OpCodes.Ldc_I4_5); break;
case 6: il.Emit(OpCodes.Ldc_I4_6); break;
case 7: il.Emit(OpCodes.Ldc_I4_7); break;
case 8: il.Emit(OpCodes.Ldc_I4_8); break;
default:
if (i >= -128 && i < 127) {
il.Emit(OpCodes.Ldc_I4_S, (sbyte) i);
} else {
il.Emit(OpCodes.Ldc_I4, i);
}
break;
}
}
public void EmitPreSetlex(int ix) {
if (ix >= (Tokens.NumInt32 + Tokens.NumInline)) {
il.Emit(OpCodes.Ldfld, Tokens.Frame_lexn);
EmitInt(ix - (Tokens.NumInt32 + Tokens.NumInline));
}
}
public void EmitSetlex(int ix, Type t) {
if (ix >= Tokens.NumInt32 && t.IsValueType)
il.Emit(OpCodes.Box, t);
if (ix >= (Tokens.NumInt32 + Tokens.NumInline)) {
il.Emit(OpCodes.Stelem_Ref);
} else if (ix >= Tokens.NumInt32) {
il.Emit(OpCodes.Stfld,
Tokens.Frame_lexobj[ix - Tokens.NumInt32]);
} else {
il.Emit(OpCodes.Stfld, Tokens.Frame_lexi32[ix]);
}
}
public void EmitGetlex(int ix, Type t) {
if (ix >= (Tokens.NumInt32 + Tokens.NumInline)) {
il.Emit(OpCodes.Ldfld, Tokens.Frame_lexn);
EmitInt(ix - (Tokens.NumInt32 + Tokens.NumInline));
il.Emit(OpCodes.Ldelem_Ref);
} else if (ix >= Tokens.NumInt32) {
il.Emit(OpCodes.Ldfld,
Tokens.Frame_lexobj[ix - Tokens.NumInt32]);
} else {
il.Emit(OpCodes.Ldfld, Tokens.Frame_lexi32[ix]);
}
if (ix >= Tokens.NumInt32) {
il.Emit(OpCodes.Unbox_Any, t);
}
}
}
sealed class Tokens {
public static readonly Type Void = typeof(void);
public static readonly Type String = typeof(string);
public static readonly Type Boolean = typeof(bool);
public static readonly Type Int32 = typeof(int);
public static readonly Type IntPtr = typeof(IntPtr);
public static readonly Type Double = typeof(double);
public static readonly Type Frame = typeof(Frame);
public static readonly Type Kernel = typeof(Kernel);
public static readonly Type Builtins = typeof(Builtins);
public static readonly Type SubInfo = typeof(SubInfo);
public static readonly Type IP6 = typeof(IP6);
public static readonly Type Variable = typeof(Variable);
public static readonly Type BValue = typeof(BValue);
public static readonly Type DynObject = typeof(DynObject);
public static readonly Type DynBlockDelegate = typeof(DynBlockDelegate);
public static readonly Type DynMetaObject = typeof(DynMetaObject);
public static readonly Type VarHash = typeof(Dictionary<string,Variable>);
public static readonly Type VVarList = typeof(VarDeque);
public static readonly Type FVarList = typeof(Variable[]);
public static readonly Type Cursor = typeof(Cursor);
public static readonly Type RxFrame = typeof(RxFrame);
public static readonly Type CC = typeof(CC);
public static readonly Type LAD = typeof(LAD);
public static readonly ConstructorInfo SubInfo_ctor =
SubInfo.GetConstructor(new Type[] {
String, typeof(int[]), typeof(DynBlockDelegate),
SubInfo, LAD, typeof(int[]), typeof(string[]),
Int32, typeof(string[]), typeof(int[]) });
public static readonly ConstructorInfo DynBlockDelegate_ctor =
typeof(DynBlockDelegate).GetConstructor(new Type[] {
typeof(object), typeof(IntPtr) });
public static readonly ConstructorInfo DynObject_ctor =
typeof(DynObject).GetConstructor(new Type[] {
DynMetaObject });
public static readonly ConstructorInfo DMO_ctor =
DynMetaObject.GetConstructor(new Type[] { String });
public static readonly ConstructorInfo RxFrame_ctor =
RxFrame.GetConstructor(new Type[] { String, Cursor, Boolean, Boolean });
public static readonly ConstructorInfo Frame_ctor =
Frame.GetConstructor(new Type[] { Frame, Frame, SubInfo });
public static readonly ConstructorInfo SV_ctor =
typeof(SimpleVariable).GetConstructor(new Type[] {
Boolean, Boolean, DynMetaObject, typeof(ViviHook), IP6 });
public static readonly ConstructorInfo SubViviHook_ctor =
typeof(SubViviHook).GetConstructor(new Type[] { IP6 });
public static readonly ConstructorInfo HashViviHook_ctor =
typeof(HashViviHook).GetConstructor(new Type[] { IP6, String });
public static readonly ConstructorInfo ArrayViviHook_ctor =
typeof(ArrayViviHook).GetConstructor(new Type[] { IP6, Int32 });
public static readonly ConstructorInfo NewHashViviHook_ctor =
typeof(NewHashViviHook).GetConstructor(new Type[] { Variable, String });
public static readonly ConstructorInfo NewArrayViviHook_ctor =
typeof(NewArrayViviHook).GetConstructor(new Type[] { Variable, Int32 });
public static readonly ConstructorInfo CC_ctor =
CC.GetConstructor(new Type[] { typeof(int[]) });
public static readonly Dictionary<string,ConstructorInfo> LADctors
= _LADctors();
private static Dictionary<string,ConstructorInfo> _LADctors() {
Dictionary<string,ConstructorInfo> n =
new Dictionary<string,ConstructorInfo>();
n["CC"] = typeof(LADCC).GetConstructor(new Type[] { CC });
n["Str"] = typeof(LADStr).GetConstructor(new Type[] { String });
n["Param"] = typeof(LADStr).GetConstructor(new Type[] { String });
n["Method"] = typeof(LADStr).GetConstructor(new Type[] { String });
n["ProtoRegex"] = typeof(LADStr).GetConstructor(new Type[] { String });
n["StrNoCase"] = typeof(LADStrNoCase).GetConstructor(new Type[] { String });
n["Imp"] = typeof(LADImp).GetConstructor(new Type[] { });
n["Dot"] = typeof(LADDot).GetConstructor(new Type[] { });
n["None"] = typeof(LADNone).GetConstructor(new Type[] { });
n["Null"] = typeof(LADNull).GetConstructor(new Type[] { });
n["Plus"] = typeof(LADPlus).GetConstructor(new Type[] { LAD });
n["Star"] = typeof(LADStar).GetConstructor(new Type[] { LAD });
n["Opt"] = typeof(LADOpt).GetConstructor(new Type[] { LAD });
n["Sequence"] = typeof(LADSequence).GetConstructor(new Type[] { typeof(LAD[]) });
n["Any"] = typeof(LADAny).GetConstructor(new Type[] { typeof(LAD[]) });
return n;
}
public static readonly MethodInfo IP6_InvokeMethod =
IP6.GetMethod("InvokeMethod");
public static readonly MethodInfo IP6_Invoke =
IP6.GetMethod("Invoke");
public static readonly MethodInfo IP6_SetSlot =
IP6.GetMethod("SetSlot");
public static readonly MethodInfo IP6_GetSlot =
IP6.GetMethod("GetSlot");
public static readonly MethodInfo Variable_Fetch =
Variable.GetMethod("Fetch");
public static readonly MethodInfo VVarList_Item =
VVarList.GetMethod("get_Item");
public static readonly MethodInfo VarHash_Remove =
VarHash.GetMethod("Remove");
public static readonly MethodInfo VarHash_get_Item =
VarHash.GetMethod("get_Item");
public static readonly MethodInfo VarHash_set_Item =
VarHash.GetMethod("set_Item");
public static readonly MethodInfo Kernel_MakeSub =
typeof(Kernel).GetMethod("MakeSub");
public static readonly MethodInfo Kernel_Die =
typeof(Kernel).GetMethod("Die");
public static readonly MethodInfo Kernel_SFH =
typeof(Kernel).GetMethod("SearchForHandler");
public static readonly MethodInfo Kernel_BootModule =
typeof(Kernel).GetMethod("BootModule");
public static readonly MethodInfo Kernel_RunLoop =
typeof(Kernel).GetMethod("RunLoop");
public static readonly MethodInfo Kernel_NewROScalar =
typeof(Kernel).GetMethod("NewROScalar");
public static readonly MethodInfo Kernel_NewRWListVar =
typeof(Kernel).GetMethod("NewRWListVar");
public static readonly MethodInfo Kernel_NewRWScalar =
typeof(Kernel).GetMethod("NewRWScalar");
public static readonly MethodInfo Kernel_NewBoundVar =
typeof(Kernel).GetMethod("NewBoundVar");
public static readonly MethodInfo Kernel_IterHasFlat =
typeof(Kernel).GetMethod("IterHasFlat");
public static readonly MethodInfo Kernel_ContextHelper =
typeof(Kernel).GetMethod("ContextHelper");
public static readonly MethodInfo Kernel_StatusHelper =
typeof(Kernel).GetMethod("StatusHelper");
public static readonly MethodInfo Kernel_SetStatus =
typeof(Kernel).GetMethod("SetStatus");
public static readonly MethodInfo Kernel_SortHelper =
typeof(Kernel).GetMethod("SortHelper");
public static readonly MethodInfo Kernel_GetVar =
typeof(Kernel).GetMethod("GetVar");
public static readonly MethodInfo Kernel_CreatePath =
typeof(Kernel).GetMethod("CreatePath");
public static readonly MethodInfo Kernel_AddPhaser =
typeof(Kernel).GetMethod("AddPhaser");
public static readonly MethodInfo Kernel_FirePhasers =
typeof(Kernel).GetMethod("FirePhasers");
public static readonly MethodInfo DMO_AddPrivateMethod =
typeof(DynMetaObject).GetMethod("AddPrivateMethod");
public static readonly MethodInfo DMO_AddMethod =
typeof(DynMetaObject).GetMethod("AddMethod");
public static readonly MethodInfo DMO_Invalidate =
typeof(DynMetaObject).GetMethod("Invalidate");
public static readonly MethodInfo DMO_FillParametricRole =
typeof(DynMetaObject).GetMethod("FillParametricRole");
public static readonly MethodInfo DMO_FillRole =
typeof(DynMetaObject).GetMethod("FillRole");
public static readonly MethodInfo DMO_FillClass =
typeof(DynMetaObject).GetMethod("FillClass");
public static readonly MethodInfo RxFrame_PushBacktrack =
typeof(RxFrame).GetMethod("PushBacktrack");
public static readonly MethodInfo RxFrame_PushCapture =
typeof(RxFrame).GetMethod("PushCapture");
public static readonly MethodInfo Console_WriteLine =
typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
public static readonly MethodInfo Console_Write =
typeof(Console).GetMethod("Write", new Type[] { typeof(string) });
public static readonly MethodInfo Environment_Exit =
typeof(Environment).GetMethod("Exit");
public static readonly MethodInfo StringBuilder_Append_String =
typeof(StringBuilder).GetMethod("Append", new Type[] { String });
public static readonly MethodInfo TW_WriteLine =
typeof(TextWriter).GetMethod("WriteLine", new Type[] { String });
public static readonly MethodInfo Console_get_Error =
typeof(Console).GetMethod("get_Error");
public static readonly MethodInfo Object_ToString =
typeof(object).GetMethod("ToString", new Type[0]);
public static readonly FieldInfo IP6_mo =
IP6.GetField("mo");
public static readonly FieldInfo BValue_v =
BValue.GetField("v");
public static readonly FieldInfo SubInfo_mo =
SubInfo.GetField("mo");
public static readonly FieldInfo SubInfo_sig_i =
SubInfo.GetField("sig_i");
public static readonly FieldInfo SubInfo_sig_r =
SubInfo.GetField("sig_r");
public static readonly FieldInfo DynObject_slots =
DynObject.GetField("slots");
public static readonly FieldInfo DMO_typeObject =
DynMetaObject.GetField("typeObject");
public static readonly FieldInfo DMO_how =
DynMetaObject.GetField("how");
public static readonly FieldInfo Kernel_NumMO =
Kernel.GetField("NumMO");
public static readonly FieldInfo Kernel_StrMO =
Kernel.GetField("StrMO");
public static readonly FieldInfo Kernel_AnyMO =
Kernel.GetField("AnyMO");
public static readonly FieldInfo Kernel_AnyP =
Kernel.GetField("AnyP");
public static readonly FieldInfo Frame_rx =
typeof(Frame).GetField("rx");
public static readonly FieldInfo Frame_ip =
typeof(Frame).GetField("ip");
public static readonly FieldInfo Frame_caller =
typeof(Frame).GetField("caller");
public static readonly FieldInfo Frame_outer =
typeof(Frame).GetField("outer");
public static readonly FieldInfo Frame_resultSlot =
typeof(Frame).GetField("resultSlot");
public static readonly FieldInfo Frame_lexn =
typeof(Frame).GetField("lexn");
public static readonly FieldInfo[] Frame_lexi32 = new FieldInfo[] {
typeof(Frame).GetField("lexi0"),
typeof(Frame).GetField("lexi1")
};
public static readonly FieldInfo[] Frame_lexobj = new FieldInfo[] {
typeof(Frame).GetField("lex0"),
typeof(Frame).GetField("lex1"),
typeof(Frame).GetField("lex2"),
typeof(Frame).GetField("lex3"),
typeof(Frame).GetField("lex4"),
typeof(Frame).GetField("lex5"),
typeof(Frame).GetField("lex6"),
typeof(Frame).GetField("lex7"),
typeof(Frame).GetField("lex8"),
typeof(Frame).GetField("lex9")
};
public const int NumInt32 = 2;
public const int NumInline = 10;
}
// This are expressional CLR operators. This is lower level than the
// CPS stuff; if HasCases is true, Returns must be void. Thus,
// there is no need to handle argument spills.
abstract class ClrOp {
public bool HasCases;
public bool Constant; // if this returns a value, can it be reordered?
public Type Returns;
public abstract void CodeGen(CgContext cx);
public virtual void ListCases(CgContext cx) { }
public virtual ClrOp Sink() {
throw (Returns == Tokens.Void)
? (Exception)new ArgumentException()
: new NotImplementedException();
}
protected static void TypeCheck(Type sub, Type super) { TypeCheck(sub,super,""); }
protected static void TypeCheck(Type sub, Type super, string msg) {
if (!super.IsAssignableFrom(sub))
throw new Exception(msg + " " + sub + " not subtype of " + super);
}
}
// NOT FOR GENERAL USE: only in implementing Sink for Clr*** with
// irreducable operations
class ClrSink : ClrOp {
public readonly ClrOp zyg;
public override void ListCases(CgContext cx) {
zyg.ListCases(cx);
}
public override void CodeGen(CgContext cx) {
zyg.CodeGen(cx);
cx.il.Emit(OpCodes.Pop);
}
public ClrSink(ClrOp zyg) {
if (zyg.Returns == Tokens.Void)
throw new ArgumentException();
this.zyg = zyg;
Returns = Tokens.Void;
}
}
class ClrMethodCall : ClrOp {
public readonly MethodInfo Method;