-
Notifications
You must be signed in to change notification settings - Fork 99
/
Types.java
5226 lines (4783 loc) · 194 KB
/
Types.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) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.code;
import java.lang.ref.SoftReference;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collector;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.Attribute.RetentionPolicy;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
import com.sun.tools.javac.code.TypeMetadata.Entry.Kind;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Check;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.LambdaToMethod;
import com.sun.tools.javac.jvm.ClassFile;
import com.sun.tools.javac.util.*;
import static com.sun.tools.javac.code.BoundKind.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import static com.sun.tools.javac.code.Scope.*;
import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
import static com.sun.tools.javac.code.Symbol.*;
import static com.sun.tools.javac.code.Type.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.jvm.ClassFile.externalize;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
/**
* Utility class containing various operations on types.
*
* <p>Unless other names are more illustrative, the following naming
* conventions should be observed in this file:
*
* <dl>
* <dt>t</dt>
* <dd>If the first argument to an operation is a type, it should be named t.</dd>
* <dt>s</dt>
* <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
* <dt>ts</dt>
* <dd>If an operations takes a list of types, the first should be named ts.</dd>
* <dt>ss</dt>
* <dd>A second list of types should be named ss.</dd>
* </dl>
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Types {
protected static final Context.Key<Types> typesKey = new Context.Key<>();
final Symtab syms;
final JavacMessages messages;
final Names names;
final boolean allowDefaultMethods;
final boolean mapCapturesToBounds;
final Check chk;
final Enter enter;
JCDiagnostic.Factory diags;
List<Warner> warnStack = List.nil();
final Name capturedName;
public final Warner noWarnings;
// <editor-fold defaultstate="collapsed" desc="Instantiating">
public static Types instance(Context context) {
Types instance = context.get(typesKey);
if (instance == null)
instance = new Types(context);
return instance;
}
protected Types(Context context) {
context.put(typesKey, this);
syms = Symtab.instance(context);
names = Names.instance(context);
Source source = Source.instance(context);
allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
mapCapturesToBounds = Feature.MAP_CAPTURES_TO_BOUNDS.allowedInSource(source);
chk = Check.instance(context);
enter = Enter.instance(context);
capturedName = names.fromString("<captured wildcard>");
messages = JavacMessages.instance(context);
diags = JCDiagnostic.Factory.instance(context);
noWarnings = new Warner(null);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="bounds">
/**
* Get a wildcard's upper bound, returning non-wildcards unchanged.
* @param t a type argument, either a wildcard or a type
*/
public Type wildUpperBound(Type t) {
if (t.hasTag(WILDCARD)) {
WildcardType w = (WildcardType) t;
if (w.isSuperBound())
return w.bound == null ? syms.objectType : w.bound.getUpperBound();
else
return wildUpperBound(w.type);
}
else return t;
}
/**
* Get a capture variable's upper bound, returning other types unchanged.
* @param t a type
*/
public Type cvarUpperBound(Type t) {
if (t.hasTag(TYPEVAR)) {
TypeVar v = (TypeVar) t;
return v.isCaptured() ? cvarUpperBound(v.getUpperBound()) : v;
}
else return t;
}
/**
* Get a wildcard's lower bound, returning non-wildcards unchanged.
* @param t a type argument, either a wildcard or a type
*/
public Type wildLowerBound(Type t) {
if (t.hasTag(WILDCARD)) {
WildcardType w = (WildcardType) t;
return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
}
else return t;
}
/**
* Get a capture variable's lower bound, returning other types unchanged.
* @param t a type
*/
public Type cvarLowerBound(Type t) {
if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) {
return cvarLowerBound(t.getLowerBound());
}
else return t;
}
/**
* Recursively skip type-variables until a class/array type is found; capture conversion is then
* (optionally) applied to the resulting type. This is useful for i.e. computing a site that is
* suitable for a method lookup.
*/
public Type skipTypeVars(Type site, boolean capture) {
while (site.hasTag(TYPEVAR)) {
site = site.getUpperBound();
}
return capture ? capture(site) : site;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="projections">
/**
* A projection kind. See {@link TypeProjection}
*/
enum ProjectionKind {
UPWARDS() {
@Override
ProjectionKind complement() {
return DOWNWARDS;
}
},
DOWNWARDS() {
@Override
ProjectionKind complement() {
return UPWARDS;
}
};
abstract ProjectionKind complement();
}
/**
* This visitor performs upwards and downwards projections on types.
*
* A projection is defined as a function that takes a type T, a set of type variables V and that
* produces another type S.
*
* An upwards projection maps a type T into a type S such that (i) T has no variables in V,
* and (ii) S is an upper bound of T.
*
* A downwards projection maps a type T into a type S such that (i) T has no variables in V,
* and (ii) S is a lower bound of T.
*
* Note that projections are only allowed to touch variables in V. Therefore, it is possible for
* a projection to leave its input type unchanged if it does not contain any variables in V.
*
* Moreover, note that while an upwards projection is always defined (every type as an upper bound),
* a downwards projection is not always defined.
*
* Examples:
*
* {@code upwards(List<#CAP1>, [#CAP1]) = List<? extends String>, where #CAP1 <: String }
* {@code downwards(List<#CAP2>, [#CAP2]) = List<? super String>, where #CAP2 :> String }
* {@code upwards(List<#CAP1>, [#CAP2]) = List<#CAP1> }
* {@code downwards(List<#CAP1>, [#CAP1]) = not defined }
*/
class TypeProjection extends TypeMapping<ProjectionKind> {
List<Type> vars;
Set<Type> seen = new HashSet<>();
public TypeProjection(List<Type> vars) {
this.vars = vars;
}
@Override
public Type visitClassType(ClassType t, ProjectionKind pkind) {
if (t.isCompound()) {
List<Type> components = directSupertypes(t);
List<Type> components1 = components.map(c -> c.map(this, pkind));
if (components == components1) return t;
else return makeIntersectionType(components1);
} else {
Type outer = t.getEnclosingType();
Type outer1 = visit(outer, pkind);
List<Type> typarams = t.getTypeArguments();
List<Type> formals = t.tsym.type.getTypeArguments();
ListBuffer<Type> typarams1 = new ListBuffer<>();
boolean changed = false;
for (Type actual : typarams) {
Type t2 = mapTypeArgument(t, formals.head.getUpperBound(), actual, pkind);
if (t2.hasTag(BOT)) {
//not defined
return syms.botType;
}
typarams1.add(t2);
changed |= actual != t2;
formals = formals.tail;
}
if (outer1 == outer && !changed) return t;
else return new ClassType(outer1, typarams1.toList(), t.tsym, t.getMetadata()) {
@Override
protected boolean needsStripping() {
return true;
}
};
}
}
@Override
public Type visitArrayType(ArrayType t, ProjectionKind s) {
Type elemtype = t.elemtype;
Type elemtype1 = visit(elemtype, s);
if (elemtype1 == elemtype) {
return t;
} else if (elemtype1.hasTag(BOT)) {
//undefined
return syms.botType;
} else {
return new ArrayType(elemtype1, t.tsym, t.metadata) {
@Override
protected boolean needsStripping() {
return true;
}
};
}
}
@Override
public Type visitTypeVar(TypeVar t, ProjectionKind pkind) {
if (vars.contains(t)) {
if (seen.add(t)) {
try {
final Type bound;
switch (pkind) {
case UPWARDS:
bound = t.getUpperBound();
break;
case DOWNWARDS:
bound = (t.getLowerBound() == null) ?
syms.botType :
t.getLowerBound();
break;
default:
Assert.error();
return null;
}
return bound.map(this, pkind);
} finally {
seen.remove(t);
}
} else {
//cycle
return pkind == ProjectionKind.UPWARDS ?
syms.objectType : syms.botType;
}
} else {
return t;
}
}
private Type mapTypeArgument(Type site, Type declaredBound, Type t, ProjectionKind pkind) {
return t.containsAny(vars) ?
t.map(new TypeArgumentProjection(site, declaredBound), pkind) :
t;
}
class TypeArgumentProjection extends TypeMapping<ProjectionKind> {
Type site;
Type declaredBound;
TypeArgumentProjection(Type site, Type declaredBound) {
this.site = site;
this.declaredBound = declaredBound;
}
@Override
public Type visitType(Type t, ProjectionKind pkind) {
//type argument is some type containing restricted vars
if (pkind == ProjectionKind.DOWNWARDS) {
//not defined
return syms.botType;
}
Type upper = t.map(TypeProjection.this, ProjectionKind.UPWARDS);
Type lower = t.map(TypeProjection.this, ProjectionKind.DOWNWARDS);
List<Type> formals = site.tsym.type.getTypeArguments();
BoundKind bk;
Type bound;
if (!isSameType(upper, syms.objectType) &&
(declaredBound.containsAny(formals) ||
!isSubtype(declaredBound, upper))) {
bound = upper;
bk = EXTENDS;
} else if (!lower.hasTag(BOT)) {
bound = lower;
bk = SUPER;
} else {
bound = syms.objectType;
bk = UNBOUND;
}
return makeWildcard(bound, bk);
}
@Override
public Type visitWildcardType(WildcardType wt, ProjectionKind pkind) {
//type argument is some wildcard whose bound contains restricted vars
Type bound = syms.botType;
BoundKind bk = wt.kind;
switch (wt.kind) {
case EXTENDS:
bound = wt.type.map(TypeProjection.this, pkind);
if (bound.hasTag(BOT)) {
return syms.botType;
}
break;
case SUPER:
bound = wt.type.map(TypeProjection.this, pkind.complement());
if (bound.hasTag(BOT)) {
bound = syms.objectType;
bk = UNBOUND;
}
break;
}
return makeWildcard(bound, bk);
}
private Type makeWildcard(Type bound, BoundKind bk) {
return new WildcardType(bound, bk, syms.boundClass) {
@Override
protected boolean needsStripping() {
return true;
}
};
}
}
}
/**
* Computes an upward projection of given type, and vars. See {@link TypeProjection}.
*
* @param t the type to be projected
* @param vars the set of type variables to be mapped
* @return the type obtained as result of the projection
*/
public Type upward(Type t, List<Type> vars) {
return t.map(new TypeProjection(vars), ProjectionKind.UPWARDS);
}
/**
* Computes the set of captured variables mentioned in a given type. See {@link CaptureScanner}.
* This routine is typically used to computed the input set of variables to be used during
* an upwards projection (see {@link Types#upward(Type, List)}).
*
* @param t the type where occurrences of captured variables have to be found
* @return the set of captured variables found in t
*/
public List<Type> captures(Type t) {
CaptureScanner cs = new CaptureScanner();
Set<Type> captures = new HashSet<>();
cs.visit(t, captures);
return List.from(captures);
}
/**
* This visitor scans a type recursively looking for occurrences of captured type variables.
*/
class CaptureScanner extends SimpleVisitor<Void, Set<Type>> {
@Override
public Void visitType(Type t, Set<Type> types) {
return null;
}
@Override
public Void visitClassType(ClassType t, Set<Type> seen) {
if (t.isCompound()) {
directSupertypes(t).forEach(s -> visit(s, seen));
} else {
t.allparams().forEach(ta -> visit(ta, seen));
}
return null;
}
@Override
public Void visitArrayType(ArrayType t, Set<Type> seen) {
return visit(t.elemtype, seen);
}
@Override
public Void visitWildcardType(WildcardType t, Set<Type> seen) {
visit(t.type, seen);
return null;
}
@Override
public Void visitTypeVar(TypeVar t, Set<Type> seen) {
if ((t.tsym.flags() & Flags.SYNTHETIC) != 0 && seen.add(t)) {
visit(t.getUpperBound(), seen);
}
return null;
}
@Override
public Void visitCapturedType(CapturedType t, Set<Type> seen) {
if (seen.add(t)) {
visit(t.getUpperBound(), seen);
visit(t.getLowerBound(), seen);
}
return null;
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isUnbounded">
/**
* Checks that all the arguments to a class are unbounded
* wildcards or something else that doesn't make any restrictions
* on the arguments. If a class isUnbounded, a raw super- or
* subclass can be cast to it without a warning.
* @param t a type
* @return true iff the given type is unbounded or raw
*/
public boolean isUnbounded(Type t) {
return isUnbounded.visit(t);
}
// where
private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
public Boolean visitType(Type t, Void ignored) {
return true;
}
@Override
public Boolean visitClassType(ClassType t, Void ignored) {
List<Type> parms = t.tsym.type.allparams();
List<Type> args = t.allparams();
while (parms.nonEmpty()) {
WildcardType unb = new WildcardType(syms.objectType,
BoundKind.UNBOUND,
syms.boundClass,
(TypeVar)parms.head);
if (!containsType(args.head, unb))
return false;
parms = parms.tail;
args = args.tail;
}
return true;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="asSub">
/**
* Return the least specific subtype of t that starts with symbol
* sym. If none exists, return null. The least specific subtype
* is determined as follows:
*
* <p>If there is exactly one parameterized instance of sym that is a
* subtype of t, that parameterized instance is returned.<br>
* Otherwise, if the plain type or raw type `sym' is a subtype of
* type t, the type `sym' itself is returned. Otherwise, null is
* returned.
*/
public Type asSub(Type t, Symbol sym) {
return asSub.visit(t, sym);
}
// where
private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
public Type visitType(Type t, Symbol sym) {
return null;
}
@Override
public Type visitClassType(ClassType t, Symbol sym) {
if (t.tsym == sym)
return t;
Type base = asSuper(sym.type, t.tsym);
if (base == null)
return null;
ListBuffer<Type> from = new ListBuffer<>();
ListBuffer<Type> to = new ListBuffer<>();
try {
adapt(base, t, from, to);
} catch (AdaptFailure ex) {
return null;
}
Type res = subst(sym.type, from.toList(), to.toList());
if (!isSubtype(res, t))
return null;
ListBuffer<Type> openVars = new ListBuffer<>();
for (List<Type> l = sym.type.allparams();
l.nonEmpty(); l = l.tail)
if (res.contains(l.head) && !t.contains(l.head))
openVars.append(l.head);
if (openVars.nonEmpty()) {
if (t.isRaw()) {
// The subtype of a raw type is raw
res = erasure(res);
} else {
// Unbound type arguments default to ?
List<Type> opens = openVars.toList();
ListBuffer<Type> qs = new ListBuffer<>();
for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND,
syms.boundClass, (TypeVar) iter.head));
}
res = subst(res, opens, qs.toList());
}
}
return res;
}
@Override
public Type visitErrorType(ErrorType t, Symbol sym) {
return t;
}
};
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="isConvertible">
/**
* Is t a subtype of or convertible via boxing/unboxing
* conversion to s?
*/
public boolean isConvertible(Type t, Type s, Warner warn) {
if (t.hasTag(ERROR)) {
return true;
}
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (tPrimitive == sPrimitive) {
return isSubtypeUnchecked(t, s, warn);
}
boolean tUndet = t.hasTag(UNDETVAR);
boolean sUndet = s.hasTag(UNDETVAR);
if (tUndet || sUndet) {
return tUndet ?
isSubtype(t, boxedTypeOrType(s)) :
isSubtype(boxedTypeOrType(t), s);
}
return tPrimitive
? isSubtype(boxedClass(t).type, s)
: isSubtype(unboxedType(t), s);
}
/**
* Is t a subtype of or convertible via boxing/unboxing
* conversions to s?
*/
public boolean isConvertible(Type t, Type s) {
return isConvertible(t, s, noWarnings);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="findSam">
/**
* Exception used to report a function descriptor lookup failure. The exception
* wraps a diagnostic that can be used to generate more details error
* messages.
*/
public static class FunctionDescriptorLookupError extends RuntimeException {
private static final long serialVersionUID = 0;
transient JCDiagnostic diagnostic;
FunctionDescriptorLookupError() {
this.diagnostic = null;
}
FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
this.diagnostic = diag;
return this;
}
public JCDiagnostic getDiagnostic() {
return diagnostic;
}
}
/**
* A cache that keeps track of function descriptors associated with given
* functional interfaces.
*/
class DescriptorCache {
private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<>();
class FunctionDescriptor {
Symbol descSym;
FunctionDescriptor(Symbol descSym) {
this.descSym = descSym;
}
public Symbol getSymbol() {
return descSym;
}
public Type getType(Type site) {
site = removeWildcards(site);
if (site.isIntersection()) {
IntersectionClassType ict = (IntersectionClassType)site;
for (Type component : ict.getExplicitComponents()) {
if (!chk.checkValidGenericType(component)) {
//if the inferred functional interface type is not well-formed,
//or if it's not a subtype of the original target, issue an error
throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
}
}
} else {
if (!chk.checkValidGenericType(site)) {
//if the inferred functional interface type is not well-formed,
//or if it's not a subtype of the original target, issue an error
throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
}
}
return memberType(site, descSym);
}
}
class Entry {
final FunctionDescriptor cachedDescRes;
final int prevMark;
public Entry(FunctionDescriptor cachedDescRes,
int prevMark) {
this.cachedDescRes = cachedDescRes;
this.prevMark = prevMark;
}
boolean matches(int mark) {
return this.prevMark == mark;
}
}
FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
Entry e = _map.get(origin);
CompoundScope members = membersClosure(origin.type, false);
if (e == null ||
!e.matches(members.getMark())) {
FunctionDescriptor descRes = findDescriptorInternal(origin, members);
_map.put(origin, new Entry(descRes, members.getMark()));
return descRes;
}
else {
return e.cachedDescRes;
}
}
/**
* Compute the function descriptor associated with a given functional interface
*/
public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
CompoundScope membersCache) throws FunctionDescriptorLookupError {
if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0 || origin.isSealed()) {
//t must be an interface
throw failure("not.a.functional.intf", origin);
}
final ListBuffer<Symbol> abstracts = new ListBuffer<>();
for (Symbol sym : membersCache.getSymbols(new DescriptorFilter(origin))) {
Type mtype = memberType(origin.type, sym);
if (abstracts.isEmpty()) {
abstracts.append(sym);
} else if ((sym.name == abstracts.first().name &&
overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
if (!abstracts.stream().filter(msym -> msym.owner.isSubClass(sym.enclClass(), Types.this))
.map(msym -> memberType(origin.type, msym))
.anyMatch(abstractMType -> isSubSignature(abstractMType, mtype))) {
abstracts.append(sym);
}
} else {
//the target method(s) should be the only abstract members of t
throw failure("not.a.functional.intf.1", origin,
diags.fragment(Fragments.IncompatibleAbstracts(Kinds.kindName(origin), origin)));
}
}
if (abstracts.isEmpty()) {
//t must define a suitable non-generic method
throw failure("not.a.functional.intf.1", origin,
diags.fragment(Fragments.NoAbstracts(Kinds.kindName(origin), origin)));
} else if (abstracts.size() == 1) {
return new FunctionDescriptor(abstracts.first());
} else { // size > 1
FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
if (descRes == null) {
//we can get here if the functional interface is ill-formed
ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
for (Symbol desc : abstracts) {
String key = desc.type.getThrownTypes().nonEmpty() ?
"descriptor.throws" : "descriptor";
descriptors.append(diags.fragment(key, desc.name,
desc.type.getParameterTypes(),
desc.type.getReturnType(),
desc.type.getThrownTypes()));
}
JCDiagnostic msg =
diags.fragment(Fragments.IncompatibleDescsInFunctionalIntf(Kinds.kindName(origin),
origin));
JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
new JCDiagnostic.MultilineDiagnostic(msg, descriptors.toList());
throw failure(incompatibleDescriptors);
}
return descRes;
}
}
/**
* Compute a synthetic type for the target descriptor given a list
* of override-equivalent methods in the functional interface type.
* The resulting method type is a method type that is override-equivalent
* and return-type substitutable with each method in the original list.
*/
private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
return mergeAbstracts(methodSyms, origin.type, false)
.map(bestSoFar -> new FunctionDescriptor(bestSoFar.baseSymbol()) {
@Override
public Type getType(Type origin) {
Type mt = memberType(origin, getSymbol());
return createMethodTypeWithThrown(mt, bestSoFar.type.getThrownTypes());
}
}).orElse(null);
}
FunctionDescriptorLookupError failure(String msg, Object... args) {
return failure(diags.fragment(msg, args));
}
FunctionDescriptorLookupError failure(JCDiagnostic diag) {
return new FunctionDescriptorLookupError().setMessage(diag);
}
}
private DescriptorCache descCache = new DescriptorCache();
/**
* Find the method descriptor associated to this class symbol - if the
* symbol 'origin' is not a functional interface, an exception is thrown.
*/
public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
return descCache.get(origin).getSymbol();
}
/**
* Find the type of the method descriptor associated to this class symbol -
* if the symbol 'origin' is not a functional interface, an exception is thrown.
*/
public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
return descCache.get(origin.tsym).getType(origin);
}
/**
* Is given type a functional interface?
*/
public boolean isFunctionalInterface(TypeSymbol tsym) {
try {
findDescriptorSymbol(tsym);
return true;
} catch (FunctionDescriptorLookupError ex) {
return false;
}
}
public boolean isFunctionalInterface(Type site) {
try {
findDescriptorType(site);
return true;
} catch (FunctionDescriptorLookupError ex) {
return false;
}
}
public Type removeWildcards(Type site) {
if (site.getTypeArguments().stream().anyMatch(t -> t.hasTag(WILDCARD))) {
//compute non-wildcard parameterization - JLS 9.9
List<Type> actuals = site.getTypeArguments();
List<Type> formals = site.tsym.type.getTypeArguments();
ListBuffer<Type> targs = new ListBuffer<>();
for (Type formal : formals) {
Type actual = actuals.head;
Type bound = formal.getUpperBound();
if (actuals.head.hasTag(WILDCARD)) {
WildcardType wt = (WildcardType)actual;
//check that bound does not contain other formals
if (bound.containsAny(formals)) {
targs.add(wt.type);
} else {
//compute new type-argument based on declared bound and wildcard bound
switch (wt.kind) {
case UNBOUND:
targs.add(bound);
break;
case EXTENDS:
targs.add(glb(bound, wt.type));
break;
case SUPER:
targs.add(wt.type);
break;
default:
Assert.error("Cannot get here!");
}
}
} else {
//not a wildcard - the new type argument remains unchanged
targs.add(actual);
}
actuals = actuals.tail;
}
return subst(site.tsym.type, formals, targs.toList());
} else {
return site;
}
}
/**
* Create a symbol for a class that implements a given functional interface
* and overrides its functional descriptor. This routine is used for two
* main purposes: (i) checking well-formedness of a functional interface;
* (ii) perform functional interface bridge calculation.
*/
public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, Type target, long cflags) {
if (target == null || target == syms.unknownType) {
return null;
}
Symbol descSym = findDescriptorSymbol(target.tsym);
Type descType = findDescriptorType(target);
ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
csym.completer = Completer.NULL_COMPLETER;
csym.members_field = WriteableScope.create(csym);
MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
csym.members_field.enter(instDescSym);
Type.ClassType ctype = new Type.ClassType(Type.noType, List.nil(), csym);
ctype.supertype_field = syms.objectType;
ctype.interfaces_field = target.isIntersection() ?
directSupertypes(target) :
List.of(target);
csym.type = ctype;
csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
return csym;
}
/**
* Find the minimal set of methods that are overridden by the functional
* descriptor in 'origin'. All returned methods are assumed to have different
* erased signatures.
*/
public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
Assert.check(isFunctionalInterface(origin));
Symbol descSym = findDescriptorSymbol(origin);
CompoundScope members = membersClosure(origin.type, false);
ListBuffer<Symbol> overridden = new ListBuffer<>();
outer: for (Symbol m2 : members.getSymbolsByName(descSym.name, bridgeFilter)) {
if (m2 == descSym) continue;
else if (descSym.overrides(m2, origin, Types.this, false)) {
for (Symbol m3 : overridden) {
if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
(m3.overrides(m2, origin, Types.this, false) &&
(pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
(((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
continue outer;
}
}
overridden.add(m2);
}
}
return overridden.toList();
}
//where
private Filter<Symbol> bridgeFilter = new Filter<Symbol>() {
public boolean accepts(Symbol t) {
return t.kind == MTH &&
t.name != names.init &&
t.name != names.clinit &&
(t.flags() & SYNTHETIC) == 0;
}
};
private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
//a symbol will be completed from a classfile if (a) symbol has
//an associated file object with CLASS kind and (b) the symbol has
//not been entered
if (origin.classfile != null &&
origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
enter.getEnv(origin) == null) {
return false;
}
if (origin == s) {
return true;
}
for (Type t : interfaces(origin.type)) {
if (pendingBridges((ClassSymbol)t.tsym, s)) {
return true;
}
}
return false;
}
// </editor-fold>
/**
* Scope filter used to skip methods that should be ignored (such as methods
* overridden by j.l.Object) during function interface conversion interface check
*/
class DescriptorFilter implements Filter<Symbol> {
TypeSymbol origin;
DescriptorFilter(TypeSymbol origin) {
this.origin = origin;
}
@Override
public boolean accepts(Symbol sym) {
return sym.kind == MTH &&
(sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
!overridesObjectMethod(origin, sym) &&
(interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
}
}
// <editor-fold defaultstate="collapsed" desc="isSubtype">
/**
* Is t an unchecked subtype of s?
*/