forked from clojure/clojure
/
Compiler.java
6794 lines (5999 loc) · 200 KB
/
Compiler.java
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.
**/
/* rich Aug 21, 2007 */
package clojure.lang;
//*
import clojure.asm.*;
import clojure.asm.commons.Method;
import clojure.asm.commons.GeneratorAdapter;
//*/
/*
import org.objectweb.asm.*;
import org.objectweb.asm.commons.Method;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import org.objectweb.asm.util.CheckClassAdapter;
//*/
import java.io.*;
import java.util.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
public class Compiler implements Opcodes{
static final Symbol DEF = Symbol.create("def");
static final Symbol LOOP = Symbol.create("loop*");
static final Symbol RECUR = Symbol.create("recur");
static final Symbol IF = Symbol.create("if");
static final Symbol LET = Symbol.create("let*");
static final Symbol LETFN = Symbol.create("letfn*");
static final Symbol DO = Symbol.create("do");
static final Symbol FN = Symbol.create("fn*");
static final Symbol QUOTE = Symbol.create("quote");
static final Symbol THE_VAR = Symbol.create("var");
static final Symbol DOT = Symbol.create(".");
static final Symbol ASSIGN = Symbol.create("set!");
//static final Symbol TRY_FINALLY = Symbol.create("try-finally");
static final Symbol TRY = Symbol.create("try");
static final Symbol CATCH = Symbol.create("catch");
static final Symbol FINALLY = Symbol.create("finally");
static final Symbol THROW = Symbol.create("throw");
static final Symbol MONITOR_ENTER = Symbol.create("monitor-enter");
static final Symbol MONITOR_EXIT = Symbol.create("monitor-exit");
static final Symbol IMPORT = Symbol.create("clojure.core", "import*");
//static final Symbol INSTANCE = Symbol.create("instance?");
static final Symbol DEFTYPE = Symbol.create("deftype*");
static final Symbol CASE = Symbol.create("case*");
//static final Symbol THISFN = Symbol.create("thisfn");
static final Symbol CLASS = Symbol.create("Class");
static final Symbol NEW = Symbol.create("new");
static final Symbol THIS = Symbol.create("this");
static final Symbol REIFY = Symbol.create("reify*");
//static final Symbol UNQUOTE = Symbol.create("unquote");
//static final Symbol UNQUOTE_SPLICING = Symbol.create("unquote-splicing");
//static final Symbol SYNTAX_QUOTE = Symbol.create("clojure.core", "syntax-quote");
static final Symbol LIST = Symbol.create("clojure.core", "list");
static final Symbol HASHMAP = Symbol.create("clojure.core", "hash-map");
static final Symbol VECTOR = Symbol.create("clojure.core", "vector");
static final Symbol IDENTITY = Symbol.create("clojure.core", "identity");
static final Symbol _AMP_ = Symbol.create("&");
static final Symbol ISEQ = Symbol.create("clojure.lang.ISeq");
static final Keyword inlineKey = Keyword.intern(null, "inline");
static final Keyword inlineAritiesKey = Keyword.intern(null, "inline-arities");
static final Keyword volatileKey = Keyword.intern(null, "volatile");
static final Keyword implementsKey = Keyword.intern(null, "implements");
static final String COMPILE_STUB_PREFIX = "compile__stub";
static final Keyword protocolKey = Keyword.intern(null, "protocol");
static final Keyword onKey = Keyword.intern(null, "on");
static final Symbol NS = Symbol.create("ns");
static final Symbol IN_NS = Symbol.create("in-ns");
//static final Symbol IMPORT = Symbol.create("import");
//static final Symbol USE = Symbol.create("use");
//static final Symbol IFN = Symbol.create("clojure.lang", "IFn");
static final public IPersistentMap specials = PersistentHashMap.create(
DEF, new DefExpr.Parser(),
LOOP, new LetExpr.Parser(),
RECUR, new RecurExpr.Parser(),
IF, new IfExpr.Parser(),
CASE, new CaseExpr.Parser(),
LET, new LetExpr.Parser(),
LETFN, new LetFnExpr.Parser(),
DO, new BodyExpr.Parser(),
FN, null,
QUOTE, new ConstantExpr.Parser(),
THE_VAR, new TheVarExpr.Parser(),
IMPORT, new ImportExpr.Parser(),
DOT, new HostExpr.Parser(),
ASSIGN, new AssignExpr.Parser(),
DEFTYPE, new NewInstanceExpr.DeftypeParser(),
REIFY, new NewInstanceExpr.ReifyParser(),
// TRY_FINALLY, new TryFinallyExpr.Parser(),
TRY, new TryExpr.Parser(),
THROW, new ThrowExpr.Parser(),
MONITOR_ENTER, new MonitorEnterExpr.Parser(),
MONITOR_EXIT, new MonitorExitExpr.Parser(),
// INSTANCE, new InstanceExpr.Parser(),
// IDENTICAL, new IdenticalExpr.Parser(),
//THISFN, null,
CATCH, null,
FINALLY, null,
// CLASS, new ClassExpr.Parser(),
NEW, new NewExpr.Parser(),
// UNQUOTE, null,
// UNQUOTE_SPLICING, null,
// SYNTAX_QUOTE, null,
_AMP_, null
);
private static final int MAX_POSITIONAL_ARITY = 20;
private static final Type OBJECT_TYPE;
private static final Type KEYWORD_TYPE = Type.getType(Keyword.class);
private static final Type VAR_TYPE = Type.getType(Var.class);
private static final Type SYMBOL_TYPE = Type.getType(Symbol.class);
//private static final Type NUM_TYPE = Type.getType(Num.class);
private static final Type IFN_TYPE = Type.getType(IFn.class);
private static final Type AFUNCTION_TYPE = Type.getType(AFunction.class);
private static final Type RT_TYPE = Type.getType(RT.class);
final static Type CLASS_TYPE = Type.getType(Class.class);
final static Type NS_TYPE = Type.getType(Namespace.class);
final static Type UTIL_TYPE = Type.getType(Util.class);
final static Type REFLECTOR_TYPE = Type.getType(Reflector.class);
final static Type THROWABLE_TYPE = Type.getType(Throwable.class);
final static Type BOOLEAN_OBJECT_TYPE = Type.getType(Boolean.class);
final static Type IPERSISTENTMAP_TYPE = Type.getType(IPersistentMap.class);
final static Type IOBJ_TYPE = Type.getType(IObj.class);
private static final Type[][] ARG_TYPES;
private static final Type[] EXCEPTION_TYPES = {Type.getType(Exception.class)};
static
{
OBJECT_TYPE = Type.getType(Object.class);
ARG_TYPES = new Type[MAX_POSITIONAL_ARITY + 2][];
for(int i = 0; i <= MAX_POSITIONAL_ARITY; ++i)
{
Type[] a = new Type[i];
for(int j = 0; j < i; j++)
a[j] = OBJECT_TYPE;
ARG_TYPES[i] = a;
}
Type[] a = new Type[MAX_POSITIONAL_ARITY + 1];
for(int j = 0; j < MAX_POSITIONAL_ARITY; j++)
a[j] = OBJECT_TYPE;
a[MAX_POSITIONAL_ARITY] = Type.getType("[Ljava/lang/Object;");
ARG_TYPES[MAX_POSITIONAL_ARITY + 1] = a;
}
//symbol->localbinding
static final public Var LOCAL_ENV = Var.create(null);
//vector<localbinding>
static final public Var LOOP_LOCALS = Var.create();
//Label
static final public Var LOOP_LABEL = Var.create();
//vector<object>
static final public Var CONSTANTS = Var.create();
//IdentityHashMap
static final public Var CONSTANT_IDS = Var.create();
//vector<keyword>
static final public Var KEYWORD_CALLSITES = Var.create();
//vector<var>
static final public Var PROTOCOL_CALLSITES = Var.create();
//vector<var>
static final public Var VAR_CALLSITES = Var.create();
//keyword->constid
static final public Var KEYWORDS = Var.create();
//var->constid
static final public Var VARS = Var.create();
//FnFrame
static final public Var METHOD = Var.create(null);
//null or not
static final public Var IN_CATCH_FINALLY = Var.create(null);
//DynamicClassLoader
static final public Var LOADER = Var.create();
//String
static final public Var SOURCE = Var.intern(Namespace.findOrCreate(Symbol.create("clojure.core")),
Symbol.create("*source-path*"), "NO_SOURCE_FILE");
//String
static final public Var SOURCE_PATH = Var.intern(Namespace.findOrCreate(Symbol.create("clojure.core")),
Symbol.create("*file*"), "NO_SOURCE_PATH");
//String
static final public Var COMPILE_PATH = Var.intern(Namespace.findOrCreate(Symbol.create("clojure.core")),
Symbol.create("*compile-path*"), null);
//boolean
static final public Var COMPILE_FILES = Var.intern(Namespace.findOrCreate(Symbol.create("clojure.core")),
Symbol.create("*compile-files*"), Boolean.FALSE);
static final public Var INSTANCE = Var.intern(Namespace.findOrCreate(Symbol.create("clojure.core")),
Symbol.create("instance?"));
//Integer
static final public Var LINE = Var.create(0);
//Integer
static final public Var LINE_BEFORE = Var.create(0);
static final public Var LINE_AFTER = Var.create(0);
//Integer
static final public Var NEXT_LOCAL_NUM = Var.create(0);
//Integer
static final public Var RET_LOCAL_NUM = Var.create();
static final public Var COMPILE_STUB_SYM = Var.create(null);
static final public Var COMPILE_STUB_CLASS = Var.create(null);
//PathNode chain
static final public Var CLEAR_PATH = Var.create(null);
//tail of PathNode chain
static final public Var CLEAR_ROOT = Var.create(null);
//LocalBinding -> Set<LocalBindingExpr>
static final public Var CLEAR_SITES = Var.create(null);
public enum C{
STATEMENT, //value ignored
EXPRESSION, //value required
RETURN, //tail position relative to enclosing recur frame
EVAL
}
interface Expr{
Object eval() throws Exception;
void emit(C context, ObjExpr objx, GeneratorAdapter gen);
boolean hasJavaClass() throws Exception;
Class getJavaClass() throws Exception;
}
public static abstract class UntypedExpr implements Expr{
public Class getJavaClass(){
throw new IllegalArgumentException("Has no Java class");
}
public boolean hasJavaClass(){
return false;
}
}
interface IParser{
Expr parse(C context, Object form) throws Exception;
}
static boolean isSpecial(Object sym){
return specials.containsKey(sym);
}
static Symbol resolveSymbol(Symbol sym){
//already qualified or classname?
if(sym.name.indexOf('.') > 0)
return sym;
if(sym.ns != null)
{
Namespace ns = namespaceFor(sym);
if(ns == null || ns.name.name == sym.ns)
return sym;
return Symbol.create(ns.name.name, sym.name);
}
Object o = currentNS().getMapping(sym);
if(o == null)
return Symbol.intern(currentNS().name.name, sym.name);
else if(o instanceof Class)
return Symbol.intern(null, ((Class) o).getName());
else if(o instanceof Var)
{
Var v = (Var) o;
return Symbol.create(v.ns.name.name, v.sym.name);
}
return null;
}
static class DefExpr implements Expr{
public final Var var;
public final Expr init;
public final Expr meta;
public final boolean initProvided;
public final String source;
public final int line;
final static Method bindRootMethod = Method.getMethod("void bindRoot(Object)");
final static Method setTagMethod = Method.getMethod("void setTag(clojure.lang.Symbol)");
final static Method setMetaMethod = Method.getMethod("void setMeta(clojure.lang.IPersistentMap)");
final static Method symcreate = Method.getMethod("clojure.lang.Symbol create(String, String)");
public DefExpr(String source, int line, Var var, Expr init, Expr meta, boolean initProvided){
this.source = source;
this.line = line;
this.var = var;
this.init = init;
this.meta = meta;
this.initProvided = initProvided;
}
public Object eval() throws Exception{
try
{
if(initProvided)
{
// if(init instanceof FnExpr && ((FnExpr) init).closes.count()==0)
// var.bindRoot(new FnLoaderThunk((FnExpr) init,var));
// else
var.bindRoot(init.eval());
}
if(meta != null)
{
var.setMeta((IPersistentMap) meta.eval());
}
return var;
}
catch(Throwable e)
{
if(!(e instanceof CompilerException))
throw new CompilerException(source, line, e);
else
throw (CompilerException) e;
}
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
objx.emitVar(gen, var);
if(meta != null)
{
gen.dup();
meta.emit(C.EXPRESSION, objx, gen);
gen.checkCast(IPERSISTENTMAP_TYPE);
gen.invokeVirtual(VAR_TYPE, setMetaMethod);
}
if(initProvided)
{
gen.dup();
init.emit(C.EXPRESSION, objx, gen);
gen.invokeVirtual(VAR_TYPE, bindRootMethod);
}
if(context == C.STATEMENT)
gen.pop();
}
public boolean hasJavaClass(){
return true;
}
public Class getJavaClass(){
return Var.class;
}
static class Parser implements IParser{
public Expr parse(C context, Object form) throws Exception{
//(def x) or (def x initexpr)
if(RT.count(form) > 3)
throw new Exception("Too many arguments to def");
else if(RT.count(form) < 2)
throw new Exception("Too few arguments to def");
else if(!(RT.second(form) instanceof Symbol))
throw new Exception("First argument to def must be a Symbol");
Symbol sym = (Symbol) RT.second(form);
Var v = lookupVar(sym, true);
if(v == null)
throw new Exception("Can't refer to qualified var that doesn't exist");
if(!v.ns.equals(currentNS()))
{
if(sym.ns == null)
throw new Exception("Name conflict, can't def " + sym + " because namespace: " + currentNS().name +
" refers to:" + v);
else
throw new Exception("Can't create defs outside of current ns");
}
IPersistentMap mm = sym.meta();
Object source_path = SOURCE_PATH.get();
source_path = source_path == null ? "NO_SOURCE_FILE" : source_path;
mm = (IPersistentMap) RT.assoc(mm, RT.LINE_KEY, LINE.get()).assoc(RT.FILE_KEY, source_path);
Expr meta = analyze(context == C.EVAL ? context : C.EXPRESSION, mm);
return new DefExpr((String) SOURCE.deref(), (Integer) LINE.deref(),
v, analyze(context == C.EVAL ? context : C.EXPRESSION, RT.third(form), v.sym.name),
meta, RT.count(form) == 3);
}
}
}
public static class AssignExpr implements Expr{
public final AssignableExpr target;
public final Expr val;
public AssignExpr(AssignableExpr target, Expr val){
this.target = target;
this.val = val;
}
public Object eval() throws Exception{
return target.evalAssign(val);
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
target.emitAssign(context, objx, gen, val);
}
public boolean hasJavaClass() throws Exception{
return val.hasJavaClass();
}
public Class getJavaClass() throws Exception{
return val.getJavaClass();
}
static class Parser implements IParser{
public Expr parse(C context, Object frm) throws Exception{
ISeq form = (ISeq) frm;
if(RT.length(form) != 3)
throw new IllegalArgumentException("Malformed assignment, expecting (set! target val)");
Expr target = analyze(C.EXPRESSION, RT.second(form));
if(!(target instanceof AssignableExpr))
throw new IllegalArgumentException("Invalid assignment target");
return new AssignExpr((AssignableExpr) target, analyze(C.EXPRESSION, RT.third(form)));
}
}
}
public static class VarExpr implements Expr, AssignableExpr{
public final Var var;
public final Object tag;
final static Method getMethod = Method.getMethod("Object get()");
final static Method setMethod = Method.getMethod("Object set(Object)");
public VarExpr(Var var, Symbol tag){
this.var = var;
this.tag = tag != null ? tag : var.getTag();
}
public Object eval() throws Exception{
return var.deref();
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
objx.emitVar(gen, var);
gen.invokeVirtual(VAR_TYPE, getMethod);
if(context == C.STATEMENT)
{
gen.pop();
}
}
public boolean hasJavaClass(){
return tag != null;
}
public Class getJavaClass() throws Exception{
return HostExpr.tagToClass(tag);
}
public Object evalAssign(Expr val) throws Exception{
return var.set(val.eval());
}
public void emitAssign(C context, ObjExpr objx, GeneratorAdapter gen,
Expr val){
objx.emitVar(gen, var);
val.emit(C.EXPRESSION, objx, gen);
gen.invokeVirtual(VAR_TYPE, setMethod);
if(context == C.STATEMENT)
gen.pop();
}
}
public static class TheVarExpr implements Expr{
public final Var var;
public TheVarExpr(Var var){
this.var = var;
}
public Object eval() throws Exception{
return var;
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
objx.emitVar(gen, var);
if(context == C.STATEMENT)
gen.pop();
}
public boolean hasJavaClass(){
return true;
}
public Class getJavaClass() throws ClassNotFoundException{
return Var.class;
}
static class Parser implements IParser{
public Expr parse(C context, Object form) throws Exception{
Symbol sym = (Symbol) RT.second(form);
Var v = lookupVar(sym, false);
if(v != null)
return new TheVarExpr(v);
throw new Exception("Unable to resolve var: " + sym + " in this context");
}
}
}
public static class KeywordExpr implements Expr{
public final Keyword k;
public KeywordExpr(Keyword k){
this.k = k;
}
public Object eval() throws Exception{
return k;
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
objx.emitKeyword(gen, k);
if(context == C.STATEMENT)
gen.pop();
}
public boolean hasJavaClass(){
return true;
}
public Class getJavaClass() throws ClassNotFoundException{
return Keyword.class;
}
}
public static class ImportExpr implements Expr{
public final String c;
final static Method forNameMethod = Method.getMethod("Class forName(String)");
final static Method importClassMethod = Method.getMethod("Class importClass(Class)");
final static Method derefMethod = Method.getMethod("Object deref()");
public ImportExpr(String c){
this.c = c;
}
public Object eval() throws Exception{
Namespace ns = (Namespace) RT.CURRENT_NS.deref();
ns.importClass(RT.classForName(c));
return null;
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
gen.getStatic(RT_TYPE,"CURRENT_NS",VAR_TYPE);
gen.invokeVirtual(VAR_TYPE, derefMethod);
gen.checkCast(NS_TYPE);
gen.push(c);
gen.invokeStatic(CLASS_TYPE, forNameMethod);
gen.invokeVirtual(NS_TYPE, importClassMethod);
if(context == C.STATEMENT)
gen.pop();
}
public boolean hasJavaClass(){
return false;
}
public Class getJavaClass() throws ClassNotFoundException{
throw new IllegalArgumentException("ImportExpr has no Java class");
}
static class Parser implements IParser{
public Expr parse(C context, Object form) throws Exception{
return new ImportExpr((String) RT.second(form));
}
}
}
public static abstract class LiteralExpr implements Expr{
abstract Object val();
public Object eval(){
return val();
}
}
static interface AssignableExpr{
Object evalAssign(Expr val) throws Exception;
void emitAssign(C context, ObjExpr objx, GeneratorAdapter gen, Expr val);
}
static public interface MaybePrimitiveExpr extends Expr{
public boolean canEmitPrimitive();
public void emitUnboxed(C context, ObjExpr objx, GeneratorAdapter gen);
}
static public abstract class HostExpr implements Expr, MaybePrimitiveExpr{
final static Type BOOLEAN_TYPE = Type.getType(Boolean.class);
final static Type CHAR_TYPE = Type.getType(Character.class);
final static Type INTEGER_TYPE = Type.getType(Integer.class);
final static Type LONG_TYPE = Type.getType(Long.class);
final static Type FLOAT_TYPE = Type.getType(Float.class);
final static Type DOUBLE_TYPE = Type.getType(Double.class);
final static Type SHORT_TYPE = Type.getType(Short.class);
final static Type BYTE_TYPE = Type.getType(Byte.class);
final static Type NUMBER_TYPE = Type.getType(Number.class);
final static Method charValueMethod = Method.getMethod("char charValue()");
final static Method booleanValueMethod = Method.getMethod("boolean booleanValue()");
final static Method charValueOfMethod = Method.getMethod("Character valueOf(char)");
final static Method intValueOfMethod = Method.getMethod("Integer valueOf(int)");
final static Method longValueOfMethod = Method.getMethod("Long valueOf(long)");
final static Method floatValueOfMethod = Method.getMethod("Float valueOf(float)");
final static Method doubleValueOfMethod = Method.getMethod("Double valueOf(double)");
final static Method shortValueOfMethod = Method.getMethod("Short valueOf(short)");
final static Method byteValueOfMethod = Method.getMethod("Byte valueOf(byte)");
final static Method intValueMethod = Method.getMethod("int intValue()");
final static Method longValueMethod = Method.getMethod("long longValue()");
final static Method floatValueMethod = Method.getMethod("float floatValue()");
final static Method doubleValueMethod = Method.getMethod("double doubleValue()");
final static Method byteValueMethod = Method.getMethod("byte byteValue()");
final static Method shortValueMethod = Method.getMethod("short shortValue()");
final static Method fromIntMethod = Method.getMethod("clojure.lang.Num from(int)");
final static Method fromLongMethod = Method.getMethod("clojure.lang.Num from(long)");
final static Method fromDoubleMethod = Method.getMethod("clojure.lang.Num from(double)");
//*
public static void emitBoxReturn(ObjExpr objx, GeneratorAdapter gen, Class returnType){
if(returnType.isPrimitive())
{
if(returnType == boolean.class)
{
Label falseLabel = gen.newLabel();
Label endLabel = gen.newLabel();
gen.ifZCmp(GeneratorAdapter.EQ, falseLabel);
gen.getStatic(BOOLEAN_OBJECT_TYPE, "TRUE", BOOLEAN_OBJECT_TYPE);
gen.goTo(endLabel);
gen.mark(falseLabel);
gen.getStatic(BOOLEAN_OBJECT_TYPE, "FALSE", BOOLEAN_OBJECT_TYPE);
// NIL_EXPR.emit(C.EXPRESSION, fn, gen);
gen.mark(endLabel);
}
else if(returnType == void.class)
{
NIL_EXPR.emit(C.EXPRESSION, objx, gen);
}
else if(returnType == char.class)
{
gen.invokeStatic(CHAR_TYPE, charValueOfMethod);
}
else
{
if(returnType == int.class)
//gen.invokeStatic(NUM_TYPE, fromIntMethod);
gen.invokeStatic(INTEGER_TYPE, intValueOfMethod);
else if(returnType == float.class)
{
//gen.visitInsn(F2D);
gen.invokeStatic(FLOAT_TYPE, floatValueOfMethod);
//m = floatValueOfMethod;
}
else if(returnType == double.class)
gen.invokeStatic(DOUBLE_TYPE, doubleValueOfMethod);
else if(returnType == long.class)
gen.invokeStatic(LONG_TYPE, longValueOfMethod);
else if(returnType == byte.class)
gen.invokeStatic(BYTE_TYPE, byteValueOfMethod);
else if(returnType == short.class)
gen.invokeStatic(SHORT_TYPE, shortValueOfMethod);
}
}
}
//*/
public static void emitUnboxArg(ObjExpr objx, GeneratorAdapter gen, Class paramType){
if(paramType.isPrimitive())
{
if(paramType == boolean.class)
{
gen.checkCast(BOOLEAN_TYPE);
gen.invokeVirtual(BOOLEAN_TYPE, booleanValueMethod);
// Label falseLabel = gen.newLabel();
// Label endLabel = gen.newLabel();
// gen.ifNull(falseLabel);
// gen.push(1);
// gen.goTo(endLabel);
// gen.mark(falseLabel);
// gen.push(0);
// gen.mark(endLabel);
}
else if(paramType == char.class)
{
gen.checkCast(CHAR_TYPE);
gen.invokeVirtual(CHAR_TYPE, charValueMethod);
}
else
{
Method m = intValueMethod;
gen.checkCast(NUMBER_TYPE);
if(paramType == int.class)
m = intValueMethod;
else if(paramType == float.class)
m = floatValueMethod;
else if(paramType == double.class)
m = doubleValueMethod;
else if(paramType == long.class)
m = longValueMethod;
else if(paramType == byte.class)
m = byteValueMethod;
else if(paramType == short.class)
m = shortValueMethod;
gen.invokeVirtual(NUMBER_TYPE, m);
}
}
else
{
gen.checkCast(Type.getType(paramType));
}
}
static class Parser implements IParser{
public Expr parse(C context, Object frm) throws Exception{
ISeq form = (ISeq) frm;
//(. x fieldname-sym) or
//(. x 0-ary-method)
// (. x methodname-sym args+)
// (. x (methodname-sym args?))
if(RT.length(form) < 3)
throw new IllegalArgumentException("Malformed member expression, expecting (. target member ...)");
//determine static or instance
//static target must be symbol, either fully.qualified.Classname or Classname that has been imported
int line = (Integer) LINE.deref();
String source = (String) SOURCE.deref();
Class c = maybeClass(RT.second(form), false);
//at this point c will be non-null if static
Expr instance = null;
if(c == null)
instance = analyze(context == C.EVAL ? context : C.EXPRESSION, RT.second(form));
boolean maybeField = RT.length(form) == 3 && RT.third(form) instanceof Symbol;
if(maybeField)
{
Symbol sym = (Symbol) RT.third(form);
if(c != null)
maybeField = Reflector.getMethods(c, 0, munge(sym.name), true).size() == 0;
else if(instance != null && instance.hasJavaClass() && instance.getJavaClass() != null)
maybeField = Reflector.getMethods(instance.getJavaClass(), 0, munge(sym.name), false).size() == 0;
}
if(maybeField) //field
{
Symbol sym = (Symbol) RT.third(form);
Symbol tag = tagOf(form);
if(c != null) {
return new StaticFieldExpr(line, c, munge(sym.name), tag);
} else
return new InstanceFieldExpr(line, instance, munge(sym.name), tag);
}
else
{
ISeq call = (ISeq) ((RT.third(form) instanceof ISeq) ? RT.third(form) : RT.next(RT.next(form)));
if(!(RT.first(call) instanceof Symbol))
throw new IllegalArgumentException("Malformed member expression");
Symbol sym = (Symbol) RT.first(call);
Symbol tag = tagOf(form);
PersistentVector args = PersistentVector.EMPTY;
for(ISeq s = RT.next(call); s != null; s = s.next())
args = args.cons(analyze(context == C.EVAL ? context : C.EXPRESSION, s.first()));
if(c != null)
return new StaticMethodExpr(source, line, tag, c, munge(sym.name), args);
else
return new InstanceMethodExpr(source, line, tag, instance, munge(sym.name), args);
}
}
}
private static Class maybeClass(Object form, boolean stringOk) throws Exception{
if(form instanceof Class)
return (Class) form;
Class c = null;
if(form instanceof Symbol)
{
Symbol sym = (Symbol) form;
if(sym.ns == null) //if ns-qualified can't be classname
{
if(Util.equals(sym,COMPILE_STUB_SYM.get()))
return (Class) COMPILE_STUB_CLASS.get();
if(sym.name.indexOf('.') > 0 || sym.name.charAt(0) == '[')
c = RT.classForName(sym.name);
else
{
Object o = currentNS().getMapping(sym);
if(o instanceof Class)
c = (Class) o;
}
}
}
else if(stringOk && form instanceof String)
c = RT.classForName((String) form);
return c;
}
/*
private static String maybeClassName(Object form, boolean stringOk){
String className = null;
if(form instanceof Symbol)
{
Symbol sym = (Symbol) form;
if(sym.ns == null) //if ns-qualified can't be classname
{
if(sym.name.indexOf('.') > 0 || sym.name.charAt(0) == '[')
className = sym.name;
else
{
IPersistentMap imports = (IPersistentMap) ((Var) RT.NS_IMPORTS.get()).get();
className = (String) imports.valAt(sym);
}
}
}
else if(stringOk && form instanceof String)
className = (String) form;
return className;
}
*/
static Class tagToClass(Object tag) throws Exception{
Class c = maybeClass(tag, true);
if(tag instanceof Symbol)
{
Symbol sym = (Symbol) tag;
if(sym.ns == null) //if ns-qualified can't be classname
{
if(sym.name.equals("objects"))
c = Object[].class;
else if(sym.name.equals("ints"))
c = int[].class;
else if(sym.name.equals("longs"))
c = long[].class;
else if(sym.name.equals("floats"))
c = float[].class;
else if(sym.name.equals("doubles"))
c = double[].class;
else if(sym.name.equals("chars"))
c = char[].class;
else if(sym.name.equals("shorts"))
c = short[].class;
else if(sym.name.equals("bytes"))
c = byte[].class;
else if(sym.name.equals("booleans"))
c = boolean[].class;
}
}
if(c != null)
return c;
throw new IllegalArgumentException("Unable to resolve classname: " + tag);
}
}
static abstract class FieldExpr extends HostExpr{
}
static class InstanceFieldExpr extends FieldExpr implements AssignableExpr{
public final Expr target;
public final Class targetClass;
public final java.lang.reflect.Field field;
public final String fieldName;
public final int line;
public final Symbol tag;
final static Method invokeNoArgInstanceMember = Method.getMethod("Object invokeNoArgInstanceMember(Object,String)");
final static Method setInstanceFieldMethod = Method.getMethod("Object setInstanceField(Object,String,Object)");
public InstanceFieldExpr(int line, Expr target, String fieldName, Symbol tag) throws Exception{
this.target = target;
this.targetClass = target.hasJavaClass() ? target.getJavaClass() : null;
this.field = targetClass != null ? Reflector.getField(targetClass, fieldName, false) : null;
this.fieldName = fieldName;
this.line = line;
this.tag = tag;
if(field == null && RT.booleanCast(RT.WARN_ON_REFLECTION.deref()))
{
((PrintWriter) RT.ERR.deref())
.format("Reflection warning, %s:%d - reference to field %s can't be resolved.\n",
SOURCE_PATH.deref(), line, fieldName);
}
}
public Object eval() throws Exception{
return Reflector.invokeNoArgInstanceMember(target.eval(), fieldName);
}
public boolean canEmitPrimitive(){
return targetClass != null && field != null &&
Util.isPrimitive(field.getType());
}
public void emitUnboxed(C context, ObjExpr objx, GeneratorAdapter gen){
gen.visitLineNumber(line, gen.mark());
if(targetClass != null && field != null)
{
target.emit(C.EXPRESSION, objx, gen);
gen.checkCast(getType(targetClass));
gen.getField(getType(targetClass), fieldName, Type.getType(field.getType()));
}
else
throw new UnsupportedOperationException("Unboxed emit of unknown member");
}
public void emit(C context, ObjExpr objx, GeneratorAdapter gen){
gen.visitLineNumber(line, gen.mark());
if(targetClass != null && field != null)
{
target.emit(C.EXPRESSION, objx, gen);
gen.checkCast(getType(targetClass));
gen.getField(getType(targetClass), fieldName, Type.getType(field.getType()));
//if(context != C.STATEMENT)
HostExpr.emitBoxReturn(objx, gen, field.getType());
if(context == C.STATEMENT)
{
gen.pop();
}
}
else
{
target.emit(C.EXPRESSION, objx, gen);
gen.push(fieldName);
gen.invokeStatic(REFLECTOR_TYPE, invokeNoArgInstanceMember);
if(context == C.STATEMENT)
gen.pop();
}
}
public boolean hasJavaClass() throws Exception{
return field != null || tag != null;
}
public Class getJavaClass() throws Exception{
return tag != null ? HostExpr.tagToClass(tag) : field.getType();
}
public Object evalAssign(Expr val) throws Exception{
return Reflector.setInstanceField(target.eval(), fieldName, val.eval());
}
public void emitAssign(C context, ObjExpr objx, GeneratorAdapter gen,
Expr val){
gen.visitLineNumber(line, gen.mark());
if(targetClass != null && field != null)
{
target.emit(C.EXPRESSION, objx, gen);
gen.checkCast(Type.getType(targetClass));
val.emit(C.EXPRESSION, objx, gen);
gen.dupX1();
HostExpr.emitUnboxArg(objx, gen, field.getType());
gen.putField(Type.getType(targetClass), fieldName, Type.getType(field.getType()));
}
else
{
target.emit(C.EXPRESSION, objx, gen);
gen.push(fieldName);
val.emit(C.EXPRESSION, objx, gen);
gen.invokeStatic(REFLECTOR_TYPE, setInstanceFieldMethod);
}
if(context == C.STATEMENT)