-
Notifications
You must be signed in to change notification settings - Fork 15
/
CLRBackend.cs
4738 lines (4289 loc) · 196 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 currently 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 = Utils.S2N(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 T[] A<T>(int cut, object x, Func<object, T> rdr) {
object[] arr = (object[]) x;
T[] r = new T[ arr.Length - cut ];
for (int i = 0; i < r.Length; i++)
r[i] = rdr(arr[i+cut]);
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 double N(object x) { return ((JScalar)x).num; }
public static int IN(object x) { return x == null ? -1 : (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(char[] 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 inputx) {
char[] input = inputx.ToCharArray();
int ilen = input.Length;
int start, write;
int ix = 0;
List<List<object>> containers = new List<List<object>>();
char i;
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' && ilen >= 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 == '"') {
ix++;
start = ix;
write = ix;
while (true) {
i = input[ix];
if (i == '\\') {
switch (input[ix+1]) {
case '/': i = '/'; break;
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;
input[write++] = i;
} else if (i == '"') {
break;
} else {
input[write++] = i;
ix++;
}
}
ix++;
containers[containers.Count - 1].Add(new JScalar(new string(input, start, write - start)));
continue;
}
start = ix;
while (true) {
i = input[ix];
if (i == ',' || i == '\r' || i == '\t' || i == '\n' ||
i == ' ' || i == ']')
break;
ix++;
}
containers[containers.Count - 1].Add(new JScalar(new string(input, start, ix - start)));
}
}
}
// 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 string filename;
public readonly double modtime;
public readonly object[] xref;
public readonly object[] tdeps;
public readonly Dictionary<string, Package> exp_pkg;
public readonly Dictionary<string, int> tdep_to_id;
public readonly List<Unit> id_to_tdep;
public Assembly clrAssembly;
public Type clrType;
bool depsBound;
public FieldInfo rtunit;
public List<byte> thaw_heap;
public Dictionary<string,int> existing_strings;
FieldInfo cc_pool;
Dictionary<string,int> cc_constant_cache = new Dictionary<string,int>();
List<int[]> cc_constants = new List<int[]>();
FieldInfo ccl_pool;
Dictionary<string,int> ccl_constant_cache = new Dictionary<string,int>();
List<int[][]> ccl_constants = new List<int[][]>();
FieldInfo sl_pool;
Dictionary<string,int> sl_constant_cache = new Dictionary<string,int>();
List<string[]> sl_constants = new List<string[]>();
FieldInfo var_pool;
Dictionary<string,int> var_constant_cache = new Dictionary<string,int>();
List<string> var_constants = new List<string>();
FieldInfo alt_info_pool;
List<object> alt_info_constants = new List<object>();
public Unit(object[] from, object[] code) {
mainline_ref = Xref.from(from[0]);
name = JScalar.S(from[1]);
log = from[2] as object[];
setting = JScalar.S(from[3]);
bottom_ref = Xref.from(from[4]);
filename = JScalar.S(from[5]);
modtime = from[6] == null ? 0 : JScalar.N(from[6]);
xref = from[7] as object[];
exp_pkg = new Dictionary<string,Package>();
tdep_to_id = new Dictionary<string,int>();
id_to_tdep = new List<Unit>();
thaw_heap = new List<byte>();
existing_strings = new Dictionary<string,int>();
for (int i = 0; i < xref.Length; i++) {
if (xref[i] == null) continue;
object[] xr = (object[]) xref[i];
if (JScalar.S(xr[0]) == "sub") {
xref[i] = new StaticSub(this, xr, (code != null &&
i < code.Length) ? (object[])code[i] : null);
} else {
Package p = Package.From(xr);
xref[i] = p;
p.own_xref = new Xref(name, i, p.name);
p.NoteExports(exp_pkg);
}
}
tdeps = from[8] as object[];
}
public void BindDepends(bool ismain) {
if (depsBound) return;
depsBound = true;
int i = 0;
foreach (object x in tdeps) {
string n = JScalar.S(((object[]) x)[0]);
tdep_to_id[n] = i++;
if (n == name) {
id_to_tdep.Add(this);
continue;
}
Unit o = CLRBackend.GetUnit(n);
id_to_tdep.Add(o);
o.BindDepends(false);
foreach (KeyValuePair<string,Package> kv in o.exp_pkg)
exp_pkg[kv.Key] = kv.Value;
}
if (ismain) return;
string dname = name.Replace("::",".");
clrAssembly = Assembly.LoadFile(Path.Combine(
CLRBackend.Current.dir, dname + ".dll"));
clrType = clrAssembly.GetType(dname);
Dictionary<string,FieldInfo> df =
new Dictionary<string,FieldInfo>();
foreach (FieldInfo fi in clrType.GetFields())
df[fi.Name] = fi;
BindFields(delegate(string fn, Type t) {
return df[fn];
});
}
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 = (bottom_ref ?? mainline_ref).Resolve<StaticSub>();
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) {
rtunit = binder("UNIT", Tokens.RuntimeUnit);
cc_pool = binder("CC", Tokens.CC.MakeArrayType());
alt_info_pool = binder("ALTINFO", typeof(AltInfo).MakeArrayType());
ccl_pool = binder("CCL", Tokens.CC.MakeArrayType().MakeArrayType());
var_pool = binder("UVAR", Tokens.Variable.MakeArrayType());
sl_pool = binder("STRLISTS", Tokens.String.MakeArrayType().MakeArrayType());
VisitSubsPostorder(delegate(int ix, StaticSub sub) {
sub.BindFields(ix, binder);
});
VisitPackages(delegate(int ix, Package pkg) {
pkg.BindFields(ix, binder);
});
}
public void EmitInt(int x) {
uint xp = (uint)x;
thaw_heap.Add((byte)xp); xp >>= 8;
thaw_heap.Add((byte)xp); xp >>= 8;
thaw_heap.Add((byte)xp); xp >>= 8;
thaw_heap.Add((byte)xp); xp >>= 8;
}
public void EmitXref(Xref x) {
if (x == null) {
EmitUShort(0xFFFF);
return;
}
EmitUShort(tdep_to_id[x.unit]);
EmitInt(x.index);
}
public void EmitByte(int x) {
if (x < 0 || x >= 256)
throw new ArgumentException();
thaw_heap.Add((byte)x);
}
public void EmitUShort(int x) {
if (x < 0 || x >= 65536)
throw new ArgumentException();
uint xp = (uint)x;
thaw_heap.Add((byte)xp); xp >>= 8;
thaw_heap.Add((byte)xp); xp >>= 8;
}
public void EmitStr(string s) {
if (s == null) { EmitUShort(0xFFFF); return; }
int l;
if (existing_strings.TryGetValue(s, out l)) {
if (l >= 0x3FFF) {
EmitInt(l * 4 + 1);
} else {
EmitUShort(l * 4 + 3);
}
} else {
existing_strings[s] = thaw_heap.Count;
bool wide = false;
foreach (char c in s) if (c > 0xFF) wide = true;
l = s.Length * 8;
if (wide) l+= 4;
if (l >= 0xFFF0) {
EmitInt(l);
} else {
EmitUShort(l + 2);
}
foreach(char c in s) {
if (wide) EmitUShort((int)c);
else EmitByte((int)c);
}
}
}
public void EmitIntArray(int[] s) {
if (s == null) { EmitInt(-1); return; }
EmitInt(s.Length);
foreach(int c in s) EmitInt(c);
}
public void EmitStrArray(string[] s) {
if (s == null) { EmitInt(-1); return; }
EmitInt(s.Length);
foreach(string c in s) EmitStr(c);
}
public void EmitLADArr(object lad) {
object[] lada = (object[]) lad;
EmitUShort(lada.Length);
foreach(object o in lada) EmitLAD(o);
}
public void EmitLAD(object lad) {
if (lad == null) {
EmitByte(0);
return;
}
object[] body = (object[]) lad;
string head = JScalar.S(body[0]);
if (!Tokens.LADcodes.ContainsKey(head))
throw new ArgumentException(head);
EmitByte(Tokens.LADcodes[head]);
if (head == "CC") { EmitIntArray(JScalar.IA(1, body)); }
else if (head == "Imp" || head == "Dot" || head == "Null" || head == "None" || head == "Dispatcher") { }
else if (head == "Str" || head == "StrNoCase" || head == "Param" || head == "Method") { EmitStr(JScalar.S(body[1])); }
else if (head == "Opt" || head == "Star" || head == "Plus") { EmitLAD(body[1]); }
else if (head == "Sequence" || head == "Any") { EmitLADArr(body[1]); }
else throw new NotImplementedException("ProcessLAD " + head);
}
void EmitBigInt(BigInteger x) {
uint[] w = x.GetWords();
int[] ws = new int[w.Length];
for (int i = 0; i < w.Length; i++) ws[i] = (int)w[i];
EmitByte((byte)x.Sign);
EmitIntArray(ws);
}
void EmitExactNum(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)) {
long val = BitConverter.DoubleToInt64Bits((double)num / (double)den);
EmitByte(1);
EmitInt((int)val);
EmitInt((int)(val >> 32));
return;
}
if (sden == 0) {
int snum;
if (num.AsInt32(out snum)) {
EmitByte(2);
EmitInt(snum);
return;
}
EmitByte(3);
EmitBigInt(num);
return;
}
EmitByte(4);
EmitBigInt(num);
EmitInt((int)sden);
EmitInt((int)(sden >> 32));
}
public CpsOp VarConst(string code) {
int ix;
if (!var_constant_cache.TryGetValue(code, out ix)) {
var_constant_cache[code] = ix = var_constants.Count;
var_constants.Add(code);
}
return CpsOp.IsConst(
CpsOp.Operator(Tokens.Variable, OpCodes.Ldelem_Ref,
CpsOp.GetSField(var_pool), CpsOp.IntLiteral(ix)));
}
public CpsOp VarConstStr(string s) { return VarConst('S' + s); }
public 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 VarConst(new string(c));
}
public CpsOp VarConstExact(int bas, string digs) {
return VarConst("X" + bas + ',' + digs);
}
public CpsOp EmitVarConsts() {
int b = thaw_heap.Count;
EmitInt(var_constants.Count);
foreach (string code in var_constants) {
if (code[0] == 'S') {
EmitByte(0);
EmitStr(code.Substring(1));
} else if (code[0] == 'N') {
EmitByte(1);
for (int j = 1; j <= 4; j++) EmitUShort(code[j]);
} else if (code[0] == 'X') {
int sep = code.IndexOf(',');
EmitExactNum(int.Parse(code.Substring(1,sep-1)), code.Substring(sep+1));
} else {
throw new ArgumentException("wtf? " + code);
}
}
return CpsOp.SetSField(var_pool,
CpsOp.MethodCall(Tokens.RuntimeUnit.GetMethod("LoadVariablePool"),
CpsOp.GetSField(rtunit), CpsOp.IntLiteral(b)));
}
public CpsOp CCConst(int[] cc) {
StringBuilder code = new StringBuilder();
foreach (int x in cc) {
code.Append((char)x);
code.Append((char)(x>>16));
}
string fcode = code.ToString();
int ix;
if (!cc_constant_cache.TryGetValue(fcode, out ix)) {
cc_constant_cache[fcode] = ix = cc_constants.Count;
cc_constants.Add(cc);
}
return CpsOp.IsConst(
CpsOp.Operator(Tokens.CC, OpCodes.Ldelem_Ref,
CpsOp.GetSField(cc_pool), CpsOp.IntLiteral(ix)));
}
public CpsOp EmitCCConsts() {
int b = thaw_heap.Count;
EmitInt(cc_constants.Count);
foreach (int[] cc in cc_constants)
EmitIntArray(cc);
return CpsOp.SetSField(cc_pool,
CpsOp.MethodCall(Tokens.RuntimeUnit.GetMethod("LoadCCPool"),
CpsOp.GetSField(rtunit), CpsOp.IntLiteral(b)));
}
public CpsOp StringListConst(string[] sl) {
StringBuilder code = new StringBuilder();
foreach (string s in sl) {
code.Append((char)(s.Length >> 16));
code.Append((char)(s.Length));
code.Append(s);
}
string fcode = code.ToString();
int ix;
if (!sl_constant_cache.TryGetValue(fcode, out ix)) {
sl_constant_cache[fcode] = ix = sl_constants.Count;
sl_constants.Add(sl);
}
return CpsOp.IsConst(CpsOp.Operator(Tokens.String.MakeArrayType(),
OpCodes.Ldelem_Ref, CpsOp.GetSField(sl_pool),
CpsOp.IntLiteral(ix)));
}
public CpsOp EmitStringListConsts() {
int b = thaw_heap.Count;
EmitInt(sl_constants.Count);
foreach (string[] sl in sl_constants) {
EmitStrArray(sl);
}
return CpsOp.SetSField(sl_pool,
CpsOp.MethodCall(Tokens.RuntimeUnit.GetMethod("LoadStrListPool"),
CpsOp.GetSField(rtunit), CpsOp.IntLiteral(b)));
}
public CpsOp CCListConst(int[][] ccl) {
StringBuilder code = new StringBuilder();
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));
}
}
string fcode = code.ToString();
int ix;
if (!ccl_constant_cache.TryGetValue(fcode, out ix)) {
ccl_constant_cache[fcode] = ix = ccl_constants.Count;
ccl_constants.Add(ccl);
}
return CpsOp.IsConst(CpsOp.Operator(Tokens.CC.MakeArrayType(), OpCodes.Ldelem_Ref,
CpsOp.GetSField(ccl_pool), CpsOp.IntLiteral(ix)));
}
public CpsOp EmitCCListConsts() {
int b = thaw_heap.Count;
EmitInt(ccl_constants.Count);
foreach (int[][] ccl in ccl_constants) {
EmitInt(ccl.Length);
foreach (int[] cc in ccl)
EmitIntArray(cc);
}
return CpsOp.SetSField(ccl_pool,
CpsOp.MethodCall(Tokens.RuntimeUnit.GetMethod("LoadCCListPool"),
CpsOp.GetSField(rtunit), CpsOp.IntLiteral(b)));
}
public CpsOp AltInfoConst(CgContext cx, object lads, string dba, string[] labels) {
int ix = alt_info_constants.Count / 4;
alt_info_constants.Add(cx);
alt_info_constants.Add(lads);
alt_info_constants.Add(dba);
alt_info_constants.Add(labels);
return CpsOp.IsConst(CpsOp.Operator(typeof(AltInfo), OpCodes.Ldelem_Ref,
CpsOp.GetSField(alt_info_pool), CpsOp.IntLiteral(ix)));
}
public CpsOp EmitAltInfoConsts() {
int b = thaw_heap.Count;
EmitInt(alt_info_constants.Count / 4);
for (int i = 0; i < alt_info_constants.Count; i += 4) {
CgContext cx = (CgContext) alt_info_constants[i];
object lads = alt_info_constants[i+1];
string dba = (string) alt_info_constants[i+2];
string[] labels = (string[]) alt_info_constants[i+3];
EmitLADArr(lads);
EmitStr(dba);
int[] lids = new int[labels.Length];
for (int j = 0; j < labels.Length; j++)
lids[j] = cx.named_cases[labels[j]];
EmitIntArray(lids);
}
return CpsOp.SetSField(alt_info_pool,
CpsOp.MethodCall(Tokens.RuntimeUnit.GetMethod("LoadAltInfoPool"),
CpsOp.GetSField(rtunit), CpsOp.IntLiteral(b)));
}
}
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 as object[]);
}
public Xref(string unit, int index, string name) {
this.unit = unit; this.index = index; this.name = name;
}
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 T Resolve<T>() { return (T) CLRBackend.Resolve(this); }
}
class Package {
public Xref own_xref;
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 metaObject;
public override void BindFields(int ix,
Func<string,Type,FieldInfo> binder) {
metaObject = binder(Unit.SharedName('M', ix, name), Tokens.STable);
}
public ModuleWithTypeObject(object[] p) : base(p) { }
}
class Method {
public readonly string name;
public readonly object cname;
public readonly int kind;
public readonly string var;
public readonly Xref body;
public Method(object[] x) {
if (x[0] is JScalar) {
name = JScalar.S(x[0]);
} else {
cname = x[0];
}
kind = JScalar.I(x[1]);
var = JScalar.S(x[2]);
body = Xref.from(x[3]);
}
public static Method[] fromArray(object x) {
return JScalar.A<Method>(0, x, delegate (object o) {
return new Method(o as object[]); });
}
}
class Attribute {
public readonly string name;
public readonly char sigil;
public readonly bool publ;
public readonly string ivar;
public readonly Xref ibody;
public readonly Xref type;
public Attribute(object[] x) {
name = JScalar.S(x[0]);
sigil = JScalar.S(x[1])[0];
publ = JScalar.B(x[2]);
ivar = JScalar.S(x[3]);
ibody = Xref.from(x[4]);
type = Xref.from(x[5]);
}
public static Attribute[] fromArray(object x) {
return JScalar.A<Attribute>(0, x, delegate (object o) {
return new Attribute(o as object[]); });
}
}
class Class: ModuleWithTypeObject {
public readonly Attribute[] attributes;
public readonly Method[] methods;
public readonly Xref[] superclasses;
public readonly Xref[] linearized_mro;
public Class(object[] p) : base(p) {
attributes = Attribute.fromArray(p[3]);
methods = Method.fromArray(p[4]);
superclasses = JScalar.A<Xref>(0, p[5], Xref.from);
linearized_mro = JScalar.A<Xref>(0, p[6], Xref.from);
}
}
class Grammar: Class {
public Grammar(object[] p) : base(p) { }
}
class Role: ModuleWithTypeObject {
public readonly Attribute[] attributes;
public readonly Method[] methods;
public readonly Xref[] superclasses;
public Role(object[] p) : base(p) {
attributes = Attribute.fromArray(p[3]);
methods = Method.fromArray(p[4]);
superclasses = JScalar.A<Xref>(0, p[5], Xref.from);
}
}
class ParametricRole: ModuleWithTypeObject {
public readonly Attribute[] attributes;
public readonly Method[] methods;
public readonly Xref[] superclasses;
public ParametricRole(object[] p) : base(p) {
attributes = Attribute.fromArray(p[3]);
methods = Method.fromArray(p[4]);
superclasses = JScalar.A<Xref>(0, p[5], Xref.from);
}
}
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 const int UNSAFE = 128;
public readonly string name;
public readonly Unit unit;
public readonly Xref outer;
public readonly int flags;
public readonly int[] zyg;
public readonly Xref parametric_role_hack;
public readonly object augment_hack;
public readonly object[] hint_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 subinfo;
public FieldInfo protopad;
public int nlexn;
public StaticSub(Unit unit, object[] s, object[] c) {
this.unit = unit;
name = JScalar.S(s[1]);
outer = Xref.from(s[2]);
flags = JScalar.I(s[3]);
zyg = JScalar.IA(0, s[4]);
sclass = JScalar.S(s[5]);
ltm = s[6];
exports = (object[]) s[7];
sig = s[8];
object[] r_lexicals = s[9] as object[];
if (c != null) {
parametric_role_hack = Xref.from(c[1]);
augment_hack = c[2];
hint_hack = c[3] as object[];
is_phaser = JScalar.IN(c[4]);
body_of = Xref.from(c[5]);
in_class = Xref.from(c[6]);
cur_pkg = JScalar.SA(0, c[7]);
if (c[8] != null) r_lexicals = c[8] as object[];
body = c[9];
}
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 == "hint") {
obj = new LexHint(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 if (type == "label") {
obj = new LexLabel(bl);
} else if (type == "dispatch") {
obj = new LexDispatch(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 == "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);
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 != "CORE")
csr = csr.outer.Resolve<StaticSub>();
while (!csr.l_lexicals.ContainsKey(name))
csr = csr.outer.Resolve<StaticSub>();
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);
}