-
Notifications
You must be signed in to change notification settings - Fork 99
/
TypeEnter.java
1490 lines (1320 loc) · 62.2 KB
/
TypeEnter.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, 2021, 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 java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import javax.tools.JavaFileObject;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Scope.ImportFilter;
import com.sun.tools.javac.code.Scope.NamedImportScope;
import com.sun.tools.javac.code.Scope.StarImportScope;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.DefinedBy.Api;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.tree.JCTree.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Flags.ANNOTATION;
import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import static com.sun.tools.javac.code.TypeTag.CLASS;
import static com.sun.tools.javac.code.TypeTag.ERROR;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import com.sun.tools.javac.util.Dependencies.CompletionCause;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
/** This is the second phase of Enter, in which classes are completed
* by resolving their headers and entering their members in the into
* the class scope. See Enter for an overall overview.
*
* This class uses internal phases to process the classes. When a phase
* processes classes, the lower phases are not invoked until all classes
* pass through the current phase. Note that it is possible that upper phases
* are run due to recursive completion. The internal phases are:
* - ImportPhase: shallow pass through imports, adds information about imports
* the NamedImportScope and StarImportScope, but avoids queries
* about class hierarchy.
* - HierarchyPhase: resolves the supertypes of the given class. Does not handle
* type parameters of the class or type argument of the supertypes.
* - HeaderPhase: finishes analysis of the header of the given class by resolving
* type parameters, attributing supertypes including type arguments
* and scheduling full annotation attribution. This phase also adds
* a synthetic default constructor if needed and synthetic "this" field.
* - MembersPhase: resolves headers for fields, methods and constructors in the given class.
* Also generates synthetic enum members.
*
* <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 TypeEnter implements Completer {
protected static final Context.Key<TypeEnter> typeEnterKey = new Context.Key<>();
/** A switch to determine whether we check for package/class conflicts
*/
static final boolean checkClash = true;
private final Names names;
private final Enter enter;
private final MemberEnter memberEnter;
private final Log log;
private final Check chk;
private final Attr attr;
private final Symtab syms;
private final TreeMaker make;
private final Todo todo;
private final Annotate annotate;
private final TypeAnnotations typeAnnotations;
private final Types types;
private final JCDiagnostic.Factory diags;
private final DeferredLintHandler deferredLintHandler;
private final Lint lint;
private final TypeEnvs typeEnvs;
private final Dependencies dependencies;
private final Preview preview;
public static TypeEnter instance(Context context) {
TypeEnter instance = context.get(typeEnterKey);
if (instance == null)
instance = new TypeEnter(context);
return instance;
}
protected TypeEnter(Context context) {
context.put(typeEnterKey, this);
names = Names.instance(context);
enter = Enter.instance(context);
memberEnter = MemberEnter.instance(context);
log = Log.instance(context);
chk = Check.instance(context);
attr = Attr.instance(context);
syms = Symtab.instance(context);
make = TreeMaker.instance(context);
todo = Todo.instance(context);
annotate = Annotate.instance(context);
typeAnnotations = TypeAnnotations.instance(context);
types = Types.instance(context);
diags = JCDiagnostic.Factory.instance(context);
deferredLintHandler = DeferredLintHandler.instance(context);
lint = Lint.instance(context);
typeEnvs = TypeEnvs.instance(context);
dependencies = Dependencies.instance(context);
preview = Preview.instance(context);
Source source = Source.instance(context);
allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
allowDeprecationOnImport = Feature.DEPRECATION_ON_IMPORT.allowedInSource(source);
}
/** Switch: support type annotations.
*/
boolean allowTypeAnnos;
/**
* Switch: should deprecation warnings be issued on import
*/
boolean allowDeprecationOnImport;
/** A flag to disable completion from time to time during member
* enter, as we only need to look up types. This avoids
* unnecessarily deep recursion.
*/
boolean completionEnabled = true;
/* Verify Imports:
*/
protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
// if there remain any unimported toplevels (these must have
// no classes at all), process their import statements as well.
for (JCCompilationUnit tree : trees) {
if (!tree.starImportScope.isFilled()) {
Env<AttrContext> topEnv = enter.topLevelEnv(tree);
finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
}
}
}
/* ********************************************************************
* Source completer
*********************************************************************/
/** Complete entering a class.
* @param sym The symbol of the class to be completed.
*/
@Override
public void complete(Symbol sym) throws CompletionFailure {
// Suppress some (recursive) MemberEnter invocations
if (!completionEnabled) {
// Re-install same completer for next time around and return.
Assert.check((sym.flags() & Flags.COMPOUND) == 0);
sym.completer = this;
return;
}
try {
annotate.blockAnnotations();
sym.flags_field |= UNATTRIBUTED;
List<Env<AttrContext>> queue;
dependencies.push((ClassSymbol) sym, CompletionCause.MEMBER_ENTER);
try {
queue = completeClass.completeEnvs(List.of(typeEnvs.get((ClassSymbol) sym)));
} finally {
dependencies.pop();
}
if (!queue.isEmpty()) {
Set<JCCompilationUnit> seen = new HashSet<>();
for (Env<AttrContext> env : queue) {
if (env.toplevel.defs.contains(env.enclClass) && seen.add(env.toplevel)) {
finishImports(env.toplevel, () -> {});
}
}
}
} finally {
annotate.unblockAnnotations();
}
}
void finishImports(JCCompilationUnit toplevel, Runnable resolve) {
JavaFileObject prev = log.useSource(toplevel.sourcefile);
try {
resolve.run();
chk.checkImportsUnique(toplevel);
chk.checkImportsResolvable(toplevel);
chk.checkImportedPackagesObservable(toplevel);
toplevel.namedImportScope.finalizeScope();
toplevel.starImportScope.finalizeScope();
} catch (CompletionFailure cf) {
chk.completionError(toplevel.pos(), cf);
} finally {
log.useSource(prev);
}
}
abstract class Phase {
private final ListBuffer<Env<AttrContext>> queue = new ListBuffer<>();
private final Phase next;
private final CompletionCause phaseName;
Phase(CompletionCause phaseName, Phase next) {
this.phaseName = phaseName;
this.next = next;
}
public final List<Env<AttrContext>> completeEnvs(List<Env<AttrContext>> envs) {
boolean firstToComplete = queue.isEmpty();
Phase prevTopLevelPhase = topLevelPhase;
boolean success = false;
try {
topLevelPhase = this;
doCompleteEnvs(envs);
success = true;
} finally {
topLevelPhase = prevTopLevelPhase;
if (!success && firstToComplete) {
//an exception was thrown, e.g. BreakAttr:
//the queue would become stale, clear it:
queue.clear();
}
}
if (firstToComplete) {
List<Env<AttrContext>> out = queue.toList();
queue.clear();
return next != null ? next.completeEnvs(out) : out;
} else {
return List.nil();
}
}
protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
for (Env<AttrContext> env : envs) {
JCClassDecl tree = (JCClassDecl)env.tree;
queue.add(env);
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
try {
dependencies.push(env.enclClass.sym, phaseName);
runPhase(env);
} catch (CompletionFailure ex) {
chk.completionError(tree.pos(), ex);
} finally {
dependencies.pop();
deferredLintHandler.setPos(prevLintPos);
log.useSource(prev);
}
}
}
protected abstract void runPhase(Env<AttrContext> env);
}
private final ImportsPhase completeClass = new ImportsPhase();
private Phase topLevelPhase;
/**Analyze import clauses.
*/
private final class ImportsPhase extends Phase {
public ImportsPhase() {
super(CompletionCause.IMPORTS_PHASE, new HierarchyPhase());
}
Env<AttrContext> env;
ImportFilter staticImportFilter;
ImportFilter typeImportFilter;
BiConsumer<JCImport, CompletionFailure> cfHandler =
(imp, cf) -> chk.completionError(imp.pos(), cf);
@Override
protected void runPhase(Env<AttrContext> env) {
JCClassDecl tree = env.enclClass;
ClassSymbol sym = tree.sym;
// If sym is a toplevel-class, make sure any import
// clauses in its source file have been seen.
if (sym.owner.kind == PCK) {
resolveImports(env.toplevel, env.enclosing(TOPLEVEL));
todo.append(env);
}
if (sym.owner.kind == TYP)
sym.owner.complete();
}
private void resolveImports(JCCompilationUnit tree, Env<AttrContext> env) {
if (tree.starImportScope.isFilled()) {
// we must have already processed this toplevel
return;
}
ImportFilter prevStaticImportFilter = staticImportFilter;
ImportFilter prevTypeImportFilter = typeImportFilter;
DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
Lint prevLint = chk.setLint(lint);
Env<AttrContext> prevEnv = this.env;
try {
this.env = env;
final PackageSymbol packge = env.toplevel.packge;
this.staticImportFilter =
(origin, sym) -> sym.isStatic() &&
chk.importAccessible(sym, packge) &&
sym.isMemberOf((TypeSymbol) origin.owner, types);
this.typeImportFilter =
(origin, sym) -> sym.kind == TYP &&
chk.importAccessible(sym, packge);
// Import-on-demand java.lang.
PackageSymbol javaLang = syms.enterPackage(syms.java_base, names.java_lang);
if (javaLang.members().isEmpty() && !javaLang.exists())
throw new FatalError(diags.fragment(Fragments.FatalErrNoJavaLang));
importAll(make.at(tree.pos()).Import(make.QualIdent(javaLang), false), javaLang, env);
JCModuleDecl decl = tree.getModuleDecl();
// Process the package def and all import clauses.
if (tree.getPackage() != null && decl == null)
checkClassPackageClash(tree.getPackage());
for (JCImport imp : tree.getImports()) {
doImport(imp);
}
if (decl != null) {
//check @Deprecated:
markDeprecated(decl.sym, decl.mods.annotations, env);
// process module annotations
annotate.annotateLater(decl.mods.annotations, env, env.toplevel.modle, null);
}
} finally {
this.env = prevEnv;
chk.setLint(prevLint);
deferredLintHandler.setPos(prevLintPos);
this.staticImportFilter = prevStaticImportFilter;
this.typeImportFilter = prevTypeImportFilter;
}
}
private void checkClassPackageClash(JCPackageDecl tree) {
// check that no class exists with same fully qualified name as
// toplevel package
if (checkClash && tree.pid != null) {
Symbol p = env.toplevel.packge;
while (p.owner != syms.rootPackage) {
p.owner.complete(); // enter all class members of p
//need to lookup the owning module/package:
PackageSymbol pack = syms.lookupPackage(env.toplevel.modle, p.owner.getQualifiedName());
if (syms.getClass(pack.modle, p.getQualifiedName()) != null) {
log.error(tree.pos,
Errors.PkgClashesWithClassOfSameName(p));
}
p = p.owner;
}
}
// process package annotations
annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null);
}
private void doImport(JCImport tree) {
JCFieldAccess imp = (JCFieldAccess)tree.qualid;
Name name = TreeInfo.name(imp);
// Create a local environment pointing to this tree to disable
// effects of other imports in Resolve.findGlobalType
Env<AttrContext> localEnv = env.dup(tree);
TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
if (name == names.asterisk) {
// Import on demand.
chk.checkCanonical(imp.selected);
if (tree.staticImport)
importStaticAll(tree, p, env);
else
importAll(tree, p, env);
} else {
// Named type import.
if (tree.staticImport) {
importNamedStatic(tree, p, name, localEnv);
chk.checkCanonical(imp.selected);
} else {
Type importedType = attribImportType(imp, localEnv);
Type originalType = importedType.getOriginalType();
TypeSymbol c = originalType.hasTag(CLASS) ? originalType.tsym : importedType.tsym;
chk.checkCanonical(imp);
importNamed(tree.pos(), c, env, tree);
}
}
}
Type attribImportType(JCTree tree, Env<AttrContext> env) {
Assert.check(completionEnabled);
Lint prevLint = chk.setLint(allowDeprecationOnImport ?
lint : lint.suppress(LintCategory.DEPRECATION, LintCategory.REMOVAL, LintCategory.PREVIEW));
try {
// To prevent deep recursion, suppress completion of some
// types.
completionEnabled = false;
return attr.attribType(tree, env);
} finally {
completionEnabled = true;
chk.setLint(prevLint);
}
}
/** Import all classes of a class or package on demand.
* @param imp The import that is being handled.
* @param tsym The class or package the members of which are imported.
* @param env The env in which the imported classes will be entered.
*/
private void importAll(JCImport imp,
final TypeSymbol tsym,
Env<AttrContext> env) {
env.toplevel.starImportScope.importAll(types, tsym.members(), typeImportFilter, imp, cfHandler);
}
/** Import all static members of a class or package on demand.
* @param imp The import that is being handled.
* @param tsym The class or package the members of which are imported.
* @param env The env in which the imported classes will be entered.
*/
private void importStaticAll(JCImport imp,
final TypeSymbol tsym,
Env<AttrContext> env) {
final StarImportScope toScope = env.toplevel.starImportScope;
final TypeSymbol origin = tsym;
toScope.importAll(types, origin.members(), staticImportFilter, imp, cfHandler);
}
/** Import statics types of a given name. Non-types are handled in Attr.
* @param imp The import that is being handled.
* @param tsym The class from which the name is imported.
* @param name The (simple) name being imported.
* @param env The environment containing the named import
* scope to add to.
*/
private void importNamedStatic(final JCImport imp,
final TypeSymbol tsym,
final Name name,
final Env<AttrContext> env) {
if (tsym.kind != TYP) {
log.error(DiagnosticFlag.RECOVERABLE, imp.pos(), Errors.StaticImpOnlyClassesAndInterfaces);
return;
}
final NamedImportScope toScope = env.toplevel.namedImportScope;
final Scope originMembers = tsym.members();
imp.importScope = toScope.importByName(types, originMembers, name, staticImportFilter, imp, cfHandler);
}
/** Import given class.
* @param pos Position to be used for error reporting.
* @param tsym The class to be imported.
* @param env The environment containing the named import
* scope to add to.
*/
private void importNamed(DiagnosticPosition pos, final Symbol tsym, Env<AttrContext> env, JCImport imp) {
if (tsym.kind == TYP)
imp.importScope = env.toplevel.namedImportScope.importType(tsym.owner.members(), tsym.owner.members(), tsym);
}
}
/**Defines common utility methods used by the HierarchyPhase and HeaderPhase.
*/
private abstract class AbstractHeaderPhase extends Phase {
public AbstractHeaderPhase(CompletionCause phaseName, Phase next) {
super(phaseName, next);
}
protected Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
WriteableScope baseScope = WriteableScope.create(tree.sym);
//import already entered local classes into base scope
for (Symbol sym : env.outer.info.scope.getSymbols(NON_RECURSIVE)) {
if (sym.isDirectlyOrIndirectlyLocal()) {
baseScope.enter(sym);
}
}
//import current type-parameters into base scope
if (tree.typarams != null)
for (List<JCTypeParameter> typarams = tree.typarams;
typarams.nonEmpty();
typarams = typarams.tail)
baseScope.enter(typarams.head.type.tsym);
Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
localEnv.baseClause = true;
localEnv.outer = outer;
localEnv.info.isSelfCall = false;
return localEnv;
}
/** Generate a base clause for an enum type.
* @param pos The position for trees and diagnostics, if any
* @param c The class symbol of the enum
*/
protected JCExpression enumBase(int pos, ClassSymbol c) {
JCExpression result = make.at(pos).
TypeApply(make.QualIdent(syms.enumSym),
List.of(make.Type(c.type)));
return result;
}
protected Type modelMissingTypes(Env<AttrContext> env, Type t, final JCExpression tree, final boolean interfaceExpected) {
if (!t.hasTag(ERROR))
return t;
return new ErrorType(t.getOriginalType(), t.tsym) {
private Type modelType;
@Override
public Type getModelType() {
if (modelType == null)
modelType = new Synthesizer(env.toplevel.modle, getOriginalType(), interfaceExpected).visit(tree);
return modelType;
}
};
}
// where:
private class Synthesizer extends JCTree.Visitor {
ModuleSymbol msym;
Type originalType;
boolean interfaceExpected;
List<ClassSymbol> synthesizedSymbols = List.nil();
Type result;
Synthesizer(ModuleSymbol msym, Type originalType, boolean interfaceExpected) {
this.msym = msym;
this.originalType = originalType;
this.interfaceExpected = interfaceExpected;
}
Type visit(JCTree tree) {
tree.accept(this);
return result;
}
List<Type> visit(List<? extends JCTree> trees) {
ListBuffer<Type> lb = new ListBuffer<>();
for (JCTree t: trees)
lb.append(visit(t));
return lb.toList();
}
@Override
public void visitTree(JCTree tree) {
result = syms.errType;
}
@Override
public void visitIdent(JCIdent tree) {
if (!tree.type.hasTag(ERROR)) {
result = tree.type;
} else {
result = synthesizeClass(tree.name, msym.unnamedPackage).type;
}
}
@Override
public void visitSelect(JCFieldAccess tree) {
if (!tree.type.hasTag(ERROR)) {
result = tree.type;
} else {
Type selectedType;
boolean prev = interfaceExpected;
try {
interfaceExpected = false;
selectedType = visit(tree.selected);
} finally {
interfaceExpected = prev;
}
ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
result = c.type;
}
}
@Override
public void visitTypeApply(JCTypeApply tree) {
if (!tree.type.hasTag(ERROR)) {
result = tree.type;
} else {
ClassType clazzType = (ClassType) visit(tree.clazz);
if (synthesizedSymbols.contains(clazzType.tsym))
synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
final List<Type> actuals = visit(tree.arguments);
result = new ErrorType(tree.type, clazzType.tsym) {
@Override @DefinedBy(Api.LANGUAGE_MODEL)
public List<Type> getTypeArguments() {
return actuals;
}
};
}
}
ClassSymbol synthesizeClass(Name name, Symbol owner) {
int flags = interfaceExpected ? INTERFACE : 0;
ClassSymbol c = new ClassSymbol(flags, name, owner);
c.members_field = new Scope.ErrorScope(c);
c.type = new ErrorType(originalType, c) {
@Override @DefinedBy(Api.LANGUAGE_MODEL)
public List<Type> getTypeArguments() {
return typarams_field;
}
};
synthesizedSymbols = synthesizedSymbols.prepend(c);
return c;
}
void synthesizeTyparams(ClassSymbol sym, int n) {
ClassType ct = (ClassType) sym.type;
Assert.check(ct.typarams_field.isEmpty());
if (n == 1) {
TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
ct.typarams_field = ct.typarams_field.prepend(v);
} else {
for (int i = n; i > 0; i--) {
TypeVar v = new TypeVar(names.fromString("T" + i), sym,
syms.botType);
ct.typarams_field = ct.typarams_field.prepend(v);
}
}
}
}
protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) {
JCClassDecl tree = env.enclClass;
ClassSymbol sym = tree.sym;
ClassType ct = (ClassType)sym.type;
// Determine supertype.
Type supertype;
JCExpression extending;
final boolean isPrimitiveClass = (tree.mods.flags & Flags.PRIMITIVE_CLASS) != 0;
if (tree.extending != null) {
extending = clearTypeParams(tree.extending);
supertype = attr.attribBase(extending, baseEnv, true, false, true);
if (supertype == syms.recordType) {
log.error(tree, Errors.InvalidSupertypeRecord(supertype.tsym));
}
} else {
extending = null;
supertype = ((tree.mods.flags & Flags.ENUM) != 0)
? attr.attribBase(enumBase(tree.pos, sym), baseEnv,
true, false, false)
: (sym.fullname == names.java_lang_Object)
? Type.noType
: sym.isRecord() ? syms.recordType : syms.objectType;
}
ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false);
// Determine interfaces.
ListBuffer<Type> interfaces = new ListBuffer<>();
ListBuffer<Type> all_interfaces = null; // lazy init
List<JCExpression> interfaceTrees = tree.implementing;
for (JCExpression iface : interfaceTrees) {
iface = clearTypeParams(iface);
Type it = attr.attribBase(iface, baseEnv, false, true, true);
if (it.hasTag(CLASS)) {
if (isPrimitiveClass && it.tsym == syms.cloneableType.tsym) {
log.error(tree, Errors.PrimitiveClassMustNotImplementCloneable(ct));
}
interfaces.append(it);
if (all_interfaces != null) all_interfaces.append(it);
} else {
if (all_interfaces == null)
all_interfaces = new ListBuffer<Type>().appendList(interfaces);
all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true));
}
}
// Determine permits.
ListBuffer<Symbol> permittedSubtypeSymbols = new ListBuffer<>();
List<JCExpression> permittedTrees = tree.permitting;
for (JCExpression permitted : permittedTrees) {
Type pt = attr.attribBase(permitted, baseEnv, false, false, false);
permittedSubtypeSymbols.append(pt.tsym);
}
if ((sym.flags_field & ANNOTATION) != 0) {
ct.interfaces_field = List.of(syms.annotationType);
ct.all_interfaces_field = ct.interfaces_field;
} else {
ct.interfaces_field = interfaces.toList();
ct.all_interfaces_field = (all_interfaces == null)
? ct.interfaces_field : all_interfaces.toList();
}
/* it could be that there are already some symbols in the permitted list, for the case
* where there are subtypes in the same compilation unit but the permits list is empty
* so don't overwrite the permitted list if it is not empty
*/
if (!permittedSubtypeSymbols.isEmpty()) {
sym.permitted = permittedSubtypeSymbols.toList();
}
sym.isPermittedExplicit = !permittedSubtypeSymbols.isEmpty();
}
//where:
protected JCExpression clearTypeParams(JCExpression superType) {
return superType;
}
}
private final class HierarchyPhase extends AbstractHeaderPhase implements Completer {
public HierarchyPhase() {
super(CompletionCause.HIERARCHY_PHASE, new PermitsPhase());
}
@Override
protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
//The ClassSymbols in the envs list may not be in the dependency order.
//To get proper results, for every class or interface C, the supertypes of
//C must be processed by the HierarchyPhase phase before C.
//To achieve that, the HierarchyPhase is registered as the Completer for
//all the classes first, and then all the classes are completed.
for (Env<AttrContext> env : envs) {
env.enclClass.sym.completer = this;
}
for (Env<AttrContext> env : envs) {
env.enclClass.sym.complete();
}
}
@Override
protected void runPhase(Env<AttrContext> env) {
JCClassDecl tree = env.enclClass;
ClassSymbol sym = tree.sym;
ClassType ct = (ClassType)sym.type;
Env<AttrContext> baseEnv = baseEnv(tree, env);
attribSuperTypes(env, baseEnv);
if (sym.fullname == names.java_lang_Object) {
if (tree.extending != null) {
chk.checkNonCyclic(tree.extending.pos(),
ct.supertype_field);
ct.supertype_field = Type.noType;
}
else if (tree.implementing.nonEmpty()) {
chk.checkNonCyclic(tree.implementing.head.pos(),
ct.interfaces_field.head);
ct.interfaces_field = List.nil();
}
}
markDeprecated(sym, tree.mods.annotations, baseEnv);
chk.checkNonCyclicDecl(tree);
}
//where:
@Override
protected JCExpression clearTypeParams(JCExpression superType) {
switch (superType.getTag()) {
case TYPEAPPLY:
return ((JCTypeApply) superType).clazz;
}
return superType;
}
@Override
public void complete(Symbol sym) throws CompletionFailure {
Assert.check((topLevelPhase instanceof ImportsPhase) ||
(topLevelPhase == this));
if (topLevelPhase != this) {
//only do the processing based on dependencies in the HierarchyPhase:
sym.completer = this;
return ;
}
Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym);
super.doCompleteEnvs(List.of(env));
}
}
private final class PermitsPhase extends AbstractHeaderPhase {
public PermitsPhase() {
super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase());
}
@Override
protected void runPhase(Env<AttrContext> env) {
JCClassDecl tree = env.enclClass;
if (!tree.sym.isAnonymous() || tree.sym.isEnum()) {
for (Type supertype : types.directSupertypes(tree.sym.type)) {
if (supertype.tsym.kind == TYP) {
ClassSymbol supClass = (ClassSymbol) supertype.tsym;
Env<AttrContext> supClassEnv = enter.getEnv(supClass);
if (supClass.isSealed() &&
!supClass.isPermittedExplicit &&
supClassEnv != null &&
supClassEnv.toplevel == env.toplevel) {
supClass.permitted = supClass.permitted.append(tree.sym);
}
}
}
}
}
}
private final class HeaderPhase extends AbstractHeaderPhase {
public HeaderPhase() {
super(CompletionCause.HEADER_PHASE, new RecordPhase());
}
@Override
protected void runPhase(Env<AttrContext> env) {
JCClassDecl tree = env.enclClass;
ClassSymbol sym = tree.sym;
ClassType ct = (ClassType)sym.type;
// create an environment for evaluating the base clauses
Env<AttrContext> baseEnv = baseEnv(tree, env);
if (tree.extending != null)
annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos());
for (JCExpression impl : tree.implementing)
annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos());
annotate.flush();
attribSuperTypes(env, baseEnv);
Set<Type> interfaceSet = new HashSet<>();
for (JCExpression iface : tree.implementing) {
Type it = iface.type;
if (it.hasTag(CLASS))
chk.checkNotRepeated(iface.pos(), types.erasure(it), interfaceSet);
}
annotate.annotateLater(tree.mods.annotations, baseEnv,
sym, tree.pos());
attr.attribTypeVariables(tree.typarams, baseEnv, false);
for (JCTypeParameter tp : tree.typarams)
annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos());
// check that no package exists with same fully qualified name,
// but admit classes in the unnamed package which have the same
// name as a top-level package.
if (checkClash &&
sym.owner.kind == PCK && sym.owner != env.toplevel.modle.unnamedPackage &&
syms.packageExists(env.toplevel.modle, sym.fullname)) {
log.error(tree.pos, Errors.ClashWithPkgOfSameName(Kinds.kindName(sym),sym));
}
if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 &&
!env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) {
sym.flags_field |= AUXILIARY;
}
}
}
private abstract class AbstractMembersPhase extends Phase {
public AbstractMembersPhase(CompletionCause completionCause, Phase next) {
super(completionCause, next);
}
private boolean completing;
private List<Env<AttrContext>> todo = List.nil();
@Override
protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
todo = todo.prependList(envs);
if (completing) {
return ; //the top-level invocation will handle all envs
}
boolean prevCompleting = completing;
completing = true;
try {
while (todo.nonEmpty()) {
Env<AttrContext> head = todo.head;
todo = todo.tail;
super.doCompleteEnvs(List.of(head));
}
} finally {
completing = prevCompleting;
}
}
void enterThisAndSuper(ClassSymbol sym, Env<AttrContext> env) {
ClassType ct = (ClassType)sym.type;
// enter symbols for 'this' into current scope.
VarSymbol thisSym =
new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym);
thisSym.pos = Position.FIRSTPOS;
env.info.scope.enter(thisSym);
// if this is a class, enter symbol for 'super' into current scope.
if ((sym.flags_field & INTERFACE) == 0 &&
ct.supertype_field.hasTag(CLASS)) {
VarSymbol superSym =
new VarSymbol(FINAL | HASINIT, names._super,
ct.supertype_field, sym);
superSym.pos = Position.FIRSTPOS;
env.info.scope.enter(superSym);
}
}
}
private final class RecordPhase extends AbstractMembersPhase {
public RecordPhase() {
super(CompletionCause.RECORD_PHASE, new MembersPhase());
}
@Override
protected void runPhase(Env<AttrContext> env) {
JCClassDecl tree = env.enclClass;
ClassSymbol sym = tree.sym;
if ((sym.flags_field & RECORD) != 0) {
List<JCVariableDecl> fields = TreeInfo.recordFields(tree);
memberEnter.memberEnter(fields, env);
for (JCVariableDecl field : fields) {
sym.getRecordComponent(field, true,
field.mods.annotations.isEmpty() ?
List.nil() :
new TreeCopier<JCTree>(make.at(field.pos)).copy(field.mods.annotations));
}
enterThisAndSuper(sym, env);
// lets enter all constructors
for (JCTree def : tree.defs) {
if (TreeInfo.isConstructor(def)) {
memberEnter.memberEnter(def, env);
}
}
}
}
}
/** Enter member fields and methods of a class
*/
private final class MembersPhase extends AbstractMembersPhase {
public MembersPhase() {
super(CompletionCause.MEMBERS_PHASE, null);
}
@Override
protected void runPhase(Env<AttrContext> env) {
JCClassDecl tree = env.enclClass;