/
Compiler.cs
1943 lines (1626 loc) · 76.1 KB
/
Compiler.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
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/**
* Author: David Miller
**/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using System.Threading;
using clojure.lang.CljCompiler.Ast;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
namespace clojure.lang
{
public static class Compiler
{
#region other constants
internal const int MaxPositionalArity = 20;
internal const string CompileStubPrefix = "compile__stub";
#endregion
#region Symbols
public static readonly Symbol DefSym = Symbol.intern("def");
public static readonly Symbol LoopSym = Symbol.intern("loop*");
public static readonly Symbol RecurSym = Symbol.intern("recur");
public static readonly Symbol IfSym = Symbol.intern("if");
public static readonly Symbol LetSym = Symbol.intern("let*");
public static readonly Symbol LetfnSym = Symbol.intern("letfn*");
public static readonly Symbol DoSym = Symbol.intern("do");
public static readonly Symbol FnSym = Symbol.intern("fn*");
public static readonly Symbol FnOnceSym = (Symbol) Symbol.intern("fn*").withMeta(RT.map(Keyword.intern(null, "once"), true));
public static readonly Symbol QuoteSym = Symbol.intern("quote");
public static readonly Symbol TheVarSym = Symbol.intern("var");
public static readonly Symbol DotSym = Symbol.intern(".");
public static readonly Symbol AssignSym = Symbol.intern("set!");
public static readonly Symbol TrySym = Symbol.intern("try");
public static readonly Symbol CatchSym = Symbol.intern("catch");
public static readonly Symbol FinallySym = Symbol.intern("finally");
public static readonly Symbol ThrowSym = Symbol.intern("throw");
public static readonly Symbol MonitorEnterSym = Symbol.intern("monitor-enter");
public static readonly Symbol MonitorExitSym = Symbol.intern("monitor-exit");
public static readonly Symbol ImportSym = Symbol.intern("clojure.core","import*");
public static readonly Symbol DeftypeSym = Symbol.intern("deftype*");
public static readonly Symbol CaseSym = Symbol.intern("case*");
public static readonly Symbol NewSym = Symbol.intern("new");
public static readonly Symbol ThisSym = Symbol.intern("this");
public static readonly Symbol ReifySym = Symbol.intern("reify*");
public static readonly Symbol AmpersandSym = Symbol.intern("&");
public static readonly Symbol IdentitySym = Symbol.intern("clojure.core", "identity");
static readonly Symbol NsSym = Symbol.intern("ns");
static readonly Symbol InNsSym = Symbol.intern("in-ns");
internal static readonly Symbol ISeqSym = Symbol.intern("clojure.lang.ISeq");
internal static readonly Symbol ClassSym = Symbol.intern("System.Type");
//internal static readonly Symbol InvokeStaticSym = Symbol.intern("invokeStatic");
#endregion
#region Keywords
static readonly Keyword InlineKeyword = Keyword.intern(null, "inline");
static readonly Keyword InlineAritiesKeyword = Keyword.intern(null, "inline-arities");
//internal static readonly Keyword StaticKeyword = Keyword.intern(null, "static");
internal static readonly Keyword ArglistsKeyword = Keyword.intern(null, "arglists");
//static readonly Keyword VolatileKeyword = Keyword.intern(null,"volatile");
internal static readonly Keyword ImplementsKeyword = Keyword.intern(null,"implements");
internal static readonly Keyword ProtocolKeyword = Keyword.intern(null,"protocol");
//static readonly Keyword OnKeyword = Keyword.intern(null, "on");
internal static readonly Keyword DynamicKeyword = Keyword.intern("dynamic");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal static readonly Keyword DisableLocalsClearingKeyword = Keyword.intern("disable-locals-clearing");
internal static readonly Keyword ElideMetaKeyword = Keyword.intern("elide-meta");
#endregion
#region Vars
//boolean
internal static readonly Var CompileFilesVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("*compile-files*"), false).setDynamic();
internal static readonly Var InstanceVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("instance?"), false).setDynamic();
//String
public static readonly Var CompilePathVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("*compile-path*"), null).setDynamic();
public static readonly Var CompileVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("compile"));
// String
internal static readonly Var SourceVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("*source-path*"), "NO_SOURCE_FILE").setDynamic();
// String
internal static readonly Var SourcePathVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("*file*"), "NO_SOURCE_PATH").setDynamic();
//Integer
internal static readonly Var LineVar = Var.create(0).setDynamic(); // From the JVM version
internal static readonly Var ColumnVar = Var.create(0).setDynamic(); // From the JVM version
//internal static readonly Var LINE_BEFORE = Var.create(0).setDynamic(); // From the JVM version
//internal static readonly Var COLUMN_BEFORE = Var.create(0).setDynamic(); // From the JVM version
//internal static readonly Var LINE_AFTER = Var.create(0).setDynamic(); // From the JVM version
//internal static readonly Var COLUMN_AFTER = Var.create(0).setDynamic(); // From the JVM version
internal static readonly Var SourceSpanVar = Var.create(null).setDynamic(); // Mine
internal static readonly Var MethodVar = Var.create(null).setDynamic();
public static readonly Var LocalEnvVar = Var.create(PersistentHashMap.EMPTY).setDynamic();
//Integer
internal static readonly Var NextLocalNumVar = Var.create(0).setDynamic();
internal static readonly Var LoopLocalsVar = Var.create(null).setDynamic();
// Label
internal static readonly Var LoopLabelVar = Var.create().setDynamic();
internal static readonly Var InCatchFinallyVar = Var.create(null).setDynamic(); //null or not
internal static readonly Var NoRecurVar = Var.create(null).setDynamic();
internal static readonly Var VarsVar = Var.create().setDynamic(); //var->constid
internal static readonly Var ConstantsVar = Var.create().setDynamic(); //vector<object>
internal static readonly Var ConstantIdsVar = Var.create().setDynamic(); // IdentityHashMap
internal static readonly Var KeywordsVar = Var.create().setDynamic(); //keyword->constid
internal static readonly Var KeywordCallsitesVar = Var.create().setDynamic(); // vector<keyword>
internal static readonly Var ProtocolCallsitesVar = Var.create().setDynamic(); // vector<var>
internal static readonly Var VarCallsitesVar = Var.create().setDynamic(); // set<var>
internal static readonly Var CompileStubSymVar = Var.create(null).setDynamic();
internal static readonly Var CompileStubClassVar = Var.create(null).setDynamic();
internal static readonly Var CompileStubOrigClassVar = Var.create(null).setDynamic();
internal static readonly Var CompilerContextVar = Var.create(null).setDynamic();
internal static readonly Var CompilerActiveVar = Var.create(false).setDynamic();
public static readonly Var CompilerOptionsVar = Var.intern(Namespace.findOrCreate(Symbol.intern("clojure.core")),
Symbol.intern("*compiler-options*"), null).setDynamic();
public static object GetCompilerOption(Keyword k)
{
return RT.get(CompilerOptionsVar.deref(), k);
}
public static object ElideMeta(object m)
{
ICollection<Object> elides = (ICollection<Object>)GetCompilerOption(ElideMetaKeyword);
if (elides != null)
{
foreach (object k in elides)
m = RT.dissoc(m, k);
}
return m;
}
#endregion
#region Special forms
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "specials")]
public static readonly IPersistentMap specials = PersistentHashMap.create(
DefSym, new DefExpr.Parser(),
LoopSym, new LetExpr.Parser(),
RecurSym, new RecurExpr.Parser(),
IfSym, new IfExpr.Parser(),
CaseSym, new CaseExpr.Parser(),
LetSym, new LetExpr.Parser(),
LetfnSym, new LetFnExpr.Parser(),
DoSym, new BodyExpr.Parser(),
FnSym, null,
QuoteSym, new ConstantExpr.Parser(),
TheVarSym, new TheVarExpr.Parser(),
ImportSym, new ImportExpr.Parser(),
DotSym, new HostExpr.Parser(),
AssignSym, new AssignExpr.Parser(),
DeftypeSym, new NewInstanceExpr.DefTypeParser(),
ReifySym, new NewInstanceExpr.ReifyParser(),
TrySym, new TryExpr.Parser(),
ThrowSym, new ThrowExpr.Parser(),
MonitorEnterSym, new MonitorEnterExpr.Parser(),
MonitorExitSym, new MonitorExitExpr.Parser(),
CatchSym, null,
FinallySym, null,
NewSym, new NewExpr.Parser(),
AmpersandSym, null
);
public static bool IsSpecial(Object sym)
{
return specials.containsKey(sym);
}
static IParser GetSpecialFormParser(object op)
{
return (IParser)specials.valAt(op);
}
#endregion
#region MethodInfos, etc.
internal static readonly PropertyInfo Method_Compiler_CurrentNamespace = typeof(Compiler).GetProperty("CurrentNamespace");
internal static readonly MethodInfo Method_Compiler_PushNS = typeof(Compiler).GetMethod("PushNS");
internal static readonly MethodInfo Method_ILookupSite_fault = typeof(ILookupSite).GetMethod("fault");
internal static readonly MethodInfo Method_ILookupThunk_get = typeof(ILookupThunk).GetMethod("get");
internal static readonly MethodInfo Method_IPersistentMap_valAt2 = typeof(ILookup).GetMethod("valAt", new Type[] { typeof(object), typeof(object) });
internal static readonly MethodInfo Method_IPersistentMap_without = typeof(IPersistentMap).GetMethod("without");
internal static readonly MethodInfo Method_IObj_withMeta = typeof(IObj).GetMethod("withMeta");
internal static readonly MethodInfo Method_Keyword_intern_string = typeof(Keyword).GetMethod("intern", new Type[] { typeof(String) });
internal static readonly MethodInfo Method_Monitor_Enter = typeof(Monitor).GetMethod("Enter", new Type[] { typeof(Object) });
internal static readonly MethodInfo Method_Monitor_Exit = typeof(Monitor).GetMethod("Exit", new Type[] { typeof(Object) });
internal static readonly MethodInfo Method_Namespace_importClass1 = typeof(Namespace).GetMethod("importClass", new Type[] { typeof(Type) });
internal static readonly MethodInfo Method_PersistentList_create = typeof(PersistentList).GetMethod("create", new Type[] { typeof(System.Collections.IList) });
internal static readonly MethodInfo Method_PersistentHashSet_create = typeof(PersistentHashSet).GetMethod("create", new Type[] { typeof(Object[]) });
internal static readonly FieldInfo Method_PersistentHashSet_EMPTY = typeof(PersistentHashSet).GetField("EMPTY");
internal static readonly MethodInfo Method_Reflector_GetInstanceFieldOrProperty = typeof(Reflector).GetMethod("GetInstanceFieldOrProperty");
internal static readonly MethodInfo Method_Reflector_SetInstanceFieldOrProperty = typeof(Reflector).GetMethod("SetInstanceFieldOrProperty");
internal static readonly MethodInfo Method_RT_classForName = typeof(RT).GetMethod("classForName");
internal static readonly MethodInfo Method_RT_intCast_long = typeof(RT).GetMethod("intCast", new Type[] { typeof(long) });
internal static readonly MethodInfo Method_RT_uncheckedIntCast_long = typeof(RT).GetMethod("uncheckedIntCast", new Type[] { typeof(long) });
internal static readonly MethodInfo Method_RT_keyword = typeof(RT).GetMethod("keyword");
internal static readonly MethodInfo Method_RT_map = typeof(RT).GetMethod("map");
internal static readonly MethodInfo Method_RT_mapUniqueKeys = typeof(RT).GetMethod("mapUniqueKeys");
internal static readonly MethodInfo Method_RT_seqOrElse = typeof(RT).GetMethod("seqOrElse");
internal static readonly MethodInfo Method_RT_set = typeof(RT).GetMethod("set");
internal static readonly MethodInfo Method_RT_vector = typeof(RT).GetMethod("vector");
internal static readonly MethodInfo Method_RT_readString = typeof(RT).GetMethod("readString");
internal static readonly MethodInfo Method_RT_var2 = typeof(RT).GetMethod("var", new Type[] { typeof(string), typeof(string) });
internal static readonly MethodInfo Method_Symbol_intern2 = typeof(Symbol).GetMethod("intern", new Type[] { typeof(string), typeof(string) });
internal static readonly MethodInfo Method_Type_GetTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle");
internal static readonly MethodInfo Method_Util_classOf = typeof(Util).GetMethod("classOf");
internal static readonly MethodInfo Method_Util_ConvertToInt = typeof(Util).GetMethod("ConvertToInt");
internal static readonly MethodInfo Method_Util_equiv = typeof(Util).GetMethod("equiv", new Type[] { typeof(object), typeof(object) });
internal static readonly MethodInfo Method_Util_hash = typeof(Util).GetMethod("hash");
internal static readonly MethodInfo Method_Util_IsNonCharNumeric = typeof(Util).GetMethod("IsNonCharNumeric");
internal static readonly MethodInfo Method_Var_bindRoot = typeof(Var).GetMethod("bindRoot");
internal static readonly MethodInfo Method_Var_get = typeof(Var).GetMethod("deref");
internal static readonly MethodInfo Method_Var_set = typeof(Var).GetMethod("set");
internal static readonly MethodInfo Method_Var_setMeta = typeof(Var).GetMethod("setMeta");
internal static readonly MethodInfo Method_Var_popThreadBindings = typeof(Var).GetMethod("popThreadBindings");
internal static readonly MethodInfo Method_Var_getRawRoot = typeof(Var).GetMethod("getRawRoot");
internal static readonly MethodInfo Method_Var_setDynamic0 = typeof(Var).GetMethod("setDynamic", Type.EmptyTypes);
internal static readonly ConstructorInfo Ctor_KeywordLookupSite_1 = typeof(KeywordLookupSite).GetConstructor(new Type[] { typeof(Keyword) });
internal static readonly ConstructorInfo Ctor_Regex_1 = typeof(Regex).GetConstructor(new Type[] { typeof(String) });
internal static readonly ConstructorInfo Ctor_Serializable = typeof(SerializableAttribute).GetConstructor(Type.EmptyTypes);
internal static readonly MethodInfo[] Methods_IFn_invoke = new MethodInfo[MaxPositionalArity + 2];
internal static Type[] CreateObjectTypeArray(int size)
{
Type[] typeArray = new Type[size];
for (int i = 0; i < size; i++)
typeArray[i] = typeof(Object);
return typeArray;
}
#endregion
#region C-tors & factory methods
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static Compiler()
{
for (int i = 0; i <= Compiler.MaxPositionalArity; i++)
Methods_IFn_invoke[i] = typeof(IFn).GetMethod("invoke", CreateObjectTypeArray(i));
Type[] types = new Type[Compiler.MaxPositionalArity + 1];
CreateObjectTypeArray(Compiler.MaxPositionalArity).CopyTo(types, 0);
types[Compiler.MaxPositionalArity] = typeof(object[]);
Methods_IFn_invoke[Compiler.MaxPositionalArity + 1]
= typeof(IFn).GetMethod("invoke", types);
}
#endregion
#region Symbol/namespace resolving
// TODO: we have duplicate code below.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resolve")]
public static Symbol resolveSymbol(Symbol sym)
{
//already qualified or classname?
if (sym.Name.IndexOf('.') > 0)
return sym;
if (sym.Namespace != null)
{
Namespace ns = namespaceFor(sym);
if (ns == null || ns.Name.Name == sym.Namespace)
return sym;
return Symbol.intern(ns.Name.Name, sym.Name);
}
Object o = CurrentNamespace.GetMapping(sym);
if (o == null)
return Symbol.intern(CurrentNamespace.Name.Name, sym.Name);
Type ot = o as Type;
if (ot != null)
return Symbol.intern(null, Util.NameForType(ot));
Var ov = o as Var;
if (ov != null)
return Symbol.intern(ov.Namespace.Name.Name, ov.Symbol.Name);
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "namespace")]
public static Namespace namespaceFor(Symbol sym)
{
return namespaceFor(CurrentNamespace, sym);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "namespace")]
public static Namespace namespaceFor(Namespace inns, Symbol sym)
{
//note, presumes non-nil sym.ns
// first check against currentNS' aliases...
Symbol nsSym = Symbol.intern(sym.Namespace);
Namespace ns = inns.LookupAlias(nsSym);
if (ns == null)
{
// ...otherwise check the Namespaces map.
ns = Namespace.find(nsSym);
}
return ns;
}
public static Namespace CurrentNamespace
{
get { return (Namespace)RT.CurrentNSVar.deref(); }
}
public static string DestubClassName(String className)
{
//skip over prefix + '.' or '/'
if (className.StartsWith(CompileStubPrefix))
return className.Substring(CompileStubPrefix.Length + 1);
return className;
}
public static object Resolve(Symbol symbol, bool allowPrivate)
{
return ResolveIn(CurrentNamespace, symbol, allowPrivate);
}
public static object Resolve(Symbol symbol)
{
return ResolveIn(CurrentNamespace, symbol, false);
}
private static object ResolveIn(Namespace n, Symbol symbol, bool allowPrivate)
{
// note: ns-qualified vars must already exist
if (symbol.Namespace != null)
{
Namespace ns = namespaceFor(n, symbol);
if (ns == null)
throw new InvalidOperationException("No such namespace: " + symbol.Namespace);
Var v = ns.FindInternedVar(Symbol.intern(symbol.Name));
if (v == null)
throw new InvalidOperationException("No such var: " + symbol);
else if (v.Namespace != CurrentNamespace && !v.isPublic && !allowPrivate)
throw new InvalidOperationException(string.Format("var: {0} is not public", symbol));
return v;
}
else if (symbol.Name.IndexOf('.') > 0 || symbol.Name[symbol.Name.Length - 1] == ']')
return RT.classForName(symbol.Name);
else if (symbol.Equals(NsSym))
return RT.NSVar;
else if (symbol.Equals(InNsSym))
return RT.InNSVar;
else
{
if (Util.equals(symbol, CompileStubSymVar.get()))
return CompileStubClassVar.get();
object o = n.GetMapping(symbol);
if (o == null)
{
if (RT.booleanCast(RT.AllowUnresolvedVarsVar.deref()))
return symbol;
else
throw new InvalidOperationException(string.Format("Unable to resolve symbol: {0} in this context", symbol));
}
return o;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "maybe")]
public static object maybeResolveIn(Namespace n, Symbol symbol)
{
// note: ns-qualified vars must already exist
if (symbol.Namespace != null)
{
Namespace ns = namespaceFor(n, symbol);
if (ns == null)
return null;
Var v = ns.FindInternedVar(Symbol.intern(symbol.Name));
if (v == null)
return null;
return v;
}
else if (symbol.Name.IndexOf('.') > 0 && !symbol.Name.EndsWith(".")
|| symbol.Name[symbol.Name.Length - 1] == ']') /// JAVA: symbol.Name[0] == '[')
return RT.classForName(symbol.Name);
else if (symbol.Equals(NsSym))
return RT.NSVar;
else if (symbol.Equals(InNsSym))
return RT.InNSVar;
else
{
object o = n.GetMapping(symbol);
return o;
}
}
#endregion
#region Bindings, registration
private static void RegisterVar(Var v)
{
if (!VarsVar.isBound)
return;
IPersistentMap varsMap = (IPersistentMap)VarsVar.deref();
Object id = RT.get(varsMap, v);
if (id == null)
{
VarsVar.set(RT.assoc(varsMap, v, RegisterConstant(v)));
}
}
internal static Var LookupVar(Symbol sym, bool internNew, Boolean registerMacro)
{
Var var = null;
// Note: ns-qualified vars in other namespaces must exist already
if (sym.Namespace != null)
{
Namespace ns = Compiler.namespaceFor(sym);
if (ns == null)
return null;
Symbol name = Symbol.intern(sym.Name);
if (internNew && ns == CurrentNamespace)
var = CurrentNamespace.intern(name);
else
var = ns.FindInternedVar(name);
}
else if (sym.Equals(NsSym))
var = RT.NSVar;
else if (sym.Equals(InNsSym))
var = RT.InNSVar;
else
{
// is it mapped?
Object o = CurrentNamespace.GetMapping(sym);
if (o == null)
{
// introduce a new var in the current ns
if (internNew)
var = CurrentNamespace.intern(Symbol.intern(sym.Name));
}
else
{
var = o as Var;
if (var == null)
throw new InvalidOperationException(string.Format("Expecting var, but {0} is mapped to {1}", sym, o));
}
}
if (var != null && (!var.IsMacro || registerMacro))
RegisterVar(var);
return var;
}
internal static Var LookupVar(Symbol sym, bool internNew)
{
return LookupVar(sym, internNew, true);
}
internal static int RegisterConstant(Object o)
{
if (!ConstantsVar.isBound)
return -1;
PersistentVector v = (PersistentVector)ConstantsVar.deref();
IdentityHashMap ids = (IdentityHashMap)ConstantIdsVar.deref();
int i;
if (ids.TryGetValue(o, out i))
return i;
ConstantsVar.set(RT.conj(v, o));
ids[o] = v.count();
return v.count();
}
internal static KeywordExpr RegisterKeyword(Keyword keyword)
{
if (!KeywordsVar.isBound)
return new KeywordExpr(keyword);
IPersistentMap keywordsMap = (IPersistentMap)KeywordsVar.deref();
object id = RT.get(keywordsMap, keyword);
if (id == null)
KeywordsVar.set(RT.assoc(keywordsMap, keyword, RegisterConstant(keyword)));
return new KeywordExpr(keyword);
}
internal static int RegisterKeywordCallsite(Keyword keyword)
{
if (!KeywordCallsitesVar.isBound)
throw new InvalidOperationException("KEYWORD_CALLSITES is not bound");
IPersistentVector keywordCallsites = (IPersistentVector)KeywordCallsitesVar.deref();
keywordCallsites = keywordCallsites.cons(keyword);
KeywordCallsitesVar.set(keywordCallsites);
return keywordCallsites.count() - 1;
}
internal static int RegisterProtocolCallsite(Var v)
{
if (!ProtocolCallsitesVar.isBound)
throw new InvalidOperationException("PROTOCOL_CALLSITES is not bound");
IPersistentVector protocolCallsites = (IPersistentVector)ProtocolCallsitesVar.deref();
protocolCallsites = protocolCallsites.cons(v);
ProtocolCallsitesVar.set(protocolCallsites);
return protocolCallsites.count() - 1;
}
internal static void RegisterVarCallsite(Var v)
{
if (!VarCallsitesVar.isBound)
throw new InvalidOperationException("VAR_CALLSITES is not bound");
IPersistentCollection varCallsites = (IPersistentCollection)VarCallsitesVar.deref();
varCallsites = varCallsites.cons(v);
VarCallsitesVar.set(varCallsites);
//return varCallsites.count() - 1;
}
internal static IPersistentCollection EmptyVarCallSites()
{
return PersistentHashSet.EMPTY;
}
internal static LocalBinding RegisterLocalThis(Symbol sym, Symbol tag, Expr init)
{
return RegisterLocalInternal(sym, tag, init, true, false, false);
}
internal static LocalBinding RegisterLocal(Symbol sym, Symbol tag, Expr init, bool isArg)
{
return RegisterLocalInternal(sym, tag, init, false, isArg, false);
}
internal static LocalBinding RegisterLocal(Symbol sym, Symbol tag, Expr init, bool isArg, bool isByRef)
{
return RegisterLocalInternal(sym,tag,init,false,isArg,isByRef);
}
private static LocalBinding RegisterLocalInternal(Symbol sym, Symbol tag, Expr init, bool isThis, bool isArg, bool isByRef)
{
int num = GetAndIncLocalNum();
LocalBinding b = new LocalBinding(num, sym, tag, init, isThis, isArg, isByRef);
IPersistentMap localsMap = (IPersistentMap)LocalEnvVar.deref();
LocalEnvVar.set(RT.assoc(localsMap, b.Symbol, b));
ObjMethod method = (ObjMethod)MethodVar.deref();
method.Locals = (IPersistentMap)RT.assoc(method.Locals, b, b);
method.IndexLocals = (IPersistentMap)RT.assoc(method.IndexLocals, num, b);
return b;
}
internal static int GetAndIncLocalNum()
{
int num = (int)NextLocalNumVar.deref();
ObjMethod m = (ObjMethod)MethodVar.deref();
if (num > m.MaxLocal)
m.MaxLocal = num;
NextLocalNumVar.set(num + 1);
return num;
}
internal static LocalBinding ReferenceLocal(Symbol symbol)
{
if (!LocalEnvVar.isBound)
return null;
LocalBinding b = (LocalBinding)RT.get(LocalEnvVar.deref(), symbol);
if (b != null)
{
ObjMethod method = (ObjMethod)MethodVar.deref();
CloseOver(b, method);
}
return b;
}
static void CloseOver(LocalBinding b, ObjMethod method)
{
if (b != null && method != null)
{
if (RT.get(method.Locals, b) == null)
{
method.Objx.Closes = (IPersistentMap)RT.assoc(method.Objx.Closes, b, b);
CloseOver(b, method.Parent);
}
else if (InCatchFinallyVar.deref() != null)
{
method.LocalsUsedInCatchFinally = (PersistentHashSet)method.LocalsUsedInCatchFinally.cons(b.Index);
}
}
}
#endregion
#region other type hacking
internal static Type MaybePrimitiveType(Expr e)
{
MaybePrimitiveExpr mpe = e as MaybePrimitiveExpr;
if (mpe != null && mpe.HasClrType && mpe.CanEmitPrimitive)
{
Type t = e.ClrType;
if (Util.IsPrimitive(t))
return t;
}
return null;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static Type MaybeClrType(ICollection<Expr> exprs)
{
Type match = null;
try
{
foreach (Expr e in exprs)
{
if (e is ThrowExpr)
continue;
if (!e.HasClrType)
return null;
Type t = e.ClrType;
if (match == null)
match = t;
else if (match != t)
return null;
}
}
catch (Exception)
{
return null;
}
return match;
}
public static Type PrimType(Symbol sym)
{
if (sym == null)
return null;
Type t = null;
switch (sym.Name)
{
case "int":
case "Int32":
case "System.Int32":
t = typeof(int); break;
case "long":
case "Int64":
case "System.Int64":
t = typeof(long); break;
case "float":
case "Single":
case "System.Single":
t = typeof(float); break;
case "double":
case "Double":
case "System.Double":
t = typeof(double); break;
case "char":
case "Char":
case "System.Char":
t = typeof(char); break;
case "short":
case "Int16":
case "System.Int16":
t = typeof(short); break;
case "byte":
case "Byte":
case "System.Byte":
t = typeof(byte); break;
case "bool":
case "boolean":
case "Boolean":
case "System.Boolean":
t = typeof(bool); break;
case "void": t = typeof(void); break;
case "uint":
case "UInt32":
case "System.UInt32":
t = typeof(uint); break;
case "ulong":
case "UInt64":
case "System.UInt64":
t = typeof(ulong); break;
case "ushort":
case "UInt16":
case "System.UInt16":
t = typeof(ushort); break;
case "sbyte":
case "SByte":
case "System.SByte":
t = typeof(sbyte); break;
}
return t;
}
public static Type PrimType(Type t)
{
return t.IsPrimitive ? t : typeof(object);
}
internal static Type TagType(Object tag)
{
if (tag == null)
return typeof(object);
Type t = null;
{
Symbol tagAsSym = tag as Symbol;
if (tagAsSym != null)
t = PrimType(tagAsSym);
}
if (t == null)
t = HostExpr.TagToType(tag);
return t;
}
#endregion
#region Name munging
static readonly IPersistentMap _charMap = PersistentHashMap.create('-', "_",
// '.', "_DOT_",
':', "_COLON_",
'+', "_PLUS_",
'>', "_GT_",
'<', "_LT_",
'=', "_EQ_",
'~', "_TILDE_",
'!', "_BANG_",
'@', "_CIRCA_",
'#', "_SHARP_",
'\'',"_SINGLEQUOTE_",
'"', "_DOUBLEQUOTE_",
'%', "_PERCENT_",
'^', "_CARET_",
'&', "_AMPERSAND_",
'*', "_STAR_",
'|', "_BAR_",
'{', "_LBRACE_",
'}', "_RBRACE_",
'[', "_LBRACK_",
']', "_RBRACK_",
'/', "_SLASH_",
'\\', "_BSLASH_",
'?', "_QMARK_"
);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores")]
public static IPersistentMap CHAR_MAP { get { return _charMap; } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "munge")]
public static string munge(string name)
{
StringBuilder sb = new StringBuilder();
foreach (char c in name)
{
string sub = (string)_charMap.valAt(c);
if (sub == null)
sb.Append(c);
else
sb.Append(sub);
}
return sb.ToString();
}
#endregion
#region Duplicate types
static Dictionary<String, Type> _duplicateTypeMap = new Dictionary<string, Type>();
internal static void RegisterDuplicateType(Type type)
{
_duplicateTypeMap[type.FullName] = type;
}
internal static Type FindDuplicateType(string typename)
{
Type type;
_duplicateTypeMap.TryGetValue(typename, out type);
return type;
}
#endregion
#region eval
/// <summary>
///
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
/// <remarks>Initial lowercase for core.clj compatibility</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "eval")]
public static object eval(object form)
{
int line = (int)LineVar.deref();
if (RT.meta(form) != null && RT.meta(form).containsKey(RT.LineKey))
line = (int)RT.meta(form).valAt(RT.LineKey);
int column = (int)ColumnVar.deref();
if (RT.meta(form) != null && RT.meta(form).containsKey(RT.ColumnKey))
column = (int)RT.meta(form).valAt(RT.ColumnKey);
IPersistentMap sourceSpan = (IPersistentMap)SourceSpanVar.deref();
if (RT.meta(form) != null && RT.meta(form).containsKey(RT.SourceSpanKey))
sourceSpan = (IPersistentMap)RT.meta(form).valAt(RT.SourceSpanKey);
ParserContext pconExpr = new ParserContext(RHC.Expression);
ParserContext pconEval = new ParserContext(RHC.Eval);
Var.pushThreadBindings(RT.map(LineVar, line, ColumnVar, column, SourceSpanVar, sourceSpan, CompilerContextVar, null));
try
{
form = Macroexpand(form);
bool formIsIpc = (form as IPersistentCollection) != null;
if (formIsIpc && Util.equals(RT.first(form), DoSym))
{
ISeq s = RT.next(form);
for (; RT.next(s) != null; s = RT.next(s))
eval(RT.first(s));
return eval(RT.first(s));
}
else if ( (form is IType) ||
(formIsIpc && !(RT.first(form) is Symbol && ((Symbol)RT.first(form)).Name.StartsWith("def"))))
{
ObjExpr objx = (ObjExpr)Analyze(pconExpr, RT.list(FnSym, PersistentVector.EMPTY, form), "eval__" + RT.nextID());
IFn fn = (IFn)objx.Eval();
return fn.invoke();
}
else
{
Expr expr = Analyze(pconEval, form);
return expr.Eval();
}
}
finally
{
Var.popThreadBindings();
}
}
#endregion
#region Macroexpansion
/// <summary>
///
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
/// <remarks>Initial lowercase for core.clj compatibility</remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "macroexpand")]
public static object macroexpand1(object form)
{
ISeq s = form as ISeq;
return s != null
? MacroexpandSeq1(s)
: form;
}
static object Macroexpand(object form)
{
object exf = macroexpand1(form);
if (exf != form)
return Macroexpand(exf);
return form;
}
private static object MacroexpandSeq1(ISeq form)
{
object op = RT.first(form);
if (IsSpecial(op))
return form;
// macro expansion
Var v = IsMacro(op);
if (v != null)
{
try
{
return v.applyTo(RT.cons(form, RT.cons(LocalEnvVar.get(), form.next())));
}
catch (ArityException e)
{
// hide the 2 extra params for a macro
throw new ArityException(e.Actual - 2, e.Name);
}
}
else
{
Symbol sym = op as Symbol;
if (sym != null)
{
string sname = sym.Name;
// (.substring s 2 5) => (. x substring 2 5)
if (sname[0] == '.')
{
if (form.count() < 2)
throw new ArgumentException("Malformed member expression, expecting (.member target ...)");
Symbol method = Symbol.intern(sname.Substring(1));
object target = RT.second(form);
if (HostExpr.MaybeType(target, false) != null)
target = ((IObj)RT.list(IdentitySym, target)).withMeta(RT.map(RT.TagKey, ClassSym));
// We need to make sure source information gets transferred
return MaybeTransferSourceInfo(PreserveTag(form, RT.listStar(DotSym, target, method, form.next().next())), form);
}
else if (NamesStaticMember(sym))
{
Symbol target = Symbol.intern(sym.Namespace);
Type t = HostExpr.MaybeType(target, false);
if (t != null)
{
Symbol method = Symbol.intern(sym.Name);
// We need to make sure source information gets transferred
return MaybeTransferSourceInfo(PreserveTag(form, RT.listStar(Compiler.DotSym, target, method, form.next())), form);
}
}
else
{
// (x.substring 2 5) => (. x substring 2 5)