-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
Resolve.java
5044 lines (4540 loc) · 215 KB
/
Resolve.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) 1999, 2022, 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.comp;
import com.sun.tools.javac.api.Formattable.LocalizedString;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.comp.Attr.ResultInfo;
import com.sun.tools.javac.comp.Check.CheckContext;
import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
import com.sun.tools.javac.comp.DeferredAttr.DeferredType;
import com.sun.tools.javac.comp.Resolve.MethodResolutionContext.Candidate;
import com.sun.tools.javac.comp.Resolve.MethodResolutionDiagHelper.Template;
import com.sun.tools.javac.comp.Resolve.ReferenceLookupResult.StaticKind;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.DefinedBy.Api;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.lang.model.element.ElementVisitor;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Flags.BLOCK;
import static com.sun.tools.javac.code.Flags.STATIC;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.comp.Resolve.MethodResolutionPhase.*;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import static com.sun.tools.javac.util.Iterators.createCompoundIterator;
/** Helper class for name resolution, used mostly by the attribution phase.
*
* <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 Resolve {
protected static final Context.Key<Resolve> resolveKey = new Context.Key<>();
Names names;
Log log;
Symtab syms;
Attr attr;
AttrRecover attrRecover;
DeferredAttr deferredAttr;
Check chk;
Infer infer;
ClassFinder finder;
ModuleFinder moduleFinder;
Types types;
JCDiagnostic.Factory diags;
public final boolean allowFunctionalInterfaceMostSpecific;
public final boolean allowModules;
public final boolean allowRecords;
public final boolean checkVarargsAccessAfterResolution;
private final boolean compactMethodDiags;
private final boolean allowLocalVariableTypeInference;
private final boolean allowYieldStatement;
final EnumSet<VerboseResolutionMode> verboseResolutionMode;
final boolean dumpMethodReferenceSearchResults;
WriteableScope polymorphicSignatureScope;
protected Resolve(Context context) {
context.put(resolveKey, this);
syms = Symtab.instance(context);
varNotFound = new SymbolNotFoundError(ABSENT_VAR);
methodNotFound = new SymbolNotFoundError(ABSENT_MTH);
typeNotFound = new SymbolNotFoundError(ABSENT_TYP);
referenceNotFound = ReferenceLookupResult.error(methodNotFound);
names = Names.instance(context);
log = Log.instance(context);
attr = Attr.instance(context);
attrRecover = AttrRecover.instance(context);
deferredAttr = DeferredAttr.instance(context);
chk = Check.instance(context);
infer = Infer.instance(context);
finder = ClassFinder.instance(context);
moduleFinder = ModuleFinder.instance(context);
types = Types.instance(context);
diags = JCDiagnostic.Factory.instance(context);
Preview preview = Preview.instance(context);
Source source = Source.instance(context);
Options options = Options.instance(context);
compactMethodDiags = options.isSet(Option.XDIAGS, "compact") ||
options.isUnset(Option.XDIAGS) && options.isUnset("rawDiagnostics");
verboseResolutionMode = VerboseResolutionMode.getVerboseResolutionMode(options);
Target target = Target.instance(context);
allowFunctionalInterfaceMostSpecific = Feature.FUNCTIONAL_INTERFACE_MOST_SPECIFIC.allowedInSource(source);
allowLocalVariableTypeInference = Feature.LOCAL_VARIABLE_TYPE_INFERENCE.allowedInSource(source);
allowYieldStatement = Feature.SWITCH_EXPRESSION.allowedInSource(source);
checkVarargsAccessAfterResolution =
Feature.POST_APPLICABILITY_VARARGS_ACCESS_CHECK.allowedInSource(source);
polymorphicSignatureScope = WriteableScope.create(syms.noSymbol);
allowModules = Feature.MODULES.allowedInSource(source);
allowRecords = Feature.RECORDS.allowedInSource(source);
dumpMethodReferenceSearchResults = options.isSet("debug.dumpMethodReferenceSearchResults");
}
/** error symbols, which are returned when resolution fails
*/
private final SymbolNotFoundError varNotFound;
private final SymbolNotFoundError methodNotFound;
private final SymbolNotFoundError typeNotFound;
/** empty reference lookup result */
private final ReferenceLookupResult referenceNotFound;
public static Resolve instance(Context context) {
Resolve instance = context.get(resolveKey);
if (instance == null)
instance = new Resolve(context);
return instance;
}
private static Symbol bestOf(Symbol s1,
Symbol s2) {
return s1.kind.betterThan(s2.kind) ? s1 : s2;
}
// <editor-fold defaultstate="collapsed" desc="Verbose resolution diagnostics support">
enum VerboseResolutionMode {
SUCCESS("success"),
FAILURE("failure"),
APPLICABLE("applicable"),
INAPPLICABLE("inapplicable"),
DEFERRED_INST("deferred-inference"),
PREDEF("predef"),
OBJECT_INIT("object-init"),
INTERNAL("internal");
final String opt;
private VerboseResolutionMode(String opt) {
this.opt = opt;
}
static EnumSet<VerboseResolutionMode> getVerboseResolutionMode(Options opts) {
String s = opts.get("debug.verboseResolution");
EnumSet<VerboseResolutionMode> res = EnumSet.noneOf(VerboseResolutionMode.class);
if (s == null) return res;
if (s.contains("all")) {
res = EnumSet.allOf(VerboseResolutionMode.class);
}
Collection<String> args = Arrays.asList(s.split(","));
for (VerboseResolutionMode mode : values()) {
if (args.contains(mode.opt)) {
res.add(mode);
} else if (args.contains("-" + mode.opt)) {
res.remove(mode);
}
}
return res;
}
}
void reportVerboseResolutionDiagnostic(DiagnosticPosition dpos, Name name, Type site,
List<Type> argtypes, List<Type> typeargtypes, Symbol bestSoFar) {
boolean success = !bestSoFar.kind.isResolutionError();
if (success && !verboseResolutionMode.contains(VerboseResolutionMode.SUCCESS)) {
return;
} else if (!success && !verboseResolutionMode.contains(VerboseResolutionMode.FAILURE)) {
return;
}
if (bestSoFar.name == names.init &&
bestSoFar.owner == syms.objectType.tsym &&
!verboseResolutionMode.contains(VerboseResolutionMode.OBJECT_INIT)) {
return; //skip diags for Object constructor resolution
} else if (site == syms.predefClass.type &&
!verboseResolutionMode.contains(VerboseResolutionMode.PREDEF)) {
return; //skip spurious diags for predef symbols (i.e. operators)
} else if (currentResolutionContext.internalResolution &&
!verboseResolutionMode.contains(VerboseResolutionMode.INTERNAL)) {
return;
}
int pos = 0;
int mostSpecificPos = -1;
ListBuffer<JCDiagnostic> subDiags = new ListBuffer<>();
for (Candidate c : currentResolutionContext.candidates) {
if (currentResolutionContext.step != c.step ||
(c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.APPLICABLE)) ||
(!c.isApplicable() && !verboseResolutionMode.contains(VerboseResolutionMode.INAPPLICABLE))) {
continue;
} else {
subDiags.append(c.isApplicable() ?
getVerboseApplicableCandidateDiag(pos, c.sym, c.mtype) :
getVerboseInapplicableCandidateDiag(pos, c.sym, c.details));
if (c.sym == bestSoFar)
mostSpecificPos = pos;
pos++;
}
}
String key = success ? "verbose.resolve.multi" : "verbose.resolve.multi.1";
List<Type> argtypes2 = argtypes.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, bestSoFar, currentResolutionContext.step));
JCDiagnostic main = diags.note(log.currentSource(), dpos, key, name,
site.tsym, mostSpecificPos, currentResolutionContext.step,
methodArguments(argtypes2),
methodArguments(typeargtypes));
JCDiagnostic d = new JCDiagnostic.MultilineDiagnostic(main, subDiags.toList());
log.report(d);
}
JCDiagnostic getVerboseApplicableCandidateDiag(int pos, Symbol sym, Type inst) {
JCDiagnostic subDiag = null;
if (sym.type.hasTag(FORALL)) {
subDiag = diags.fragment(Fragments.PartialInstSig(inst));
}
String key = subDiag == null ?
"applicable.method.found" :
"applicable.method.found.1";
return diags.fragment(key, pos, sym, subDiag);
}
JCDiagnostic getVerboseInapplicableCandidateDiag(int pos, Symbol sym, JCDiagnostic subDiag) {
return diags.fragment(Fragments.NotApplicableMethodFound(pos, sym, subDiag));
}
// </editor-fold>
/* ************************************************************************
* Identifier resolution
*************************************************************************/
/** An environment is "static" if its static level is greater than
* the one of its outer environment
*/
protected static boolean isStatic(Env<AttrContext> env) {
return env.outer != null && env.info.staticLevel > env.outer.info.staticLevel;
}
/** An environment is an "initializer" if it is a constructor or
* an instance initializer.
*/
static boolean isInitializer(Env<AttrContext> env) {
Symbol owner = env.info.scope.owner;
return owner.isConstructor() ||
owner.owner.kind == TYP &&
(owner.kind == VAR ||
owner.kind == MTH && (owner.flags() & BLOCK) != 0) &&
(owner.flags() & STATIC) == 0;
}
/** Is class accessible in given environment?
* @param env The current environment.
* @param c The class whose accessibility is checked.
*/
public boolean isAccessible(Env<AttrContext> env, TypeSymbol c) {
return isAccessible(env, c, false);
}
public boolean isAccessible(Env<AttrContext> env, TypeSymbol c, boolean checkInner) {
/* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor
to refer to an inaccessible type
*/
if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)
return true;
if (env.info.visitingServiceImplementation &&
env.toplevel.modle == c.packge().modle) {
return true;
}
boolean isAccessible = false;
switch ((short)(c.flags() & AccessFlags)) {
case PRIVATE:
isAccessible =
env.enclClass.sym.outermostClass() ==
c.owner.outermostClass();
break;
case 0:
isAccessible =
env.toplevel.packge == c.owner // fast special case
||
env.toplevel.packge == c.packge();
break;
default: // error recovery
isAccessible = true;
break;
case PUBLIC:
if (allowModules) {
ModuleSymbol currModule = env.toplevel.modle;
currModule.complete();
PackageSymbol p = c.packge();
isAccessible =
currModule == p.modle ||
currModule.visiblePackages.get(p.fullname) == p ||
p == syms.rootPackage ||
(p.modle == syms.unnamedModule && currModule.readModules.contains(p.modle));
} else {
isAccessible = true;
}
break;
case PROTECTED:
isAccessible =
env.toplevel.packge == c.owner // fast special case
||
env.toplevel.packge == c.packge()
||
isInnerSubClass(env.enclClass.sym, c.owner)
||
env.info.allowProtectedAccess;
break;
}
return (checkInner == false || c.type.getEnclosingType() == Type.noType) ?
isAccessible :
isAccessible && isAccessible(env, c.type.getEnclosingType(), checkInner);
}
//where
/** Is given class a subclass of given base class, or an inner class
* of a subclass?
* Return null if no such class exists.
* @param c The class which is the subclass or is contained in it.
* @param base The base class
*/
private boolean isInnerSubClass(ClassSymbol c, Symbol base) {
while (c != null && !c.isSubClass(base, types)) {
c = c.owner.enclClass();
}
return c != null;
}
boolean isAccessible(Env<AttrContext> env, Type t) {
return isAccessible(env, t, false);
}
boolean isAccessible(Env<AttrContext> env, Type t, boolean checkInner) {
if (t.hasTag(ARRAY)) {
return isAccessible(env, types.cvarUpperBound(types.elemtype(t)));
} else if (t.isUnion()) {
return StreamSupport.stream(((UnionClassType) t).getAlternativeTypes().spliterator(), false)
.allMatch(alternative -> isAccessible(env, alternative.tsym, checkInner));
} else {
return isAccessible(env, t.tsym, checkInner);
}
}
/** Is symbol accessible as a member of given type in given environment?
* @param env The current environment.
* @param site The type of which the tested symbol is regarded
* as a member.
* @param sym The symbol.
*/
public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym) {
return isAccessible(env, site, sym, false);
}
public boolean isAccessible(Env<AttrContext> env, Type site, Symbol sym, boolean checkInner) {
if (sym.name == names.init && sym.owner != site.tsym) return false;
/* 15.9.5.1: Note that it is possible for the signature of the anonymous constructor
to refer to an inaccessible type
*/
if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)
return true;
if (env.info.visitingServiceImplementation &&
env.toplevel.modle == sym.packge().modle) {
return true;
}
switch ((short)(sym.flags() & AccessFlags)) {
case PRIVATE:
return
(env.enclClass.sym == sym.owner // fast special case
||
env.enclClass.sym.outermostClass() ==
sym.owner.outermostClass())
&&
sym.isInheritedIn(site.tsym, types);
case 0:
return
(env.toplevel.packge == sym.owner.owner // fast special case
||
env.toplevel.packge == sym.packge())
&&
isAccessible(env, site, checkInner)
&&
sym.isInheritedIn(site.tsym, types)
&&
notOverriddenIn(site, sym);
case PROTECTED:
return
(env.toplevel.packge == sym.owner.owner // fast special case
||
env.toplevel.packge == sym.packge()
||
isProtectedAccessible(sym, env.enclClass.sym, site)
||
// OK to select instance method or field from 'super' or type name
// (but type names should be disallowed elsewhere!)
env.info.selectSuper && (sym.flags() & STATIC) == 0 && sym.kind != TYP)
&&
isAccessible(env, site, checkInner)
&&
notOverriddenIn(site, sym);
default: // this case includes erroneous combinations as well
return isAccessible(env, site, checkInner) && notOverriddenIn(site, sym);
}
}
//where
/* `sym' is accessible only if not overridden by
* another symbol which is a member of `site'
* (because, if it is overridden, `sym' is not strictly
* speaking a member of `site'). A polymorphic signature method
* cannot be overridden (e.g. MH.invokeExact(Object[])).
*/
private boolean notOverriddenIn(Type site, Symbol sym) {
if (sym.kind != MTH || sym.isConstructor() || sym.isStatic())
return true;
else {
Symbol s2 = ((MethodSymbol)sym).implementation(site.tsym, types, true);
return (s2 == null || s2 == sym || sym.owner == s2.owner || (sym.owner.isInterface() && s2.owner == syms.objectType.tsym) ||
!types.isSubSignature(types.memberType(site, s2), types.memberType(site, sym)));
}
}
//where
/** Is given protected symbol accessible if it is selected from given site
* and the selection takes place in given class?
* @param sym The symbol with protected access
* @param c The class where the access takes place
* @site The type of the qualifier
*/
private
boolean isProtectedAccessible(Symbol sym, ClassSymbol c, Type site) {
Type newSite = site.hasTag(TYPEVAR) ? site.getUpperBound() : site;
while (c != null &&
!(c.isSubClass(sym.owner, types) &&
(c.flags() & INTERFACE) == 0 &&
// In JLS 2e 6.6.2.1, the subclass restriction applies
// only to instance fields and methods -- types are excluded
// regardless of whether they are declared 'static' or not.
((sym.flags() & STATIC) != 0 || sym.kind == TYP || newSite.tsym.isSubClass(c, types))))
c = c.owner.enclClass();
return c != null;
}
/**
* Performs a recursive scan of a type looking for accessibility problems
* from current attribution environment
*/
void checkAccessibleType(Env<AttrContext> env, Type t) {
accessibilityChecker.visit(t, env);
}
/**
* Accessibility type-visitor
*/
Types.SimpleVisitor<Void, Env<AttrContext>> accessibilityChecker =
new Types.SimpleVisitor<Void, Env<AttrContext>>() {
void visit(List<Type> ts, Env<AttrContext> env) {
for (Type t : ts) {
visit(t, env);
}
}
public Void visitType(Type t, Env<AttrContext> env) {
return null;
}
@Override
public Void visitArrayType(ArrayType t, Env<AttrContext> env) {
visit(t.elemtype, env);
return null;
}
@Override
public Void visitClassType(ClassType t, Env<AttrContext> env) {
visit(t.getTypeArguments(), env);
if (!isAccessible(env, t, true)) {
accessBase(new AccessError(env, null, t.tsym), env.tree.pos(), env.enclClass.sym, t, t.tsym.name, true);
}
return null;
}
@Override
public Void visitWildcardType(WildcardType t, Env<AttrContext> env) {
visit(t.type, env);
return null;
}
@Override
public Void visitMethodType(MethodType t, Env<AttrContext> env) {
visit(t.getParameterTypes(), env);
visit(t.getReturnType(), env);
visit(t.getThrownTypes(), env);
return null;
}
};
/** Try to instantiate the type of a method so that it fits
* given type arguments and argument types. If successful, return
* the method's instantiated type, else return null.
* The instantiation will take into account an additional leading
* formal parameter if the method is an instance method seen as a member
* of an under determined site. In this case, we treat site as an additional
* parameter and the parameters of the class containing the method as
* additional type variables that get instantiated.
*
* @param env The current environment
* @param site The type of which the method is a member.
* @param m The method symbol.
* @param argtypes The invocation's given value arguments.
* @param typeargtypes The invocation's given type arguments.
* @param allowBoxing Allow boxing conversions of arguments.
* @param useVarargs Box trailing arguments into an array for varargs.
*/
Type rawInstantiate(Env<AttrContext> env,
Type site,
Symbol m,
ResultInfo resultInfo,
List<Type> argtypes,
List<Type> typeargtypes,
boolean allowBoxing,
boolean useVarargs,
Warner warn) throws Infer.InferenceException {
Type mt = types.memberType(site, m);
// tvars is the list of formal type variables for which type arguments
// need to inferred.
List<Type> tvars = List.nil();
if (typeargtypes == null) typeargtypes = List.nil();
if (!mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
// This is not a polymorphic method, but typeargs are supplied
// which is fine, see JLS 15.12.2.1
} else if (mt.hasTag(FORALL) && typeargtypes.nonEmpty()) {
ForAll pmt = (ForAll) mt;
if (typeargtypes.length() != pmt.tvars.length())
// not enough args
throw new InapplicableMethodException(diags.fragment(Fragments.WrongNumberTypeArgs(Integer.toString(pmt.tvars.length()))));
// Check type arguments are within bounds
List<Type> formals = pmt.tvars;
List<Type> actuals = typeargtypes;
while (formals.nonEmpty() && actuals.nonEmpty()) {
List<Type> bounds = types.subst(types.getBounds((TypeVar)formals.head),
pmt.tvars, typeargtypes);
for (; bounds.nonEmpty(); bounds = bounds.tail) {
if (!types.isSubtypeUnchecked(actuals.head, bounds.head, warn)) {
throw new InapplicableMethodException(diags.fragment(Fragments.ExplicitParamDoNotConformToBounds(actuals.head, bounds)));
}
}
formals = formals.tail;
actuals = actuals.tail;
}
mt = types.subst(pmt.qtype, pmt.tvars, typeargtypes);
} else if (mt.hasTag(FORALL)) {
ForAll pmt = (ForAll) mt;
List<Type> tvars1 = types.newInstances(pmt.tvars);
tvars = tvars.appendList(tvars1);
mt = types.subst(pmt.qtype, pmt.tvars, tvars1);
}
// find out whether we need to go the slow route via infer
boolean instNeeded = tvars.tail != null; /*inlined: tvars.nonEmpty()*/
for (List<Type> l = argtypes;
l.tail != null/*inlined: l.nonEmpty()*/ && !instNeeded;
l = l.tail) {
if (l.head.hasTag(FORALL)) instNeeded = true;
}
if (instNeeded) {
return infer.instantiateMethod(env,
tvars,
(MethodType)mt,
resultInfo,
(MethodSymbol)m,
argtypes,
allowBoxing,
useVarargs,
currentResolutionContext,
warn);
}
DeferredAttr.DeferredAttrContext dc = currentResolutionContext.deferredAttrContext(m, infer.emptyContext, resultInfo, warn);
currentResolutionContext.methodCheck.argumentsAcceptable(env, dc,
argtypes, mt.getParameterTypes(), warn);
dc.complete();
return mt;
}
Type checkMethod(Env<AttrContext> env,
Type site,
Symbol m,
ResultInfo resultInfo,
List<Type> argtypes,
List<Type> typeargtypes,
Warner warn) {
MethodResolutionContext prevContext = currentResolutionContext;
try {
currentResolutionContext = new MethodResolutionContext();
currentResolutionContext.attrMode = (resultInfo.pt == Infer.anyPoly) ?
AttrMode.SPECULATIVE : DeferredAttr.AttrMode.CHECK;
if (env.tree.hasTag(JCTree.Tag.REFERENCE)) {
//method/constructor references need special check class
//to handle inference variables in 'argtypes' (might happen
//during an unsticking round)
currentResolutionContext.methodCheck =
new MethodReferenceCheck(resultInfo.checkContext.inferenceContext());
}
MethodResolutionPhase step = currentResolutionContext.step = env.info.pendingResolutionPhase;
return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
step.isBoxingRequired(), step.isVarargsRequired(), warn);
}
finally {
currentResolutionContext = prevContext;
}
}
/** Same but returns null instead throwing a NoInstanceException
*/
Type instantiate(Env<AttrContext> env,
Type site,
Symbol m,
ResultInfo resultInfo,
List<Type> argtypes,
List<Type> typeargtypes,
boolean allowBoxing,
boolean useVarargs,
Warner warn) {
try {
return rawInstantiate(env, site, m, resultInfo, argtypes, typeargtypes,
allowBoxing, useVarargs, warn);
} catch (InapplicableMethodException ex) {
return null;
}
}
/**
* This interface defines an entry point that should be used to perform a
* method check. A method check usually consist in determining as to whether
* a set of types (actuals) is compatible with another set of types (formals).
* Since the notion of compatibility can vary depending on the circumstances,
* this interfaces allows to easily add new pluggable method check routines.
*/
interface MethodCheck {
/**
* Main method check routine. A method check usually consist in determining
* as to whether a set of types (actuals) is compatible with another set of
* types (formals). If an incompatibility is found, an unchecked exception
* is assumed to be thrown.
*/
void argumentsAcceptable(Env<AttrContext> env,
DeferredAttrContext deferredAttrContext,
List<Type> argtypes,
List<Type> formals,
Warner warn);
/**
* Retrieve the method check object that will be used during a
* most specific check.
*/
MethodCheck mostSpecificCheck(List<Type> actuals);
}
/**
* Helper enum defining all method check diagnostics (used by resolveMethodCheck).
*/
enum MethodCheckDiag {
/**
* Actuals and formals differs in length.
*/
ARITY_MISMATCH("arg.length.mismatch", "infer.arg.length.mismatch"),
/**
* An actual is incompatible with a formal.
*/
ARG_MISMATCH("no.conforming.assignment.exists", "infer.no.conforming.assignment.exists"),
/**
* An actual is incompatible with the varargs element type.
*/
VARARG_MISMATCH("varargs.argument.mismatch", "infer.varargs.argument.mismatch"),
/**
* The varargs element type is inaccessible.
*/
INACCESSIBLE_VARARGS("inaccessible.varargs.type", "inaccessible.varargs.type");
final String basicKey;
final String inferKey;
MethodCheckDiag(String basicKey, String inferKey) {
this.basicKey = basicKey;
this.inferKey = inferKey;
}
String regex() {
return String.format("([a-z]*\\.)*(%s|%s)", basicKey, inferKey);
}
}
/**
* Dummy method check object. All methods are deemed applicable, regardless
* of their formal parameter types.
*/
MethodCheck nilMethodCheck = new MethodCheck() {
public void argumentsAcceptable(Env<AttrContext> env, DeferredAttrContext deferredAttrContext, List<Type> argtypes, List<Type> formals, Warner warn) {
//do nothing - method always applicable regardless of actuals
}
public MethodCheck mostSpecificCheck(List<Type> actuals) {
return this;
}
};
/**
* Base class for 'real' method checks. The class defines the logic for
* iterating through formals and actuals and provides and entry point
* that can be used by subclasses in order to define the actual check logic.
*/
abstract class AbstractMethodCheck implements MethodCheck {
@Override
public void argumentsAcceptable(final Env<AttrContext> env,
DeferredAttrContext deferredAttrContext,
List<Type> argtypes,
List<Type> formals,
Warner warn) {
//should we expand formals?
boolean useVarargs = deferredAttrContext.phase.isVarargsRequired();
JCTree callTree = treeForDiagnostics(env);
List<JCExpression> trees = TreeInfo.args(callTree);
//inference context used during this method check
InferenceContext inferenceContext = deferredAttrContext.inferenceContext;
Type varargsFormal = useVarargs ? formals.last() : null;
if (varargsFormal == null &&
argtypes.size() != formals.size()) {
reportMC(callTree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
}
while (argtypes.nonEmpty() && formals.head != varargsFormal) {
DiagnosticPosition pos = trees != null ? trees.head : null;
checkArg(pos, false, argtypes.head, formals.head, deferredAttrContext, warn);
argtypes = argtypes.tail;
formals = formals.tail;
trees = trees != null ? trees.tail : trees;
}
if (formals.head != varargsFormal) {
reportMC(callTree, MethodCheckDiag.ARITY_MISMATCH, inferenceContext); // not enough args
}
if (useVarargs) {
//note: if applicability check is triggered by most specific test,
//the last argument of a varargs is _not_ an array type (see JLS 15.12.2.5)
final Type elt = types.elemtype(varargsFormal);
while (argtypes.nonEmpty()) {
DiagnosticPosition pos = trees != null ? trees.head : null;
checkArg(pos, true, argtypes.head, elt, deferredAttrContext, warn);
argtypes = argtypes.tail;
trees = trees != null ? trees.tail : trees;
}
}
}
// where
private JCTree treeForDiagnostics(Env<AttrContext> env) {
return env.info.preferredTreeForDiagnostics != null ? env.info.preferredTreeForDiagnostics : env.tree;
}
/**
* Does the actual argument conforms to the corresponding formal?
*/
abstract void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn);
protected void reportMC(DiagnosticPosition pos, MethodCheckDiag diag, InferenceContext inferenceContext, Object... args) {
boolean inferDiag = inferenceContext != infer.emptyContext;
if (inferDiag && (!diag.inferKey.equals(diag.basicKey))) {
Object[] args2 = new Object[args.length + 1];
System.arraycopy(args, 0, args2, 1, args.length);
args2[0] = inferenceContext.inferenceVars();
args = args2;
}
String key = inferDiag ? diag.inferKey : diag.basicKey;
throw inferDiag ?
infer.error(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args)) :
methodCheckFailure.setMessage(diags.create(DiagnosticType.FRAGMENT, log.currentSource(), pos, key, args));
}
/**
* To eliminate the overhead associated with allocating an exception object in such an
* hot execution path, we use flyweight pattern - and share the same exception instance
* across multiple method check failures.
*/
class SharedInapplicableMethodException extends InapplicableMethodException {
private static final long serialVersionUID = 0;
SharedInapplicableMethodException() {
super(null);
}
SharedInapplicableMethodException setMessage(JCDiagnostic details) {
this.diagnostic = details;
return this;
}
}
SharedInapplicableMethodException methodCheckFailure = new SharedInapplicableMethodException();
public MethodCheck mostSpecificCheck(List<Type> actuals) {
return nilMethodCheck;
}
}
/**
* Arity-based method check. A method is applicable if the number of actuals
* supplied conforms to the method signature.
*/
MethodCheck arityMethodCheck = new AbstractMethodCheck() {
@Override
void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
//do nothing - actual always compatible to formals
}
@Override
public String toString() {
return "arityMethodCheck";
}
};
/**
* Main method applicability routine. Given a list of actual types A,
* a list of formal types F, determines whether the types in A are
* compatible (by method invocation conversion) with the types in F.
*
* Since this routine is shared between overload resolution and method
* type-inference, a (possibly empty) inference context is used to convert
* formal types to the corresponding 'undet' form ahead of a compatibility
* check so that constraints can be propagated and collected.
*
* Moreover, if one or more types in A is a deferred type, this routine uses
* DeferredAttr in order to perform deferred attribution. If one or more actual
* deferred types are stuck, they are placed in a queue and revisited later
* after the remainder of the arguments have been seen. If this is not sufficient
* to 'unstuck' the argument, a cyclic inference error is called out.
*
* A method check handler (see above) is used in order to report errors.
*/
MethodCheck resolveMethodCheck = new AbstractMethodCheck() {
@Override
void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
mresult.check(pos, actual);
}
@Override
public void argumentsAcceptable(final Env<AttrContext> env,
DeferredAttrContext deferredAttrContext,
List<Type> argtypes,
List<Type> formals,
Warner warn) {
super.argumentsAcceptable(env, deferredAttrContext, argtypes, formals, warn);
// should we check varargs element type accessibility?
if (deferredAttrContext.phase.isVarargsRequired()) {
if (deferredAttrContext.mode == AttrMode.CHECK || !checkVarargsAccessAfterResolution) {
varargsAccessible(env, types.elemtype(formals.last()), deferredAttrContext.inferenceContext);
}
}
}
/**
* Test that the runtime array element type corresponding to 't' is accessible. 't' should be the
* varargs element type of either the method invocation type signature (after inference completes)
* or the method declaration signature (before inference completes).
*/
private void varargsAccessible(final Env<AttrContext> env, final Type t, final InferenceContext inferenceContext) {
if (inferenceContext.free(t)) {
inferenceContext.addFreeTypeListener(List.of(t),
solvedContext -> varargsAccessible(env, solvedContext.asInstType(t), solvedContext));
} else {
if (!isAccessible(env, types.erasure(t))) {
Symbol location = env.enclClass.sym;
reportMC(env.tree, MethodCheckDiag.INACCESSIBLE_VARARGS, inferenceContext, t, Kinds.kindName(location), location);
}
}
}
private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
MethodCheckDiag methodDiag = varargsCheck ?
MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
@Override
public void report(DiagnosticPosition pos, JCDiagnostic details) {
reportMC(pos, methodDiag, deferredAttrContext.inferenceContext, details);
}
};
return new MethodResultInfo(to, checkContext);
}
@Override
public MethodCheck mostSpecificCheck(List<Type> actuals) {
return new MostSpecificCheck(actuals);
}
@Override
public String toString() {
return "resolveMethodCheck";
}
};
/**
* This class handles method reference applicability checks; since during
* these checks it's sometime possible to have inference variables on
* the actual argument types list, the method applicability check must be
* extended so that inference variables are 'opened' as needed.
*/
class MethodReferenceCheck extends AbstractMethodCheck {
InferenceContext pendingInferenceContext;
MethodReferenceCheck(InferenceContext pendingInferenceContext) {
this.pendingInferenceContext = pendingInferenceContext;
}
@Override
void checkArg(DiagnosticPosition pos, boolean varargs, Type actual, Type formal, DeferredAttrContext deferredAttrContext, Warner warn) {
ResultInfo mresult = methodCheckResult(varargs, formal, deferredAttrContext, warn);
mresult.check(pos, actual);
}
private ResultInfo methodCheckResult(final boolean varargsCheck, Type to,
final DeferredAttr.DeferredAttrContext deferredAttrContext, Warner rsWarner) {
CheckContext checkContext = new MethodCheckContext(!deferredAttrContext.phase.isBoxingRequired(), deferredAttrContext, rsWarner) {
MethodCheckDiag methodDiag = varargsCheck ?
MethodCheckDiag.VARARG_MISMATCH : MethodCheckDiag.ARG_MISMATCH;
@Override
public boolean compatible(Type found, Type req, Warner warn) {
found = pendingInferenceContext.asUndetVar(found);
if (found.hasTag(UNDETVAR) && req.isPrimitive()) {
req = types.boxedClass(req).type;
}
return super.compatible(found, req, warn);
}
@Override