forked from DrJavaAtRice/drjava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStandardTypeSystem.java
More file actions
2775 lines (2460 loc) · 126 KB
/
Copy pathStandardTypeSystem.java
File metadata and controls
2775 lines (2460 loc) · 126 KB
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
package edu.rice.cs.drjava.model.repl;
import java.util.*;
import edu.rice.cs.plt.tuple.Pair;
import edu.rice.cs.plt.tuple.Option;
import edu.rice.cs.plt.tuple.Wrapper;
import edu.rice.cs.plt.recur.*;
import edu.rice.cs.plt.lambda.*;
import edu.rice.cs.plt.iter.IterUtil;
import edu.rice.cs.plt.collect.CollectUtil;
import edu.rice.cs.plt.collect.Order;
import edu.rice.cs.plt.collect.PredicateSet;
import edu.rice.cs.plt.reflect.JavaVersion;
//import koala.dynamicjava.tree.*;
//import koala.dynamicjava.interpreter.TypeUtil;
//import koala.dynamicjava.interpreter.NodeProperties;
//import edu.rice.cs.dynamicjava.interpreter.EvaluatorException;
//import edu.rice.cs.dynamicjava.interpreter.ExpressionEvaluator;
//import edu.rice.cs.dynamicjava.interpreter.RuntimeBindings;
//import edu.rice.cs.dynamicjava.symbol.type.*;
import edu.rice.cs.drjava.model.repl.types.*;
import edu.rice.cs.drjava.model.repl.types.Type;
import static edu.rice.cs.plt.debug.DebugUtil.debug;
/** Abstract parent class for TypeSystems that stick to the standard Java notions of types, conversions,
* class members, etc. Subclasses are responsible for providing core type operations: subtyping, inference,
* well-formedness checking, etc.
*/
public abstract class StandardTypeSystem extends TypeSystem {
private final Options _opt;
/** Whether the most specific method test can use boxing to match parameters' types. This contradicts
* the JLS, but matches javac.
*/
private final boolean _boxingInMostSpecific;
/**
* Whether explicit type arguments (provided by the programmer) should be used if available. If not,
* inference always occurs, ignoring the explicit type arguments.
*/
private final boolean _useExplicitTypeArgs;
/**
* Whether two classes should be considered equal only if they have they are represented by the same
* object. The alternative is to compare full names. (Permissive equality allows for interdependencies,
* for example, between already-compiled classes and source classes.)
*/
private final boolean _strictClassEquality;
protected StandardTypeSystem(Options opt, boolean boxingInMostSpecific, boolean useExplicitTypeArgs,
boolean strictClassEquality) {
_opt = opt;
_boxingInMostSpecific = boxingInMostSpecific;
_useExplicitTypeArgs = useExplicitTypeArgs;
_strictClassEquality = strictClassEquality;
}
/** Determine if the type is well-formed. */
public abstract boolean isWellFormed(Type t);
/** Determine if the given types may be treated as equal. This is recursive, transitive, and symmetric. */
public abstract boolean isEqual(Type t1, Type t2);
/**
* Determine if {@code subT} is a subtype of {@code superT}. This is a recursive
* (in terms of {@link #isEqual}), transitive relation.
*/
public abstract boolean isSubtype(Type subT, Type superT);
/** Compute a common supertype of the given list of types. */
public abstract Type join(Iterable<? extends Type> ts);
/** Compute a common subtype of the given list of types. */
public abstract Type meet(Iterable<? extends Type> ts);
/** Produce types that are bounded by the corresponding type argument and parameter. */
protected abstract Iterable<Type> captureTypeArgs(Iterable<? extends Type> targs,
Iterable<? extends VariableType> params);
/**
* Top-level entry point for type inference. Produces the set of types corresponding to the given
* type parameters, given that {@code args} were provided where {@code params} were expected
* ({@code args} and {@code params} are assumed to have the same length), and {@code returned} will
* be returned where {@code expected} is expected.
*
* @return A set of inferred type arguments for {@code tparams}, or {@code null} if the parameters
* are overconstrained
*/
protected abstract Iterable<Type> inferTypeArguments(Iterable<? extends VariableType> tparams,
Iterable<? extends Type> params, Type returned,
Iterable<? extends Type> args, Option<Type> expected);
protected boolean sameClass(ClassType c1, ClassType c2) {
if (_strictClassEquality) { return c1.ofClass().equals(c2.ofClass()); }
else { return c1.ofClass().fullName().equals(c2.ofClass().fullName()); }
}
protected static final Type CLONEABLE_AND_SERIALIZABLE =
new IntersectionType(IterUtil.make(CLONEABLE, SERIALIZABLE));
// non-static because it depends on makeClassType
private final Type ITERABLE;
{
Class<?> c;
try { c = Class.forName("java.lang.Iterable"); }
catch (ClassNotFoundException e) { c = null; }
ITERABLE = (c == null) ? null : makeClassType(SymbolUtil.wrapClass(c));
}
// non-static because it depends on makeClassType
private final Type COLLECTION = makeClassType(SymbolUtil.wrapClass(Collection.class));
// non-static because it depends on makeClassType
private final Type ENUM;
{
Class<?> c;
try { c = Class.forName("java.lang.Enum"); }
catch (ClassNotFoundException e) { c = null; }
ENUM = (c == null) ? null : makeClassType(SymbolUtil.wrapClass(c));
}
private final DJClass CLASS = SymbolUtil.wrapClass(Class.class);
public TypePrinter typePrinter() { return new StandardTypePrinter(); }
/** Determine if {@code t} is a primitive. */
public boolean isPrimitive(Type t) { return t.apply(IS_PRIMITIVE); }
protected static final TypeVisitorLambda<Boolean> IS_PRIMITIVE = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forPrimitiveType(PrimitiveType t) { return true; }
};
/** Determine if {@code t} is a reference. */
public boolean isReference(Type t) { return t.apply(IS_REFERENCE); }
protected static final TypeVisitorLambda<Boolean> IS_REFERENCE = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forReferenceType(ReferenceType t) { return true; }
@Override public Boolean forVariableType(VariableType t) { return true; }
@Override public Boolean forIntersectionType(IntersectionType t) { return true; }
@Override public Boolean forUnionType(UnionType t) { return true; }
};
/** Determine if {@code t} is an array. */
public boolean isArray(Type t) { return t.apply(IS_ARRAY); }
protected static final TypeVisitorLambda<Boolean> IS_ARRAY = new TypeAbstractVisitor<Boolean>() {
private final Predicate<Type> PRED = LambdaUtil.asPredicate(this);
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forArrayType(ArrayType t) { return true; }
@Override public Boolean forVariableType(VariableType t) { return t.symbol().upperBound().apply(this); }
@Override public Boolean forIntersectionType(IntersectionType t) { return IterUtil.or(t.ofTypes(), PRED); }
@Override public Boolean forUnionType(UnionType t) {
// BOTTOM is not an array type
return !IterUtil.isEmpty(t.ofTypes()) && IterUtil.and(t.ofTypes(), PRED);
}
};
/**
* Determine if the type can be used in an enhanced for loop. {@code true} implies that an object of
* type {@code t} has member {@code iterator()}, which returns a {@link java.util.Iterator}.
*/
public boolean isIterable(Type t) { return isSubtype(t, ITERABLE == null ? COLLECTION : ITERABLE); }
/**
* Determine if an object with type {@code t} is enumerable (and so can be used as the selector of a
* {@code switch} statement)
*/
public boolean isEnum(Type t) { return ENUM != null && isSubtype(t, ENUM); }
/** Determine if the type is available at runtime (via a {@link Class} object) */
public boolean isReifiable(Type t) { return t.apply(IS_REIFIABLE); }
// cannot be defined statically, because it relies on the definition of non-static "IS_UNBOUNDED_WILDCARD"
private final TypeVisitorLambda<Boolean> IS_REIFIABLE = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forPrimitiveType(PrimitiveType t) { return true; }
@Override public Boolean forNullType(NullType t) { return true; }
@Override public Boolean forArrayType(ArrayType t) { return t.ofType().apply(this); }
@Override public Boolean forSimpleClassType(SimpleClassType t) { return true; }
@Override public Boolean forRawClassType(RawClassType t) { return true; }
@Override public Boolean forVoidType(VoidType t) { return true; }
@Override public Boolean forParameterizedClassType (ParameterizedClassType t) {
for (Type targ : t.typeArguments()) {
if (!targ.apply(IS_UNBOUNDED_WILDCARD)) { return false; }
}
return true;
}
};
// cannot be defined statically, because it relies on the definition of non-static "isEqual"
private final TypeVisitorLambda<Boolean> IS_UNBOUNDED_WILDCARD = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forWildcard(Wildcard t) {
return isEqual(t.symbol().upperBound(), OBJECT) && isEqual(t.symbol().lowerBound(), NULL);
}
};
/**
* Determine if there exist values whose most specific type is {@code t} (ignoring
* constructor-accessibility issues). (Note that this implies that {@code t} is captured.)
*/
public boolean isConcrete(Type t) { return t.apply(IS_CONCRETE); }
private static final TypeVisitorLambda<Boolean> IS_CONCRETE = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forPrimitiveType(PrimitiveType t) { return true; }
@Override public Boolean forArrayType(ArrayType t) { return true; }
@Override public Boolean forSimpleClassType(SimpleClassType t) { return isConcreteClass(t.ofClass()); }
@Override public Boolean forRawClassType(RawClassType t) { return isConcreteClass(t.ofClass()); }
@Override public Boolean forParameterizedClassType(ParameterizedClassType t) {
if (!isConcreteClass(t.ofClass())) { return false; }
for (Type targ : t.typeArguments()) {
if (targ instanceof Wildcard) { return false; }
}
return true;
}
private boolean isConcreteClass(DJClass c) {
return !c.isInterface() && !c.isAbstract();
}
};
public Option<Type> dynamicallyEnclosingType(Type t) { return t.apply(DYNAMICALLY_ENCLOSING); }
private static final TypeVisitorLambda<Option<Type>> DYNAMICALLY_ENCLOSING =
new TypeAbstractVisitor<Option<Type>>() {
public Option<Type> defaultCase(Type t) { return Option.none(); }
@Override public Option<Type> forClassType(ClassType t) {
return Option.<Type>wrap(SymbolUtil.dynamicOuterClassType(t));
}
};
/** Determine if {@code t} is valid in the {@code extends} clause of a class definition */
public boolean isExtendable(Type t) { return t.apply(IS_EXTENDABLE); }
private static final TypeVisitorLambda<Boolean> IS_EXTENDABLE = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forClassType(ClassType t) {
return !t.ofClass().isInterface() && !t.ofClass().isFinal();
}
};
/** Determine if {@code t} is valid in the {@code implements} clause of a class definition */
public boolean isImplementable(Type t) { return t.apply(IS_IMPLEMENTABLE); }
private static final TypeVisitorLambda<Boolean> IS_IMPLEMENTABLE = new TypeAbstractVisitor<Boolean>() {
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forClassType(ClassType t) { return t.ofClass().isInterface(); }
};
/** Test whether a variable is reachable from a type. */
protected boolean containsVar(Type t, final VariableType var) {
return containsAnyVar(t, Collections.singleton(var));
}
/** Test whether any of the given variables is reachable from a type. */
protected boolean containsAnyVar(Type t, final Set<? extends VariableType> vars) {
return t.apply(new TypeAbstractVisitor<Boolean>() {
private final RecursionStack<Type> _stack = new RecursionStack<Type>(Wrapper.<Type>factory());
public Boolean defaultCase(Type t) { return false; }
@Override public Boolean forArrayType(ArrayType t) { return t.ofType().apply(this); }
@Override public Boolean forParameterizedClassType(ParameterizedClassType t) {
return checkList(t.typeArguments());
}
@Override public Boolean forBoundType(BoundType t) { return checkList(t.ofTypes()); }
@Override public Boolean forVariableType(VariableType t) {
return vars.contains(t) || checkBoundedSymbol(t, t.symbol());
}
@Override public Boolean forWildcard(Wildcard w) { return checkBoundedSymbol(w, w.symbol()); }
private Boolean checkList(Iterable<? extends Type> types) {
for (Type t : types) {
if (t.apply(this)) { return true; }
}
return false;
}
private Boolean checkBoundedSymbol(Type t, final BoundedSymbol s) {
final TypeVisitor<Boolean> visitor = this; // handles this shadowing
Thunk<Boolean> handleBounds = new Thunk<Boolean>() {
public Boolean value() {
return s.lowerBound().apply(visitor) || s.upperBound().apply(visitor);
}
};
return _stack.apply(handleBounds, false, t);
}
});
}
/** Whether two types are known to be disjoint. (Standard version is implicitly defined in JLS 5.5.) */
public boolean isDisjoint(final Type s, final Type t) {
// By default, returns null for arrays and classes
abstract class Visitor extends TypeAbstractVisitor<Boolean> {
private final Type _other;
public Visitor(Type other) { _other = other; }
public abstract boolean recur(Type that);
@Override public Boolean forPrimitiveType(PrimitiveType that) {
return !isSubtype(that, _other) && !isSubtype(_other, that);
}
@Override public Boolean forNullType(NullType that) {
return !isSubtype(that, _other);
}
@Override public Boolean forArrayType(ArrayType that) { return null; }
@Override public Boolean forClassType(ClassType that) { return null; }
@Override public Boolean forIntersectionType(IntersectionType that) {
for (Type elt : that.ofTypes()) { if (recur(elt)) return true; }
return false;
}
@Override public Boolean forUnionType(UnionType that) {
for (Type elt : that.ofTypes()) { if (!recur(elt)) return false; }
return true;
}
@Override public Boolean forVariableType(VariableType that) {
// TODO: to be correct, we would need to recur (checked by a RecursionStack)
return false;
}
@Override public Boolean forTopType(TopType s) { return false; }
@Override public Boolean forBottomType(BottomType s) { return true; }
}
Boolean sResult = s.apply(new Visitor(t) {
public boolean recur(Type that) { return isDisjoint(that, t); }
});
if (sResult != null) { return sResult; }
else {
return t.apply(new Visitor(s) {
public boolean recur(Type that) { return isDisjoint(s, that); }
@Override public Boolean forArrayType(ArrayType t) {
if (s instanceof ArrayType) { return isDisjoint(((ArrayType) s).ofType(), t.ofType()); }
else { return !isSubtype(t, s); }
}
@Override public Boolean forClassType(ClassType t) {
if (s instanceof ArrayType) { return !isSubtype(s, t); }
else {
ClassType sAsClass = (ClassType) s;
if (sAsClass.ofClass().isFinal() || t.ofClass().isFinal() ||
(!sAsClass.ofClass().isInterface() && !t.ofClass().isInterface())) {
// either one of them is a final class or both are non-final classes
if (!isSubtype(s, erase(t)) && !isSubtype(t, erase(s))) { return true; }
}
// TODO: The JLS also checks for disjoint type arguments (comparing *all* common superclasses)
return false;
}
}
});
}
}
/** Determine if {@link #assign} would succeed given a non-constant expression of the given type */
public boolean isAssignable(Type target, Type expT) {
// TODO: Handle unchecked warnings -- perhaps at the call site
try {
Expression e = TypeUtil.makeEmptyExpression();
NodeProperties.setType(e, expT);
assign(target, e);
return true;
}
catch (UnsupportedConversionException e) { return false; }
}
/** Determine if {@link #assign} would succeed given a constant expression of the given type and value */
public boolean isAssignable(Type target, Type expT, Object expValue) {
// TODO: Handle unchecked warnings -- perhaps at the call site
try {
Expression e = TypeUtil.makeEmptyExpression();
NodeProperties.setType(e, expT);
NodeProperties.setValue(e, expValue);
assign(target, e);
return true;
}
catch (UnsupportedConversionException e) { return false; }
}
public boolean isPrimitiveConvertible(Type t) {
return isPrimitive(t) ||
(!_opt.prohibitBoxing() && !isSubtype(t, NULL) &&
(isSubtype(t, BOOLEAN_CLASS) ||
isSubtype(t, CHARACTER_CLASS) ||
isSubtype(t, BYTE_CLASS) ||
isSubtype(t, SHORT_CLASS) ||
isSubtype(t, INTEGER_CLASS) ||
isSubtype(t, LONG_CLASS) ||
isSubtype(t, FLOAT_CLASS) ||
isSubtype(t, DOUBLE_CLASS)));
}
public boolean isReferenceConvertible(Type t) {
return isReference(t) || !_opt.prohibitBoxing() && t instanceof PrimitiveType;
}
public Type immediateSuperclass(Type t) {
if (t instanceof ClassType) { return ((ClassType) t).ofClass().immediateSuperclass(); }
else { return null; }
}
public Type capture(Type t) { return t.apply(CAPTURE); }
// cannot be defined statically, because it relies on the definition of non-static "capture"
private final TypeVisitorLambda<Type> CAPTURE = new TypeAbstractVisitor<Type>() {
public Type defaultCase(Type t) { return t; }
public Type forVarargArrayType(VarargArrayType t) { return new SimpleArrayType(t.ofType()); }
@Override public Type forParameterizedClassType(ParameterizedClassType t) { return capture(t); }
};
protected ParameterizedClassType capture(ParameterizedClassType t) {
boolean ground = true; // optimization: simply return non-wildcard cases
for (Type arg : t.typeArguments()) {
if (arg instanceof Wildcard) { ground = false; break; }
}
if (ground) { return t; }
else {
Iterable<VariableType> params = SymbolUtil.allTypeParameters(t.ofClass());
Iterable<Type> captureArgs = captureTypeArgs(t.typeArguments(), params);
return new ParameterizedClassType(t.ofClass(), captureArgs);
}
}
/**
* Compute the erased type of {@code t}. The result is guaranteed to be reifiable (according
* to {@link #isReifiable}) and a supertype of {@code t}.
*/
public Type erase(Type t) { return t.apply(ERASE); }
private static final TypeVisitorLambda<Type> ERASE = new TypeAbstractVisitor<Type>() {
public Type defaultCase(Type t) { return t; }
@Override public Type forNullType(NullType t) { return OBJECT; }
@Override public Type forSimpleArrayType(SimpleArrayType t) {
Type newElementType = t.ofType().apply(this);
return (t.ofType() == newElementType) ? t : new SimpleArrayType(newElementType);
}
@Override public Type forVarargArrayType(VarargArrayType t) {
Type newElementType = t.ofType().apply(this);
return (t.ofType() == newElementType) ? t : new VarargArrayType(newElementType);
}
@Override public Type forParameterizedClassType(ParameterizedClassType t) {
return new RawClassType(t.ofClass());
}
@Override public Type forVariableType(VariableType t) { return t.symbol().upperBound().apply(this); }
@Override public Type forIntersectionType(IntersectionType t) {
if (IterUtil.isEmpty(t.ofTypes())) { return OBJECT; }
else { return IterUtil.first(t.ofTypes()).apply(this); }
}
@Override public Type forUnionType(UnionType t) {
// TODO: improve this result by performing a join on the erased class hierarchy
return OBJECT;
}
@Override public Type forWildcard(Wildcard t) { throw new IllegalArgumentException(); }
@Override public Type forTopType(TopType t) { throw new IllegalArgumentException(); }
@Override public Type forBottomType(BottomType t) { throw new IllegalArgumentException(); }
};
/**
* Determine the class corresponding to the erasure of {@code t}, or {@code null} if no such class object
* exists. To prevent over-eager loading of user-defined classes, computation of the result
* is delayed by wrapping it in a thunk. (A DJClass return type would be incorrect, as there's no such
* thing (for example) as an array DJClass.)
*/
public Thunk<Class<?>> erasedClass(Type t) { return t.apply(ERASED_CLASS); }
private static final TypeVisitorLambda<Thunk<Class<?>>> ERASED_CLASS = new TypeVisitorLambda<Thunk<Class<?>>>() {
public Thunk<Class<?>> forBooleanType(BooleanType t) { return LambdaUtil.<Class<?>>valueLambda(boolean.class); }
public Thunk<Class<?>> forCharType(CharType t) { return LambdaUtil.<Class<?>>valueLambda(char.class); }
public Thunk<Class<?>> forByteType(ByteType t) { return LambdaUtil.<Class<?>>valueLambda(byte.class); }
public Thunk<Class<?>> forShortType(ShortType t) { return LambdaUtil.<Class<?>>valueLambda(short.class); }
public Thunk<Class<?>> forIntType(IntType t) { return LambdaUtil.<Class<?>>valueLambda(int.class); }
public Thunk<Class<?>> forLongType(LongType t) { return LambdaUtil.<Class<?>>valueLambda(long.class); }
public Thunk<Class<?>> forFloatType(FloatType t) { return LambdaUtil.<Class<?>>valueLambda(float.class); }
public Thunk<Class<?>> forDoubleType(DoubleType t) { return LambdaUtil.<Class<?>>valueLambda(double.class); }
public Thunk<Class<?>> forNullType(NullType t) { return forSimpleClassType(OBJECT); }
public Thunk<Class<?>> forSimpleArrayType(SimpleArrayType t) {
Thunk<Class<?>> elementType = t.ofType().apply(this);
return (elementType == null) ? null : SymbolUtil.arrayClassThunk(elementType);
}
public Thunk<Class<?>> forVarargArrayType(VarargArrayType t) {
Thunk<Class<?>> elementType = t.ofType().apply(this);
return (elementType == null) ? null : SymbolUtil.arrayClassThunk(elementType);
}
public Thunk<Class<?>> forSimpleClassType(SimpleClassType t) { return wrapDJClass(t.ofClass()); }
public Thunk<Class<?>> forRawClassType(RawClassType t) { return wrapDJClass(t.ofClass()); }
public Thunk<Class<?>> forParameterizedClassType(ParameterizedClassType t) {
return wrapDJClass(t.ofClass());
}
public Thunk<Class<?>> forVariableType(VariableType t) {
return t.symbol().upperBound().apply(this);
}
public Thunk<Class<?>> forIntersectionType(IntersectionType t) {
Iterator<? extends Type> sups = t.ofTypes().iterator();
if (!sups.hasNext()) { return null; }
else { return sups.next().apply(this); }
}
public Thunk<Class<?>> forUnionType(UnionType t) { return forSimpleClassType(OBJECT); }
public Thunk<Class<?>> forWildcard(Wildcard t) { throw new IllegalArgumentException(); }
public Thunk<Class<?>> forVoidType(VoidType t) { return LambdaUtil.<Class<?>>valueLambda(void.class); }
public Thunk<Class<?>> forTopType(TopType t) { throw new IllegalArgumentException(); }
public Thunk<Class<?>> forBottomType(BottomType t) { throw new IllegalArgumentException(); }
private Thunk<Class<?>> wrapDJClass(final DJClass c) {
return new Thunk<Class<?>>() {
public Class<?> value() { return c.load(); }
};
}
};
/** Convert a raw class type to its wildcard-parameterized equivalent. */
protected ParameterizedClassType parameterize(final RawClassType t) {
Iterable<VariableType> tparams = SymbolUtil.allTypeParameters(t.ofClass());
return new ParameterizedClassType(t.ofClass(), IterUtil.mapSnapshot(tparams, new Lambda<VariableType, Type>() {
public Type value(VariableType param) {
// identity is determined by t and param -- result should be identical when repeatedly invoked
return new Wildcard(new BoundedSymbol(Pair.make(t, param), OBJECT, NULL));
}
}));
}
/**
* @return The type of the Class object associated with t (for example, (informally)
* {@code reflectionClassOf(java.lang.Integer) = Class<Integer>}).
*/
public Type reflectionClassOf(Type t) {
if (IterUtil.isEmpty(SymbolUtil.allTypeParameters(CLASS))) { return makeClassType(CLASS); }
else {
try { return makeClassType(CLASS, IterUtil.make(t)); }
catch (InvalidTypeArgumentException e) {
throw new RuntimeException("java.lang.Class has unexpected type parameter(s)");
}
}
}
/**
* Determine the element type of the given array type. Assumes {@code t} is an array type (according to
* {@link #isArray}).
*/
public Type arrayElementType(Type t) {
return t.apply(ARRAY_ELEMENT_TYPE);
}
// not defined statically because it relies on non-static meet() and join()
private final TypeVisitorLambda<Type> ARRAY_ELEMENT_TYPE = new TypeAbstractVisitor<Type>() {
public Type defaultCase(Type t) { throw new IllegalArgumentException(); }
@Override public Type forArrayType(ArrayType t) { return t.ofType(); }
@Override public Type forVariableType(VariableType t) { return t.symbol().upperBound().apply(this); }
@Override public Type forIntersectionType(IntersectionType t) {
// at least one element has an array type
return meet(IterUtil.map(t.ofTypes(), new Lambda<Type, Type>() {
public Type value(Type arrayT) {
return arrayT.apply(IS_ARRAY) ? arrayT.apply(ARRAY_ELEMENT_TYPE) : TOP;
}
}));
}
@Override public Type forUnionType(UnionType t) {
// there is at least one element, and all have array types
return join(IterUtil.map(t.ofTypes(), this));
}
};
protected static class SubstitutionMap {
private Map<VariableType, Type> _sigma;
private Iterable<? extends VariableType> _vars;
private Iterable<? extends Type> _values;
public static final SubstitutionMap EMPTY = new SubstitutionMap(IterUtil.<VariableType>empty(),
EMPTY_TYPE_ITERABLE);
public SubstitutionMap(Iterable<? extends VariableType> vars, Iterable<? extends Type> values) {
_sigma = null;
_vars = vars;
_values = values;
}
public SubstitutionMap(Map<? extends VariableType, ? extends Type> map) {
// make a copy to prevent mutation
_sigma = new HashMap<VariableType, Type>(map);
}
public boolean isEmpty() {
if (_sigma == null) { return IterUtil.isEmpty(_vars); }
else { return _sigma.isEmpty(); }
}
public Type get(VariableType v) {
if (_sigma == null) { initSigma(); }
return _sigma.get(v);
}
// Initialize the map lazily, because in same cases it may not be used at all.
private void initSigma() {
_sigma = new HashMap<VariableType, Type>();
for (Pair<VariableType, Type> pair : IterUtil.zip(_vars, _values)) {
_sigma.put(pair.first(), pair.second());
}
_vars = null;
_values = null;
}
}
/**
* Assumes each paramater is a unique variable, and that the length of params
* is consistent with the length of args.
*/
protected Type substitute(Type t, Iterable<? extends VariableType> params, Iterable<? extends Type> args) {
return substitute(t, new SubstitutionMap(params, args));
}
protected Type substitute(Type t, Map<? extends VariableType, ? extends Type> map) {
return substitute(t, new SubstitutionMap(map));
}
protected Type substitute(Type t, final SubstitutionMap sigma) {
if (sigma.isEmpty()) { return t; }
else {
final PrecomputedRecursionStack<Type, Type> stack = PrecomputedRecursionStack.make();
return t.apply(new TypeUpdateVisitor() {
@Override public Type forVariableType(VariableType t) {
Type result = sigma.get(t);
return (result == null) ? t : result;
}
@Override public Type forWildcard(final Wildcard t) {
final Wildcard newWildcard = new Wildcard(new BoundedSymbol(new Object()));
Thunk<Type> substituteBounds = new Thunk<Type>() {
public Type value() {
BoundedSymbol bounds = t.symbol();
Type newUpper = recur(bounds.upperBound());
Type newLower = recur(bounds.lowerBound());
if (newUpper == bounds.upperBound() && newLower == bounds.lowerBound()) { return t; }
else {
newWildcard.symbol().initializeUpperBound(newUpper);
newWildcard.symbol().initializeLowerBound(newLower);
return newWildcard;
}
}
};
return stack.apply(substituteBounds, newWildcard, t);
}
});
}
}
private Iterable<? extends Type> substitute(Iterable<? extends Type> ts,
Iterable<? extends VariableType> vars,
Iterable<? extends Type> values) {
return substitute(ts, new SubstitutionMap(vars, values));
}
private Iterable<? extends Type> substitute(Iterable<? extends Type> ts, final SubstitutionMap sigma) {
if (sigma.isEmpty()) { return ts; }
else {
return IterUtil.mapSnapshot(ts, new Lambda<Type, Type>() {
public Type value(Type t) { return substitute(t, sigma); }
});
}
}
/**
* Create a {@link SimpleClassType} or {@link RawClassType} corresponding to the given class.
*/
public ClassType makeClassType(DJClass c) {
if (IterUtil.isEmpty(SymbolUtil.allTypeParameters(c))) { return new SimpleClassType(c); }
else { return new RawClassType(c); }
}
/**
* Create a {@link SimpleClassType}, {@link RawClassType}, or {@link ParameterizedClassType}
* corresponding to the given class with given type arguments. If {@code args} is nonempty,
* the result must be a {@code ParameterizedClassType} (or an error must occur).
*
* @param c The class to be instantiated
* @param args The type arguments for {@code c}
* @throws InvalidTypeArgumentException If the arguments do not correspond to the formal parameters of
* {@code c} (bounds are not checked, so the result may not be
* well-formed).
*/
public ClassType makeClassType(DJClass c, Iterable<? extends Type> args) throws InvalidTypeArgumentException {
if (IterUtil.isEmpty(args)) { return makeClassType(c); }
else {
Iterable<VariableType> params = SymbolUtil.allTypeParameters(c);
if (IterUtil.sizeOf(params) != IterUtil.sizeOf(args)) { throw new InvalidTypeArgumentException(); }
else {
ParameterizedClassType result = new ParameterizedClassType(c, args);
return result;
}
}
}
/**
* Convert the expression to a primitive. The result is guaranteed to have a primitive type as its
* TYPE property (according to {@link #isPrimitive}).
*
* @param e A typed expression
* @return A typed expression equivalent to {@code e} that has a primitive type
* @throws UnsupportedConversionException If the expression cannot be converted to a primitive
*/
public Expression makePrimitive(Expression e) throws UnsupportedConversionException {
Type t = NodeProperties.getType(e);
if (isPrimitive(t)) { return e; }
else if (_opt.prohibitBoxing()) { throw new UnsupportedConversionException(); }
// Note: The spec is not clear about whether a *subtype* (such as a variable) can
// be unboxed. We allow it here unless the type is null, because that seems
// like the correct approach.
else if (isSubtype(t, NULL)) { throw new UnsupportedConversionException(); }
else if (isSubtype(t, BOOLEAN_CLASS)) { return unbox(e, "booleanValue"); }
else if (isSubtype(t, CHARACTER_CLASS)) { return unbox(e, "charValue"); }
else if (isSubtype(t, BYTE_CLASS)) { return unbox(e, "byteValue"); }
else if (isSubtype(t, SHORT_CLASS)) { return unbox(e, "shortValue"); }
else if (isSubtype(t, INTEGER_CLASS)) { return unbox(e, "intValue"); }
else if (isSubtype(t, LONG_CLASS)) { return unbox(e, "longValue"); }
else if (isSubtype(t, FLOAT_CLASS)) { return unbox(e, "floatValue"); }
else if (isSubtype(t, DOUBLE_CLASS)) { return unbox(e, "doubleValue"); }
else { throw new UnsupportedConversionException(); }
}
private Expression unbox(Expression exp, String methodName) {
ObjectMethodCall result = new ObjectMethodCall(exp, methodName, null, exp.getSourceInfo());
try {
ObjectMethodInvocation inv = lookupMethod(exp, methodName, EMPTY_TYPE_ITERABLE, EMPTY_EXPRESSION_ITERABLE,
NONE_TYPE_OPTION, new TopLevelAccessModule(""));
result.setExpression(inv.object());
result.setArguments(CollectUtil.makeList(inv.args()));
NodeProperties.setMethod(result, inv.method());
NodeProperties.setType(result, capture(inv.returnType()));
if (NodeProperties.hasValue(exp)) { NodeProperties.setValue(result, NodeProperties.getValue(exp)); }
return result;
}
catch (TypeSystemException e) { throw new RuntimeException("Unboxing method inaccessible", e); }
}
/**
* Convert the expression to a reference. The result is guaranteed to have a reference type as its
* TYPE property (according to {@link #isReference}).
*
* @param e A typed expression
* @return A typed expression equivalent to {@code e} that has a reference type
* @throws UnsupportedConversionException If the expression cannot be converted to a reference
*/
public Expression makeReference(final Expression e) throws UnsupportedConversionException {
Type t = NodeProperties.getType(e);
if (isReference(t)) { return e; }
else if (_opt.prohibitBoxing()) { throw new UnsupportedConversionException(); }
else {
Expression result = t.apply(new TypeAbstractVisitor<Expression>() {
public Expression defaultCase(Type t) { return null; }
@Override public Expression forBooleanType(BooleanType t) { return box(e, BOOLEAN_CLASS); }
@Override public Expression forCharType(CharType t) { return box(e, CHARACTER_CLASS); }
@Override public Expression forByteType(ByteType t) { return box(e, BYTE_CLASS); }
@Override public Expression forShortType(ShortType t) { return box(e, SHORT_CLASS); }
@Override public Expression forIntType(IntType t) { return box(e, INTEGER_CLASS); }
@Override public Expression forLongType(LongType t) { return box(e, LONG_CLASS); }
@Override public Expression forFloatType(FloatType t) { return box(e, FLOAT_CLASS); }
@Override public Expression forDoubleType(DoubleType t) { return box(e, DOUBLE_CLASS); }
});
if (result == null) { throw new UnsupportedConversionException(); }
else { return result; }
}
}
private Expression box(Expression exp, ClassType boxedType) {
ReferenceTypeName boxedTypeName = new ReferenceTypeName("java", "lang", boxedType.ofClass().declaredName());
NodeProperties.setType(boxedTypeName, boxedType);
List<Expression> arguments = Collections.singletonList(exp);
if (JavaVersion.CURRENT.supports(JavaVersion.JAVA_5)) {
StaticMethodCall m = new StaticMethodCall(boxedTypeName, "valueOf", arguments, exp.getSourceInfo());
try {
MethodInvocation inv = lookupStaticMethod(boxedType, "valueOf", EMPTY_TYPE_ITERABLE, arguments,
NONE_TYPE_OPTION, new TopLevelAccessModule(""));
m.setArguments(CollectUtil.makeList(inv.args()));
NodeProperties.setMethod(m, inv.method());
NodeProperties.setType(m, capture(inv.returnType()));
if (NodeProperties.hasValue(exp)) { NodeProperties.setValue(m, NodeProperties.getValue(exp)); }
return m;
}
catch (TypeSystemException e) { throw new RuntimeException("Boxing method inaccessible", e); }
}
else {
SimpleAllocation k = new SimpleAllocation(boxedTypeName, arguments, exp.getSourceInfo());
try {
ConstructorInvocation inv = lookupConstructor(boxedType, EMPTY_TYPE_ITERABLE, arguments, NONE_TYPE_OPTION,
new TopLevelAccessModule(""));
k.setArguments(CollectUtil.makeList(inv.args()));
NodeProperties.setConstructor(k, inv.constructor());
NodeProperties.setType(k, boxedType);
if (NodeProperties.hasValue(exp)) { NodeProperties.setValue(k, NodeProperties.getValue(exp)); }
return k;
}
catch (TypeSystemException e) { throw new RuntimeException("Boxing constructor inaccessible", e); }
}
}
/**
* Perform unary numeric promotion on an expression.
*
* @param e A typed expression with a primitive type
* @return A typed expression equivalent to {@code e} with the promoted type
* @throws UnsupportedConversionException If the expression cannot be used for numeric promotion
*/
public Expression unaryPromote(final Expression e) throws UnsupportedConversionException {
// Note: Variables with primitive bounds are not supported
Expression result = NodeProperties.getType(e).apply(new TypeAbstractVisitor<Expression>() {
public Expression defaultCase(Type t) { return null; }
@Override public Expression forNumericType(NumericType t) { return e; }
@Override public Expression forCharType(CharType t) { return makeCast(INT, e); }
@Override public Expression forByteType(ByteType t) { return makeCast(INT, e); }
@Override public Expression forShortType(ShortType t) { return makeCast(INT, e); }
});
if (result == null) { throw new UnsupportedConversionException(); }
else { return result; }
}
/**
* Perform binary numeric promotion on a pair of expressions. The resulting pair of expressions
* are guaranteed to have the same type.
*
* @param e1 A typed expression with a primitive type
* @param e2 A typed expression with a primitive type
* @return Two typed expressions equivalent to {@code e1} and {@code e2} with the promoted type
* @throws UnsupportedConversionException If either expression cannot be used for numeric promotion
*/
public Pair<Expression, Expression> binaryPromote(final Expression e1, final Expression e2)
throws UnsupportedConversionException {
// Note: Variables with primitive bounds are not fully supported
final Type t1 = NodeProperties.getType(e1);
final Type t2 = NodeProperties.getType(e2);
final Type t1Promoted = t1.apply(new TypeAbstractVisitor<Type>() {
@Override public Type defaultCase(Type t) { return null; }
@Override public Type forNumericType(NumericType t) { return INT; }
@Override public Type forFloatingPointType(FloatingPointType t) { return t; }
@Override public Type forLongType(LongType t) { return t; }
});
if (t1Promoted == null) { throw new UnsupportedConversionException(); }
final Type promoted = t2.apply(new TypeAbstractVisitor<Type>() {
@Override public Type defaultCase(Type t) { return null; }
@Override public Type forNumericType(NumericType t) { return t1Promoted; }
@Override public Type forDoubleType(DoubleType t) { return t; }
@Override public Type forFloatType(FloatType t) {
return (t1Promoted instanceof DoubleType) ? t1Promoted : t;
}
@Override public Type forLongType(LongType t) {
return (t1Promoted instanceof FloatingPointType) ? t1Promoted : t;
}
});
if (promoted == null) { throw new UnsupportedConversionException(); }
return Pair.make(t1.equals(promoted) ? e1 : makeCast(promoted, e1),
t2.equals(promoted) ? e2 : makeCast(promoted, e2));
}
/**
* Perform a join (as defined for the ? : operator) on a pair of expressions. The resulting pair
* of expressions are guaranteed to have the same type. That type may contain non-captured wildcards.
*
* @param e1 A typed expression
* @param e2 A typed expression
* @return Two typed expressions equivalent to {@code e1} and {@code e2} with the joined type
* @throws UnsupportedConversionException If the two types are incompatible.
*/
public Pair<Expression, Expression> mergeConditional(final Expression e1, final Expression e2)
throws UnsupportedConversionException {
return NodeProperties.getType(e1).apply(new TypeAbstractVisitor<Pair<Expression, Expression>>() {
public Pair<Expression, Expression> defaultCase(Type t1) {
if (isNumericReference(t1)) { return checkForNumericE2(); }
else if (isBooleanReference(t1) && NodeProperties.getType(e2) instanceof BooleanType) {
try { return Pair.make(makePrimitive(e1), e2); }
catch (UnsupportedConversionException e) { throw new RuntimeException("isBooleanReference() lied"); }
}
else { return joinReferences(); }
}
@Override public Pair<Expression, Expression> forBooleanType(BooleanType t1) {
Type t2 = NodeProperties.getType(e2);
if (t2 instanceof BooleanType) { return Pair.make(e1, e2); }
else if (isBooleanReference(t2)) {
try { return Pair.make(e1, makePrimitive(e2)); }
catch (UnsupportedConversionException e) { throw new RuntimeException("isBooleanReference() lied"); }
}
else { return joinReferences(); }
}
@Override public Pair<Expression, Expression> forNumericType(NumericType t1) { return checkForNumericE2(); }
private boolean isNumericReference(Type t) {
return !_opt.prohibitBoxing() && !isSubtype(t, NULL) &&
(isSubtype(t, CHARACTER_CLASS) ||
isSubtype(t, BYTE_CLASS) ||
isSubtype(t, SHORT_CLASS) ||
isSubtype(t, INTEGER_CLASS) ||
isSubtype(t, LONG_CLASS) ||
isSubtype(t, FLOAT_CLASS) ||
isSubtype(t, DOUBLE_CLASS));
}
private boolean isBooleanReference(Type t) {
return !_opt.prohibitBoxing() && isSubtype(t, BOOLEAN_CLASS) && !isSubtype(t, NULL);
}
private Pair<Expression, Expression> checkForNumericE2() {
return NodeProperties.getType(e2).apply(new TypeAbstractVisitor<Pair<Expression, Expression>>() {
public Pair<Expression, Expression> defaultCase(Type t2) {
if (isNumericReference(t2)) { return joinNumbers(); }
else { return joinReferences(); }
}
@Override public Pair<Expression, Expression> forNumericType(NumericType t2) { return joinNumbers(); }
});
}
private Pair<Expression, Expression> joinNumbers() {
try {
Expression unboxed1 = makePrimitive(e1);
Expression unboxed2 = makePrimitive(e2);
Type numT1 = NodeProperties.getType(unboxed1);
Type numT2 = NodeProperties.getType(unboxed2);
Type joined = null;
if (NodeProperties.hasValue(unboxed1) && numT1 instanceof IntType) {
joined = inRange(NodeProperties.getValue(unboxed1), numT2) ? numT2 : null;
}
if (joined == null && NodeProperties.hasValue(unboxed2) && numT2 instanceof IntType) {
joined = inRange(NodeProperties.getValue(unboxed2), numT1) ? numT1 : null;
}
if (joined == null) { joined = join(numT1, numT2); }
Expression result1 = isEqual(numT1, joined) ? unboxed1 : makeCast(joined, unboxed1);
Expression result2 = isEqual(numT2, joined) ? unboxed2 : makeCast(joined, unboxed2);
return Pair.make(result1, result2);
}
catch (UnsupportedConversionException e) { throw new IllegalArgumentException(e); }
}
private Pair<Expression, Expression> joinReferences() {
try {
Expression boxed1 = makeReference(e1);
Expression boxed2 = makeReference(e2);
Type refT1 = NodeProperties.getType(boxed1);
Type refT2 = NodeProperties.getType(boxed2);
Type joined = join(refT1, refT2);
Expression result1 = isEqual(refT1, joined) ? boxed1 : makeCast(joined, boxed1);
Expression result2 = isEqual(refT2, joined) ? boxed2 : makeCast(joined, boxed2);
return Pair.make(result1, result2);
}
catch (UnsupportedConversionException e) { throw new IllegalArgumentException(); }
}
});
}
/**
* Perform a cast on the given expression. Any necessary conversions are performed. One of
* {@code CHECKED_TYPE}, {@code CONVERTED_TYPE}, or {@code ASSERTED_TYPE} is set on the result.
*
* @return An expression equivalent to {@code e}, wrapped in any necessary conversions
* @throws UnsupportedConversionException If the cast is to an incompatible type.
*/
public Expression cast(final Type target, final Expression e) throws UnsupportedConversionException {
Expression result = target.apply(new TypeAbstractVisitor<Expression>() {
@Override public Expression forPrimitiveType(PrimitiveType target) {
try {
Expression result = makePrimitive(e);
Type source = NodeProperties.getType(result);