/
LookupEnvironment.java
2321 lines (2169 loc) · 101 KB
/
LookupEnvironment.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
// GROOVY PATCHED
/*******************************************************************************
* Copyright (c) 2000, 2020 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Stephan Herrmann - contributions for
* bug 337868 - [compiler][model] incomplete support for package-info.java when using SearchableEnvironment
* bug 186342 - [compiler][null] Using annotations for null checking
* bug 365531 - [compiler][null] investigate alternative strategy for internally encoding nullness defaults
* bug 392099 - [1.8][compiler][null] Apply null annotation on types for null analysis
* bug 392862 - [1.8][compiler][null] Evaluate null annotations on array types
* bug 392384 - [1.8][compiler][null] Restore nullness info from type annotations in class files
* Bug 392099 - [1.8][compiler][null] Apply null annotation on types for null analysis
* Bug 415291 - [1.8][null] differentiate type incompatibilities due to null annotations
* Bug 392238 - [1.8][compiler][null] Detect semantically invalid null type annotations
* Bug 415850 - [1.8] Ensure RunJDTCoreTests can cope with null annotations enabled
* Bug 415043 - [1.8][null] Follow-up re null type annotations after bug 392099
* Bug 416183 - [1.8][compiler][null] Overload resolution fails with null annotations
* Bug 416307 - [1.8][compiler][null] subclass with type parameter substitution confuses null checking
* Bug 417295 - [1.8[[null] Massage type annotated null analysis to gel well with deep encoded type bindings.
* Bug 416190 - [1.8][null] detect incompatible overrides due to null type annotations
* Bug 424624 - [1.8][null] if a static-object with annotation @NonNull is used, a warning is shown
* Bug 438458 - [1.8][null] clean up handling of null type annotations wrt type variables
* Bug 439516 - [1.8][null] NonNullByDefault wrongly applied to implicit type bound of binary type
* Bug 434602 - Possible error with inferred null annotations leading to contradictory null annotations
* Bug 435805 - [1.8][compiler][null] Java 8 compiler does not recognize declaration style null annotations
* Bug 453475 - [1.8][null] Contradictory null annotations (4.5 M3 edition)
* Bug 457079 - Regression: type inference
* Bug 440477 - [null] Infrastructure for feeding external annotations into compilation
* Bug 455180 - IllegalStateException in AnnotatableTypeSystem.getRawType
* Bug 470467 - [null] Nullness of special Enum methods not detected from .class file
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.lookup;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ClassFilePool;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
import org.eclipse.jdt.internal.compiler.ast.Wildcard;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.eclipse.jdt.internal.compiler.util.HashtableOfModule;
import org.eclipse.jdt.internal.compiler.util.HashtableOfPackage;
import org.eclipse.jdt.internal.compiler.util.SimpleLookupTable;
@SuppressWarnings({"rawtypes", "unchecked"})
public class LookupEnvironment implements ProblemReasons, TypeConstants {
/**
* Map from typeBinding -> accessRestriction rule
*/
private Map accessRestrictions;
ImportBinding[] defaultImports; // ROOT_ONLY
/**
* The root environment driving the current compilation.
* Other mutable fields in this class marked as ROOT_ONLY must always be accessed from the root environment.
* It is assumed that external clients only know the root environment, whereas calls internally in the compiler
* have to delegate to root where necessary.
* Immutable fields with "global" semantics are SHARED among environments via aliasing.
*/
public final LookupEnvironment root;
public ModuleBinding UnNamedModule;
public ModuleBinding JavaBaseModule;
public ModuleBinding module;
public PlainPackageBinding defaultPackage;
/** All visible toplevel packages, i.e. observable packages associated with modules read by the current module. */
HashtableOfPackage knownPackages;
private int lastCompletedUnitIndex = -1; // ROOT_ONLY
private int lastUnitIndex = -1; // ROOT_ONLY
TypeSystem typeSystem; // SHARED
public INameEnvironment nameEnvironment; // SHARED
public CompilerOptions globalOptions; // SHARED
public ProblemReporter problemReporter; // SHARED
public ClassFilePool classFilePool; // SHARED
// indicate in which step on the compilation we are.
// step 1 : build the reference binding
// step 2 : conect the hierarchy (connect bindings)
// step 3 : build fields and method bindings.
private int stepCompleted; // ROOT_ONLY
public ITypeRequestor typeRequestor; // SHARED
private SimpleLookupTable uniqueParameterizedGenericMethodBindings;
// key is a string with the method selector value is an array of method bindings
private SimpleLookupTable uniquePolymorphicMethodBindings;
private SimpleLookupTable uniqueGetClassMethodBinding; // https://bugs.eclipse.org/bugs/show_bug.cgi?id=300734
boolean useModuleSystem; // true when compliance >= 9 and nameEnvironment is module aware
// key is a string with the module name value is a module binding
public HashtableOfModule knownModules; // SHARED
public CompilationUnitDeclaration unitBeingCompleted = null; // only set while completing units -- ROOT_ONLY
public Object missingClassFileLocation = null; // only set when resolving certain references, to help locating problems
private CompilationUnitDeclaration[] units = new CompilationUnitDeclaration[4]; // ROOT_ONLY
private MethodVerifier verifier;
private ArrayList missingTypes;
Set<SourceTypeBinding> typesBeingConnected; // SHARED
public boolean isProcessingAnnotations = false; // ROOT_ONLY
public boolean mayTolerateMissingType = false;
PackageBinding nullableAnnotationPackage; // the package supposed to contain the Nullable annotation type
PackageBinding nonnullAnnotationPackage; // the package supposed to contain the NonNull annotation type
PackageBinding nonnullByDefaultAnnotationPackage; // the package supposed to contain the NonNullByDefault annotation type
AnnotationBinding nonNullAnnotation;
AnnotationBinding nullableAnnotation;
Map<String,Integer> allNullAnnotations = null;
final List<MethodBinding> deferredEnumMethods; // SHARED: during early initialization we cannot mark Enum-methods as nonnull.
/** Global access to the outermost active inference context as the universe for inference variable interning. */
InferenceContext18 currentInferenceContext;
/**
* Flag that should be set during annotation traversal or similar runs
* to prevent caching of failures regarding imports of yet to be generated classes.
*/
public boolean suppressImportErrors; // per module
public String moduleVersion; // ROOT_ONLY
final static int BUILD_FIELDS_AND_METHODS = 4;
final static int BUILD_TYPE_HIERARCHY = 1;
final static int CHECK_AND_SET_IMPORTS = 2;
final static int CONNECT_TYPE_HIERARCHY = 3;
static final ProblemPackageBinding TheNotFoundPackage = new ProblemPackageBinding(CharOperation.NO_CHAR, NotFound, null/*not perfect*/);
static final ProblemReferenceBinding TheNotFoundType = new ProblemReferenceBinding(CharOperation.NO_CHAR_CHAR, null, NotFound);
static final ModuleBinding TheNotFoundModule = new ModuleBinding(CharOperation.NO_CHAR);
/** Construct the root LookupEnvironment, corresponding to the UnNamedModule. */
public LookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions globalOptions, ProblemReporter problemReporter, INameEnvironment nameEnvironment) {
this.root = this;
this.UnNamedModule = new ModuleBinding.UnNamedModule(this);
this.module = this.UnNamedModule;
this.typeRequestor = typeRequestor;
this.globalOptions = globalOptions;
this.problemReporter = problemReporter;
this.defaultPackage = new PlainPackageBinding(this); // assume the default package always exists
this.defaultImports = null;
this.nameEnvironment = nameEnvironment;
this.knownPackages = new HashtableOfPackage();
this.uniqueParameterizedGenericMethodBindings = new SimpleLookupTable(3);
this.uniquePolymorphicMethodBindings = new SimpleLookupTable(3);
this.missingTypes = null;
this.accessRestrictions = new HashMap(3);
this.classFilePool = ClassFilePool.newInstance();
this.typesBeingConnected = new HashSet<>();
this.deferredEnumMethods = new ArrayList<>();
this.typeSystem = this.globalOptions.sourceLevel >= ClassFileConstants.JDK1_8 && this.globalOptions.storeAnnotations ? new AnnotatableTypeSystem(this) : new TypeSystem(this);
this.knownModules = new HashtableOfModule();
this.useModuleSystem = nameEnvironment instanceof IModuleAwareNameEnvironment && globalOptions.complianceLevel >= ClassFileConstants.JDK9;
this.resolutionListeners = new IQualifiedTypeResolutionListener[0];
}
/** Construct a specific LookupEnvironment, corresponding to the given module. */
LookupEnvironment(LookupEnvironment rootEnv, ModuleBinding module) {
this.root = rootEnv;
this.UnNamedModule = rootEnv.UnNamedModule;
this.module = module;
this.typeRequestor = rootEnv.typeRequestor;
this.globalOptions = rootEnv.globalOptions;
this.problemReporter = rootEnv.problemReporter;
this.defaultPackage = new PlainPackageBinding(this); // assume the default package always exists
this.defaultImports = null;
this.nameEnvironment = rootEnv.nameEnvironment;
this.knownPackages = new HashtableOfPackage();
this.uniqueParameterizedGenericMethodBindings = new SimpleLookupTable(3);
this.uniquePolymorphicMethodBindings = new SimpleLookupTable(3);
this.missingTypes = null;
this.accessRestrictions = new HashMap(3);
this.classFilePool = rootEnv.classFilePool;
this.typesBeingConnected = rootEnv.typesBeingConnected;
this.deferredEnumMethods = rootEnv.deferredEnumMethods;
this.typeSystem = rootEnv.typeSystem;
// knownModules is unused in specific LookupEnvironments
this.useModuleSystem = rootEnv.useModuleSystem;
}
// NOTE: only for resolving!
public ModuleBinding getModule(char[] name) {
if (this.root != this)
return this.root.getModule(name);
if (name == null || name == ModuleBinding.UNNAMED || CharOperation.equals(name, ModuleBinding.ALL_UNNAMED))
return this.UnNamedModule;
ModuleBinding moduleBinding = this.knownModules.get(name);
if (moduleBinding == null) {
if (this.useModuleSystem) {
IModule mod = ((IModuleAwareNameEnvironment) this.nameEnvironment).getModule(name);
if (mod != null) {
this.typeRequestor.accept(mod, this);
moduleBinding = this.root.knownModules.get(name);
}
} else
return this.UnNamedModule;
}
return moduleBinding;
}
/**
* Ask the name environment for a type which corresponds to the compoundName.
* Answer null if the name cannot be found.
*/
public ReferenceBinding askForType(char[][] compoundName, /*@NonNull*/ModuleBinding clientModule) {
assert clientModule != null : "lookup needs a module"; //$NON-NLS-1$
NameEnvironmentAnswer[] answers = null;
if (this.useModuleSystem) {
IModuleAwareNameEnvironment moduleEnv = (IModuleAwareNameEnvironment) this.nameEnvironment;
answers = askForTypeFromModules(clientModule, clientModule.getAllRequiredModules(),
mod -> moduleEnv.findType(compoundName, mod.nameForLookup()));
} else {
NameEnvironmentAnswer answer = this.nameEnvironment.findType(compoundName);
if (answer != null) {
answer.moduleBinding = this.module;
answers = new NameEnvironmentAnswer[] { answer };
}
}
if (answers == null)
return null;
ReferenceBinding candidate = null;
for (NameEnvironmentAnswer answer : answers) {
if (answer == null) continue;
ModuleBinding answerModule = answer.moduleBinding != null ? answer.moduleBinding : this.UnNamedModule;
if (answer.isBinaryType()) {
// the type was found as a .class file
PackageBinding pkg = answerModule.environment.computePackageFrom(compoundName, false /* valid pkg */);
this.typeRequestor.accept(answer.getBinaryType(), pkg, answer.getAccessRestriction());
ReferenceBinding binding = pkg.getType0(compoundName[compoundName.length - 1]);
if (binding instanceof BinaryTypeBinding) {
((BinaryTypeBinding) binding).module = answerModule;
if (pkg.enclosingModule == null)
pkg.enclosingModule = answerModule;
}
} else if (answer.isCompilationUnit()) {
// the type was found as a .java file, try to build it then search the cache
this.typeRequestor.accept(answer.getCompilationUnit(), answer.getAccessRestriction());
} else if (answer.isSourceType()) {
// the type was found as a source model
PackageBinding pkg = answerModule.environment.computePackageFrom(compoundName, false /* valid pkg */);
this.typeRequestor.accept(answer.getSourceTypes(), pkg, answer.getAccessRestriction());
ReferenceBinding binding = pkg.getType0(compoundName[compoundName.length - 1]);
if (binding instanceof SourceTypeBinding) {
((SourceTypeBinding) binding).module = answerModule;
if (pkg.enclosingModule == null)
pkg.enclosingModule = answerModule;
}
}
candidate = combine(candidate, answerModule.environment.getCachedType(compoundName), clientModule);
}
return candidate;
}
/* Ask the oracle for a type named name in the packageBinding.
* Answer null if the name cannot be found.
*/
ReferenceBinding askForType(PackageBinding packageBinding, char[] name, ModuleBinding clientModule) {
assert clientModule != null : "lookup needs a module"; //$NON-NLS-1$
if (packageBinding == null) {
packageBinding = this.defaultPackage;
}
NameEnvironmentAnswer[] answers = null;
if (this.useModuleSystem) {
IModuleAwareNameEnvironment moduleEnv = (IModuleAwareNameEnvironment) this.nameEnvironment;
final PackageBinding pack = packageBinding;
// leverage module information from the (split?) package as to prefer NotAccessible over NotFound:
answers = askForTypeFromModules(null, packageBinding.getDeclaringModules(),
mod -> fromSplitPackageOrOracle(moduleEnv, mod, pack, name));
} else {
NameEnvironmentAnswer answer = this.nameEnvironment.findType(name, packageBinding.compoundName);
if (answer != null) {
answer.moduleBinding = this.module;
answers = new NameEnvironmentAnswer[] { answer };
}
}
if (answers == null)
return null;
ReferenceBinding candidate = null;
for (NameEnvironmentAnswer answer : answers) {
if (answer == null) continue;
if (candidate != null && candidate.problemId() == ProblemReasons.Ambiguous)
return candidate; // saw enough
ModuleBinding answerModule = answer.moduleBinding != null ? answer.moduleBinding : this.UnNamedModule;
PackageBinding answerPackage = packageBinding;
if (answerModule != null) {
if (!answerPackage.isDeclaredIn(answerModule))
continue; // this answer is not reachable via the packageBinding
answerPackage = answerPackage.getIncarnation(answerModule);
}
if (answer.isResolvedBinding()) {
candidate = combine(candidate, answer.getResolvedBinding(), clientModule);
continue;
} else if (answer.isBinaryType()) {
// the type was found as a .class file
this.typeRequestor.accept(answer.getBinaryType(), answerPackage, answer.getAccessRestriction());
ReferenceBinding binding = answerPackage.getType0(name);
if (binding instanceof BinaryTypeBinding) {
((BinaryTypeBinding) binding).module = answerModule;
}
} else if (answer.isCompilationUnit()) {
// the type was found as a .java file, try to build it then search the cache
try {
this.typeRequestor.accept(answer.getCompilationUnit(), answer.getAccessRestriction());
} catch (AbortCompilation abort) {
if (CharOperation.equals(name, TypeConstants.PACKAGE_INFO_NAME))
return null; // silently, requestor may not be able to handle compilation units (HierarchyResolver)
throw abort;
}
} else if (answer.isSourceType()) {
// the type was found as a source model
this.typeRequestor.accept(answer.getSourceTypes(), answerPackage, answer.getAccessRestriction());
ReferenceBinding binding = answerPackage.getType0(name);
if (binding instanceof SourceTypeBinding) {
((SourceTypeBinding) binding).module = answerModule;
}
String externalAnnotationPath = answer.getExternalAnnotationPath();
if (externalAnnotationPath != null && this.globalOptions.isAnnotationBasedNullAnalysisEnabled && binding instanceof SourceTypeBinding) {
ExternalAnnotationSuperimposer.apply((SourceTypeBinding) binding, externalAnnotationPath);
}
candidate = combine(candidate, binding, clientModule);
continue;
}
candidate = combine(candidate, answerPackage.getType0(name), clientModule);
}
return candidate;
}
/** Combine up-to two candidate types. If both types are present let accessibility from the given clientModule decide. */
private ReferenceBinding combine(ReferenceBinding one, ReferenceBinding two, ModuleBinding clientModule) {
if (one == null) return two;
if (two == null) return one;
if (one.fPackage == null || !clientModule.canAccess(one.fPackage)) return two;
if (two.fPackage == null || !clientModule.canAccess(two.fPackage)) return one;
if (one == two) return one; //$IDENTITY-COMPARISON$
return new ProblemReferenceBinding(one.compoundName, one, ProblemReasons.Ambiguous); // TODO(SHMOD): use a new problem ID
}
/** Collect answers from the oracle concerning the given clientModule (if present) and each of a set of other modules. */
private NameEnvironmentAnswer[] askForTypeFromModules(ModuleBinding clientModule, ModuleBinding[] otherModules,
Function<ModuleBinding,NameEnvironmentAnswer> oracle)
{
if (clientModule != null && clientModule.nameForLookup().length == 0) {
NameEnvironmentAnswer answer = oracle.apply(clientModule);
if (answer != null)
answer.moduleBinding = this.root.getModuleFromAnswer(answer);
return new NameEnvironmentAnswer[] { answer };
} else {
boolean found = false;
NameEnvironmentAnswer[] answers = null;
if (clientModule != null) {
answers = new NameEnvironmentAnswer[otherModules.length+1];
NameEnvironmentAnswer answer = oracle.apply(clientModule);
if (answer != null) {
answer.moduleBinding = clientModule;
answers[answers.length-1] = answer;
found = true;
}
} else {
answers = new NameEnvironmentAnswer[otherModules.length];
}
for (int i = 0; i < otherModules.length; i++) {
NameEnvironmentAnswer answer = oracle.apply(otherModules[i]);
if (answer != null) {
if (answer.moduleBinding == null) {
char[] nameFromAnswer = answer.moduleName();
if (CharOperation.equals(nameFromAnswer, otherModules[i].moduleName)) {
answer.moduleBinding = otherModules[i];
} else {
answer.moduleBinding = getModule(nameFromAnswer);
}
}
answers[i] = answer;
found = true;
}
}
return found ? answers : null;
}
}
/** First check for a known type in a split package and otherwise ask the oracle. */
private static NameEnvironmentAnswer fromSplitPackageOrOracle(IModuleAwareNameEnvironment moduleEnv, ModuleBinding module,
PackageBinding packageBinding, char[] name)
{
if (packageBinding instanceof SplitPackageBinding) {
// when asking a split package getType0() we may have answered null in case of ambiguity (not knowing the module context).
// now check if the module-incarnation of the package has the type:
// (needed because the moduleEnv will not answer initial types).
ReferenceBinding binding = ((SplitPackageBinding) packageBinding).getType0ForModule(module, name);
if (binding != null && binding.isValidBinding()) {
if (binding instanceof UnresolvedReferenceBinding)
binding = ((UnresolvedReferenceBinding) binding).resolve(module.environment, false);
if (binding.isValidBinding())
return new NameEnvironmentAnswer(binding, module);
}
}
return moduleEnv.findType(name, packageBinding.compoundName, module.nameForLookup());
}
private ModuleBinding getModuleFromAnswer(NameEnvironmentAnswer answer) {
char[] moduleName = answer.moduleName();
if (moduleName != null) {
ModuleBinding moduleBinding;
if (!this.useModuleSystem || moduleName == ModuleBinding.UNNAMED) {
moduleBinding = this.UnNamedModule;
} else {
moduleBinding = this.knownModules.get(moduleName);
if (moduleBinding == null && this.nameEnvironment instanceof IModuleAwareNameEnvironment) {
IModule iModule = ((IModuleAwareNameEnvironment) this.nameEnvironment).getModule(moduleName);
try {
this.typeRequestor.accept(iModule, this);
moduleBinding = this.knownModules.get(moduleName);
} catch (NullPointerException e) {
System.err.println("Bug 529367: moduleName: " + new String(moduleName) + "iModule null" + //$NON-NLS-1$ //$NON-NLS-2$
(iModule == null ? "true" : "false")); //$NON-NLS-1$ //$NON-NLS-2$]
throw e;
}
}
}
return moduleBinding;
}
return null;
}
public boolean canTypeBeAccessed(SourceTypeBinding binding, Scope scope) {
ModuleBinding client = scope.module();
return client.canAccess(binding.fPackage);
}
/* Create the initial type bindings for the compilation unit.
*
* See completeTypeBindings() for a description of the remaining steps
*
* NOTE: This method can be called multiple times as additional source files are needed
*/
public void buildTypeBindings(CompilationUnitDeclaration unit, AccessRestriction accessRestriction) {
CompilationUnitScope scope;
ModuleBinding unitModule = null;
if (unit.moduleDeclaration != null) {
char[] moduleName = unit.moduleDeclaration.moduleName;
scope = new CompilationUnitScope(unit, this.globalOptions);
unitModule = unit.moduleDeclaration.setBinding(new SourceModuleBinding(moduleName, scope, this.root));
} else {
unitModule = unit.module(this);
// GROOVY edit
//scope = new CompilationUnitScope(unit, unitModule != null ? unitModule.environment : this);
scope = unit.buildCompilationUnitScope(unitModule != null ? unitModule.environment : this);
// GROOVY end
}
scope.buildTypeBindings(accessRestriction);
LookupEnvironment rootEnv = this.root;
int unitsLength = rootEnv.units.length;
if (++rootEnv.lastUnitIndex >= unitsLength)
System.arraycopy(rootEnv.units, 0, rootEnv.units = new CompilationUnitDeclaration[2 * unitsLength], 0, unitsLength);
rootEnv.units[rootEnv.lastUnitIndex] = unit;
}
/* Cache the binary type since we know it is needed during this compile.
*
* Answer the created BinaryTypeBinding or null if the type is already in the cache.
*/
public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType, AccessRestriction accessRestriction) {
return cacheBinaryType(binaryType, true, accessRestriction);
}
/* Cache the binary type since we know it is needed during this compile.
*
* Answer the created BinaryTypeBinding or null if the type is already in the cache.
*/
public BinaryTypeBinding cacheBinaryType(IBinaryType binaryType, boolean needFieldsAndMethods, AccessRestriction accessRestriction) {
char[][] compoundName = CharOperation.splitOn('/', binaryType.getName());
ReferenceBinding existingType = getCachedType(compoundName);
if (existingType == null || existingType instanceof UnresolvedReferenceBinding)
// only add the binary type if its not already in the cache
return createBinaryTypeFrom(binaryType, computePackageFrom(compoundName, false /* valid pkg */), needFieldsAndMethods, accessRestriction);
return null; // the type already exists & can be retrieved from the cache
}
public void completeTypeBindings() {
if (this != this.root) {
this.root.completeTypeBindings();
return;
}
this.stepCompleted = BUILD_TYPE_HIERARCHY;
for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) {
(this.unitBeingCompleted = this.units[i]).scope.checkAndSetImports();
}
this.stepCompleted = CHECK_AND_SET_IMPORTS;
for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) {
(this.unitBeingCompleted = this.units[i]).scope.connectTypeHierarchy();
// GROOVY add -- augment type hierarchy may bring in GroovyObject as source (if in groovycore) and that will then need its type hierarchy connecting
(this.unitBeingCompleted = this.units[i]).scope.augmentTypeHierarchy();
// GROOVY end
}
this.stepCompleted = CONNECT_TYPE_HIERARCHY;
for (int i = this.lastCompletedUnitIndex + 1; i <= this.lastUnitIndex; i++) {
CompilationUnitScope unitScope = (this.unitBeingCompleted = this.units[i]).scope;
unitScope.checkParameterizedTypes();
unitScope.buildFieldsAndMethods();
this.units[i] = null; // release unnecessary reference to the parsed unit
}
this.stepCompleted = BUILD_FIELDS_AND_METHODS;
this.lastCompletedUnitIndex = this.lastUnitIndex;
this.unitBeingCompleted = null;
}
/*
* 1. Connect the type hierarchy for the type bindings created for parsedUnits.
* 2. Create the field bindings
* 3. Create the method bindings
*/
/* We know each known compilationUnit is free of errors at this point...
*
* Each step will create additional bindings unless a problem is detected, in which
* case either the faulty import/superinterface/field/method will be skipped or a
* suitable replacement will be substituted (such as Object for a missing superclass)
*/
public void completeTypeBindings(CompilationUnitDeclaration parsedUnit) {
if (this != this.root) {
this.root.completeTypeBindings(parsedUnit);
return;
}
if (this.stepCompleted == BUILD_FIELDS_AND_METHODS) {
// This can only happen because the original set of units are completely built and
// are now being processed, so we want to treat all the additional units as a group
// until they too are completely processed.
completeTypeBindings();
} else {
if (parsedUnit.scope == null) return; // parsing errors were too severe
if (this.stepCompleted >= CHECK_AND_SET_IMPORTS)
(this.unitBeingCompleted = parsedUnit).scope.checkAndSetImports();
if (this.stepCompleted >= CONNECT_TYPE_HIERARCHY)
(this.unitBeingCompleted = parsedUnit).scope.connectTypeHierarchy();
this.unitBeingCompleted = null;
}
}
/*
* Used by other compiler tools which do not start by calling completeTypeBindings().
*
* 1. Connect the type hierarchy for the type bindings created for parsedUnits.
* 2. Create the field bindings
* 3. Create the method bindings
*/
/*
* Each step will create additional bindings unless a problem is detected, in which
* case either the faulty import/superinterface/field/method will be skipped or a
* suitable replacement will be substituted (such as Object for a missing superclass)
*/
public void completeTypeBindings(CompilationUnitDeclaration parsedUnit, boolean buildFieldsAndMethods) {
if (parsedUnit.scope == null) return; // parsing errors were too severe
LookupEnvironment rootEnv = this.root;
CompilationUnitDeclaration previousUnitBeingCompleted = rootEnv.unitBeingCompleted;
(rootEnv.unitBeingCompleted = parsedUnit).scope.checkAndSetImports();
parsedUnit.scope.connectTypeHierarchy();
parsedUnit.scope.checkParameterizedTypes();
if (buildFieldsAndMethods)
parsedUnit.scope.buildFieldsAndMethods();
rootEnv.unitBeingCompleted = previousUnitBeingCompleted;
}
/*
* Used by other compiler tools which do not start by calling completeTypeBindings()
* and have more than 1 unit to complete.
*
* 1. Connect the type hierarchy for the type bindings created for parsedUnits.
* 2. Create the field bindings
* 3. Create the method bindings
*/
public void completeTypeBindings(CompilationUnitDeclaration[] parsedUnits, boolean[] buildFieldsAndMethods, int unitCount) {
LookupEnvironment rootEnv = this.root;
for (int i = 0; i < unitCount; i++) {
CompilationUnitDeclaration parsedUnit = parsedUnits[i];
if (parsedUnit.scope != null)
(rootEnv.unitBeingCompleted = parsedUnit).scope.checkAndSetImports();
}
for (int i = 0; i < unitCount; i++) {
CompilationUnitDeclaration parsedUnit = parsedUnits[i];
if (parsedUnit.scope != null)
(rootEnv.unitBeingCompleted = parsedUnit).scope.connectTypeHierarchy();
}
for (int i = 0; i < unitCount; i++) {
CompilationUnitDeclaration parsedUnit = parsedUnits[i];
if (parsedUnit.scope != null) {
(rootEnv.unitBeingCompleted = parsedUnit).scope.checkParameterizedTypes();
if (buildFieldsAndMethods[i])
parsedUnit.scope.buildFieldsAndMethods();
}
}
rootEnv.unitBeingCompleted = null;
}
public TypeBinding computeBoxingType(TypeBinding type) {
TypeBinding boxedType;
switch (type.id) {
case TypeIds.T_JavaLangBoolean :
return TypeBinding.BOOLEAN;
case TypeIds.T_JavaLangByte :
return TypeBinding.BYTE;
case TypeIds.T_JavaLangCharacter :
return TypeBinding.CHAR;
case TypeIds.T_JavaLangShort :
return TypeBinding.SHORT;
case TypeIds.T_JavaLangDouble :
return TypeBinding.DOUBLE;
case TypeIds.T_JavaLangFloat :
return TypeBinding.FLOAT;
case TypeIds.T_JavaLangInteger :
return TypeBinding.INT;
case TypeIds.T_JavaLangLong :
return TypeBinding.LONG;
case TypeIds.T_int :
boxedType = getType(JAVA_LANG_INTEGER, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_INTEGER, null, NotFound);
case TypeIds.T_byte :
boxedType = getType(JAVA_LANG_BYTE, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_BYTE, null, NotFound);
case TypeIds.T_short :
boxedType = getType(JAVA_LANG_SHORT, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_SHORT, null, NotFound);
case TypeIds.T_char :
boxedType = getType(JAVA_LANG_CHARACTER, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_CHARACTER, null, NotFound);
case TypeIds.T_long :
boxedType = getType(JAVA_LANG_LONG, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_LONG, null, NotFound);
case TypeIds.T_float :
boxedType = getType(JAVA_LANG_FLOAT, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_FLOAT, null, NotFound);
case TypeIds.T_double :
boxedType = getType(JAVA_LANG_DOUBLE, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_DOUBLE, null, NotFound);
case TypeIds.T_boolean :
boxedType = getType(JAVA_LANG_BOOLEAN, javaBaseModule());
if (boxedType != null) return boxedType;
return new ProblemReferenceBinding(JAVA_LANG_BOOLEAN, null, NotFound);
// case TypeIds.T_int :
// return getResolvedType(JAVA_LANG_INTEGER, null);
// case TypeIds.T_byte :
// return getResolvedType(JAVA_LANG_BYTE, null);
// case TypeIds.T_short :
// return getResolvedType(JAVA_LANG_SHORT, null);
// case TypeIds.T_char :
// return getResolvedType(JAVA_LANG_CHARACTER, null);
// case TypeIds.T_long :
// return getResolvedType(JAVA_LANG_LONG, null);
// case TypeIds.T_float :
// return getResolvedType(JAVA_LANG_FLOAT, null);
// case TypeIds.T_double :
// return getResolvedType(JAVA_LANG_DOUBLE, null);
// case TypeIds.T_boolean :
// return getResolvedType(JAVA_LANG_BOOLEAN, null);
}
// allow indirect unboxing conversion for wildcards and type parameters
switch (type.kind()) {
case Binding.WILDCARD_TYPE :
case Binding.INTERSECTION_TYPE :
case Binding.TYPE_PARAMETER :
case Binding.INTERSECTION_TYPE18:
switch (type.erasure().id) {
case TypeIds.T_JavaLangBoolean :
return TypeBinding.BOOLEAN;
case TypeIds.T_JavaLangByte :
return TypeBinding.BYTE;
case TypeIds.T_JavaLangCharacter :
return TypeBinding.CHAR;
case TypeIds.T_JavaLangShort :
return TypeBinding.SHORT;
case TypeIds.T_JavaLangDouble :
return TypeBinding.DOUBLE;
case TypeIds.T_JavaLangFloat :
return TypeBinding.FLOAT;
case TypeIds.T_JavaLangInteger :
return TypeBinding.INT;
case TypeIds.T_JavaLangLong :
return TypeBinding.LONG;
}
break;
case Binding.POLY_TYPE:
return ((PolyTypeBinding) type).computeBoxingType();
}
return type;
}
public ModuleBinding javaBaseModule() {
if (this.JavaBaseModule != null)
return this.JavaBaseModule;
if (this.root != this)
return this.JavaBaseModule = this.root.javaBaseModule();
ModuleBinding resolvedModel = null;
if (this.useModuleSystem)
resolvedModel = getModule(TypeConstants.JAVA_BASE);
return this.JavaBaseModule = (resolvedModel != null ? resolvedModel : this.UnNamedModule); // fall back to pre-Jigsaw view
}
private PackageBinding computePackageFrom(char[][] constantPoolName, boolean isMissing) {
if (constantPoolName.length == 1)
return this.defaultPackage;
PackageBinding packageBinding = getPackage0(constantPoolName[0]);
if (packageBinding == null || packageBinding == TheNotFoundPackage) {
if (this.useModuleSystem) {
if (this.module.isUnnamed()) {
char[][] declaringModules = ((IModuleAwareNameEnvironment) this.nameEnvironment).getUniqueModulesDeclaringPackage(new char[][] {constantPoolName[0]}, ModuleBinding.ANY);
if (declaringModules != null) {
for (char[] mod : declaringModules) {
ModuleBinding declaringModule = this.root.getModule(mod);
if (declaringModule != null)
packageBinding = SplitPackageBinding.combine(declaringModule.getTopLevelPackage(constantPoolName[0]), packageBinding, this.module);
}
}
} else {
packageBinding = this.module.getTopLevelPackage(constantPoolName[0]);
}
}
if (packageBinding == null || packageBinding == TheNotFoundPackage) {
packageBinding = this.module.createDeclaredToplevelPackage(constantPoolName[0]);
}
if (isMissing) packageBinding.tagBits |= TagBits.HasMissingType;
this.knownPackages.put(constantPoolName[0], packageBinding); // TODO: split?
}
for (int i = 1, length = constantPoolName.length - 1; i < length; i++) {
PackageBinding parent = packageBinding;
if ((packageBinding = parent.getPackage0(constantPoolName[i])) == null || packageBinding == TheNotFoundPackage) {
if (this.useModuleSystem) {
if (this.module.isUnnamed()) {
char[][] currentCompoundName = CharOperation.arrayConcat(parent.compoundName, constantPoolName[i]);
char[][] declaringModules = ((IModuleAwareNameEnvironment) this.nameEnvironment).getModulesDeclaringPackage(
currentCompoundName, ModuleBinding.ANY);
if (declaringModules != null) {
for (char[] mod : declaringModules) {
ModuleBinding declaringModule = this.root.getModule(mod);
if (declaringModule != null)
packageBinding = SplitPackageBinding.combine(declaringModule.getVisiblePackage(currentCompoundName), packageBinding, this.module);
}
}
} else {
packageBinding = this.module.getVisiblePackage(parent, constantPoolName[i]);
}
}
if (packageBinding == null || packageBinding == TheNotFoundPackage) {
packageBinding = this.module.createDeclaredPackage(CharOperation.subarray(constantPoolName, 0, i + 1), parent);
}
if (isMissing) {
packageBinding.tagBits |= TagBits.HasMissingType;
}
packageBinding = parent.addPackage(packageBinding, this.module);
}
}
if (packageBinding instanceof SplitPackageBinding) {
PackageBinding candidate = null;
// select from incarnations the unique package containing CUs, if any:
for (PackageBinding incarnation : ((SplitPackageBinding) packageBinding).incarnations) {
if (incarnation.hasCompilationUnit(false)) {
if (candidate != null) {
candidate = null;
break; // likely to report "accessible from more than one module" downstream
}
candidate = incarnation;
}
}
if (candidate != null)
return candidate;
}
return packageBinding;
}
/**
* Convert a given source type into a parameterized form if generic.
* generic X<E> --> param X<E>
*/
public ReferenceBinding convertToParameterizedType(ReferenceBinding originalType) {
if (originalType != null) {
boolean isGeneric = originalType.isGenericType();
if (!isGeneric && !originalType.hasEnclosingInstanceContext())
return originalType;
ReferenceBinding originalEnclosingType = originalType.enclosingType();
ReferenceBinding convertedEnclosingType = originalEnclosingType;
boolean needToConvert = isGeneric;
if (originalEnclosingType != null && originalType.hasEnclosingInstanceContext()) {
convertedEnclosingType = convertToParameterizedType(originalEnclosingType);
needToConvert |= TypeBinding.notEquals(originalEnclosingType, convertedEnclosingType);
}
if (needToConvert) {
return createParameterizedType(originalType, isGeneric ? originalType.typeVariables() : null, convertedEnclosingType);
}
}
return originalType;
}
/**
* Returns the given binding's raw type binding.
* @param type the TypeBinding to raw convert
* @param forceRawEnclosingType forces recursive raw conversion of enclosing types (used in Javadoc references only)
* @return TypeBinding the raw converted TypeBinding
*/
public TypeBinding convertToRawType(TypeBinding type, boolean forceRawEnclosingType) {
int dimension;
TypeBinding originalType;
switch(type.kind()) {
case Binding.BASE_TYPE :
case Binding.TYPE_PARAMETER:
case Binding.WILDCARD_TYPE:
case Binding.INTERSECTION_TYPE:
case Binding.RAW_TYPE:
return type;
case Binding.ARRAY_TYPE:
dimension = type.dimensions();
originalType = type.leafComponentType();
break;
default:
if (type.id == TypeIds.T_JavaLangObject)
return type; // Object is not generic
dimension = 0;
originalType = type;
}
boolean needToConvert;
switch (originalType.kind()) {
case Binding.BASE_TYPE :
return type;
case Binding.GENERIC_TYPE :
needToConvert = true;
break;
case Binding.PARAMETERIZED_TYPE :
ParameterizedTypeBinding paramType = (ParameterizedTypeBinding) originalType;
needToConvert = paramType.genericType().isGenericType(); // only recursive call to enclosing type can find parameterizedType with arguments
break;
default :
needToConvert = false;
break;
}
forceRawEnclosingType &= !originalType.isStatic();
ReferenceBinding originalEnclosing = originalType.enclosingType();
TypeBinding convertedType;
if (originalEnclosing == null) {
convertedType = needToConvert ? createRawType((ReferenceBinding)originalType.erasure(), null) : originalType;
} else {
ReferenceBinding convertedEnclosing;
if (!((ReferenceBinding)originalType).hasEnclosingInstanceContext()) {
convertedEnclosing = (ReferenceBinding) originalEnclosing.original();
} else {
if (originalEnclosing.kind() == Binding.RAW_TYPE) {
convertedEnclosing = originalEnclosing;
needToConvert = true;
} else if (forceRawEnclosingType && !needToConvert/*stop recursion when conversion occurs*/) {
convertedEnclosing = (ReferenceBinding) convertToRawType(originalEnclosing, forceRawEnclosingType);
needToConvert = TypeBinding.notEquals(originalEnclosing, convertedEnclosing); // only convert generic or parameterized types
} else if (needToConvert) {
convertedEnclosing = (ReferenceBinding) convertToRawType(originalEnclosing, false);
} else {
convertedEnclosing = convertToParameterizedType(originalEnclosing);
}
}
if (needToConvert) {
convertedType = createRawType((ReferenceBinding) originalType.erasure(), convertedEnclosing);
} else if (TypeBinding.notEquals(originalEnclosing, convertedEnclosing)) {
convertedType = createParameterizedType((ReferenceBinding) originalType.erasure(), null, convertedEnclosing);
} else {
convertedType = originalType;
}
}
if (TypeBinding.notEquals(originalType, convertedType)) {
return dimension > 0 ? (TypeBinding)createArrayType(convertedType, dimension) : convertedType;
}
return type;
}
/**
* Convert an array of types in raw forms.
* Only allocate an array if anything is different.
*/
public ReferenceBinding[] convertToRawTypes(ReferenceBinding[] originalTypes, boolean forceErasure, boolean forceRawEnclosingType) {
if (originalTypes == null) return null;
ReferenceBinding[] convertedTypes = originalTypes;
for (int i = 0, length = originalTypes.length; i < length; i++) {
ReferenceBinding originalType = originalTypes[i];
ReferenceBinding convertedType = (ReferenceBinding) convertToRawType(forceErasure ? originalType.erasure() : originalType, forceRawEnclosingType);
if (TypeBinding.notEquals(convertedType, originalType)) {
if (convertedTypes == originalTypes) {
System.arraycopy(originalTypes, 0, convertedTypes = new ReferenceBinding[length], 0, i);
}
convertedTypes[i] = convertedType;
} else if (convertedTypes != originalTypes) {
convertedTypes[i] = originalType;
}
}
return convertedTypes;
}
// variation for unresolved types in binaries (consider generic type as raw)
public TypeBinding convertUnresolvedBinaryToRawType(TypeBinding type) {
int dimension;
TypeBinding originalType;
switch(type.kind()) {
case Binding.BASE_TYPE :
case Binding.TYPE_PARAMETER:
case Binding.WILDCARD_TYPE:
case Binding.INTERSECTION_TYPE:
case Binding.RAW_TYPE:
return type;
case Binding.ARRAY_TYPE:
dimension = type.dimensions();
originalType = type.leafComponentType();
break;
default:
if (type.id == TypeIds.T_JavaLangObject)
return type; // Object is not generic
dimension = 0;
originalType = type;
}
boolean needToConvert;
switch (originalType.kind()) {
case Binding.BASE_TYPE :
return type;
case Binding.GENERIC_TYPE :
needToConvert = true;
break;
case Binding.PARAMETERIZED_TYPE :
ParameterizedTypeBinding paramType = (ParameterizedTypeBinding) originalType;
needToConvert = paramType.genericType().isGenericType(); // only recursive call to enclosing type can find parameterizedType with arguments
break;
default :
needToConvert = false;
break;
}
ReferenceBinding originalEnclosing = originalType.enclosingType();
TypeBinding convertedType;
if (originalEnclosing == null) {
convertedType = needToConvert ? createRawType((ReferenceBinding)originalType.erasure(), null) : originalType;
} else {
if (!needToConvert && originalType.isStatic())
return originalType;
ReferenceBinding convertedEnclosing = (ReferenceBinding) convertUnresolvedBinaryToRawType(originalEnclosing);
if (TypeBinding.notEquals(convertedEnclosing, originalEnclosing)) {
needToConvert = true;
}
if (needToConvert) {
convertedType = createRawType((ReferenceBinding) originalType.erasure(), convertedEnclosing);
} else {
convertedType = originalType;
}
}
if (TypeBinding.notEquals(originalType, convertedType)) {
return dimension > 0 ? (TypeBinding)createArrayType(convertedType, dimension) : convertedType;
}
return type;
}
/* Used to guarantee annotation identity: we do that only for marker annotations and others with all default values.
We don't have the machinery for the general case as of now.
*/
public AnnotationBinding createAnnotation(ReferenceBinding annotationType, ElementValuePair[] pairs) {
if (pairs.length != 0) {
AnnotationBinding.setMethodBindings(annotationType, pairs);