1 /*
2  * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package com.sun.tools.javac.comp;
27 
28 import java.util.*;
29 import java.util.function.Predicate;
30 import java.util.function.Supplier;
31 
32 import javax.lang.model.element.ElementKind;
33 import javax.lang.model.element.NestingKind;
34 import javax.tools.JavaFileManager;
35 
36 import com.sun.source.tree.CaseTree;
37 import com.sun.tools.javac.code.*;
38 import com.sun.tools.javac.code.Attribute.Compound;
39 import com.sun.tools.javac.code.Directive.ExportsDirective;
40 import com.sun.tools.javac.code.Directive.RequiresDirective;
41 import com.sun.tools.javac.code.Source.Feature;
42 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
43 import com.sun.tools.javac.jvm.*;
44 import com.sun.tools.javac.resources.CompilerProperties.Errors;
45 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
46 import com.sun.tools.javac.resources.CompilerProperties.Warnings;
47 import com.sun.tools.javac.tree.*;
48 import com.sun.tools.javac.util.*;
49 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
51 import com.sun.tools.javac.util.JCDiagnostic.Error;
52 import com.sun.tools.javac.util.JCDiagnostic.Fragment;
53 import com.sun.tools.javac.util.JCDiagnostic.Warning;
54 import com.sun.tools.javac.util.List;
55 
56 import com.sun.tools.javac.code.Lint;
57 import com.sun.tools.javac.code.Lint.LintCategory;
58 import com.sun.tools.javac.code.Scope.WriteableScope;
59 import com.sun.tools.javac.code.Type.*;
60 import com.sun.tools.javac.code.Symbol.*;
61 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
62 import com.sun.tools.javac.tree.JCTree.*;
63 
64 import static com.sun.tools.javac.code.Flags.*;
65 import static com.sun.tools.javac.code.Flags.ANNOTATION;
66 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
67 import static com.sun.tools.javac.code.Kinds.*;
68 import static com.sun.tools.javac.code.Kinds.Kind.*;
69 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
70 import static com.sun.tools.javac.code.TypeTag.*;
71 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
72 
73 import static com.sun.tools.javac.tree.JCTree.Tag.*;
74 
75 /** Type checking helper class for the attribution phase.
76  *
77  *  <p><b>This is NOT part of any supported API.
78  *  If you write code that depends on this, you do so at your own risk.
79  *  This code and its internal interfaces are subject to change or
80  *  deletion without notice.</b>
81  */
82 public class Check {
83     protected static final Context.Key<Check> checkKey = new Context.Key<>();
84 
85     private final Names names;
86     private final Log log;
87     private final Resolve rs;
88     private final Symtab syms;
89     private final Enter enter;
90     private final DeferredAttr deferredAttr;
91     private final Infer infer;
92     private final Types types;
93     private final TypeAnnotations typeAnnotations;
94     private final JCDiagnostic.Factory diags;
95     private final JavaFileManager fileManager;
96     private final Source source;
97     private final Target target;
98     private final Profile profile;
99     private final Preview preview;
100     private final boolean warnOnAnyAccessToMembers;
101 
102     // The set of lint options currently in effect. It is initialized
103     // from the context, and then is set/reset as needed by Attr as it
104     // visits all the various parts of the trees during attribution.
105     private Lint lint;
106 
107     // The method being analyzed in Attr - it is set/reset as needed by
108     // Attr as it visits new method declarations.
109     private MethodSymbol method;
110 
instance(Context context)111     public static Check instance(Context context) {
112         Check instance = context.get(checkKey);
113         if (instance == null)
114             instance = new Check(context);
115         return instance;
116     }
117 
Check(Context context)118     protected Check(Context context) {
119         context.put(checkKey, this);
120 
121         names = Names.instance(context);
122         log = Log.instance(context);
123         rs = Resolve.instance(context);
124         syms = Symtab.instance(context);
125         enter = Enter.instance(context);
126         deferredAttr = DeferredAttr.instance(context);
127         infer = Infer.instance(context);
128         types = Types.instance(context);
129         typeAnnotations = TypeAnnotations.instance(context);
130         diags = JCDiagnostic.Factory.instance(context);
131         Options options = Options.instance(context);
132         lint = Lint.instance(context);
133         fileManager = context.get(JavaFileManager.class);
134 
135         source = Source.instance(context);
136         target = Target.instance(context);
137         warnOnAnyAccessToMembers = options.isSet("warnOnAccessToMembers");
138 
139         Target target = Target.instance(context);
140         syntheticNameChar = target.syntheticNameChar();
141 
142         profile = Profile.instance(context);
143         preview = Preview.instance(context);
144 
145         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
146         boolean verboseRemoval = lint.isEnabled(LintCategory.REMOVAL);
147         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
148         boolean enforceMandatoryWarnings = true;
149 
150         deprecationHandler = new MandatoryWarningHandler(log, null, verboseDeprecated,
151                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
152         removalHandler = new MandatoryWarningHandler(log, null, verboseRemoval,
153                 enforceMandatoryWarnings, "removal", LintCategory.REMOVAL);
154         uncheckedHandler = new MandatoryWarningHandler(log, null, verboseUnchecked,
155                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
156         sunApiHandler = new MandatoryWarningHandler(log, null, false,
157                 enforceMandatoryWarnings, "sunapi", null);
158 
159         deferredLintHandler = DeferredLintHandler.instance(context);
160 
161         allowModules = Feature.MODULES.allowedInSource(source);
162         allowRecords = Feature.RECORDS.allowedInSource(source);
163         allowSealed = Feature.SEALED_CLASSES.allowedInSource(source);
164     }
165 
166     /** Character for synthetic names
167      */
168     char syntheticNameChar;
169 
170     /** A table mapping flat names of all compiled classes for each module in this run
171      *  to their symbols; maintained from outside.
172      */
173     private Map<Pair<ModuleSymbol, Name>,ClassSymbol> compiled = new HashMap<>();
174 
175     /** A handler for messages about deprecated usage.
176      */
177     private MandatoryWarningHandler deprecationHandler;
178 
179     /** A handler for messages about deprecated-for-removal usage.
180      */
181     private MandatoryWarningHandler removalHandler;
182 
183     /** A handler for messages about unchecked or unsafe usage.
184      */
185     private MandatoryWarningHandler uncheckedHandler;
186 
187     /** A handler for messages about using proprietary API.
188      */
189     private MandatoryWarningHandler sunApiHandler;
190 
191     /** A handler for deferred lint warnings.
192      */
193     private DeferredLintHandler deferredLintHandler;
194 
195     /** Are modules allowed
196      */
197     private final boolean allowModules;
198 
199     /** Are records allowed
200      */
201     private final boolean allowRecords;
202 
203     /** Are sealed classes allowed
204      */
205     private final boolean allowSealed;
206 
207 /* *************************************************************************
208  * Errors and Warnings
209  **************************************************************************/
210 
setLint(Lint newLint)211     Lint setLint(Lint newLint) {
212         Lint prev = lint;
213         lint = newLint;
214         return prev;
215     }
216 
setMethod(MethodSymbol newMethod)217     MethodSymbol setMethod(MethodSymbol newMethod) {
218         MethodSymbol prev = method;
219         method = newMethod;
220         return prev;
221     }
222 
223     /** Warn about deprecated symbol.
224      *  @param pos        Position to be used for error reporting.
225      *  @param sym        The deprecated symbol.
226      */
warnDeprecated(DiagnosticPosition pos, Symbol sym)227     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
228         if (sym.isDeprecatedForRemoval()) {
229             if (!lint.isSuppressed(LintCategory.REMOVAL)) {
230                 if (sym.kind == MDL) {
231                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemovalModule(sym));
232                 } else {
233                     removalHandler.report(pos, Warnings.HasBeenDeprecatedForRemoval(sym, sym.location()));
234                 }
235             }
236         } else if (!lint.isSuppressed(LintCategory.DEPRECATION)) {
237             if (sym.kind == MDL) {
238                 deprecationHandler.report(pos, Warnings.HasBeenDeprecatedModule(sym));
239             } else {
240                 deprecationHandler.report(pos, Warnings.HasBeenDeprecated(sym, sym.location()));
241             }
242         }
243     }
244 
245     /** Log a preview warning.
246      *  @param pos        Position to be used for error reporting.
247      *  @param msg        A Warning describing the problem.
248      */
warnPreviewAPI(DiagnosticPosition pos, Warning warnKey)249     public void warnPreviewAPI(DiagnosticPosition pos, Warning warnKey) {
250         if (!lint.isSuppressed(LintCategory.PREVIEW))
251             preview.reportPreviewWarning(pos, warnKey);
252     }
253 
254     /** Log a preview warning.
255      *  @param pos        Position to be used for error reporting.
256      *  @param msg        A Warning describing the problem.
257      */
warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym)258     public void warnDeclaredUsingPreview(DiagnosticPosition pos, Symbol sym) {
259         if (!lint.isSuppressed(LintCategory.PREVIEW))
260             preview.reportPreviewWarning(pos, Warnings.DeclaredUsingPreview(kindName(sym), sym));
261     }
262 
263     /** Warn about unchecked operation.
264      *  @param pos        Position to be used for error reporting.
265      *  @param msg        A string describing the problem.
266      */
warnUnchecked(DiagnosticPosition pos, Warning warnKey)267     public void warnUnchecked(DiagnosticPosition pos, Warning warnKey) {
268         if (!lint.isSuppressed(LintCategory.UNCHECKED))
269             uncheckedHandler.report(pos, warnKey);
270     }
271 
272     /** Warn about unsafe vararg method decl.
273      *  @param pos        Position to be used for error reporting.
274      */
warnUnsafeVararg(DiagnosticPosition pos, Warning warnKey)275     void warnUnsafeVararg(DiagnosticPosition pos, Warning warnKey) {
276         if (lint.isEnabled(LintCategory.VARARGS))
277             log.warning(LintCategory.VARARGS, pos, warnKey);
278     }
279 
warnStatic(DiagnosticPosition pos, Warning warnKey)280     public void warnStatic(DiagnosticPosition pos, Warning warnKey) {
281         if (lint.isEnabled(LintCategory.STATIC))
282             log.warning(LintCategory.STATIC, pos, warnKey);
283     }
284 
285     /** Warn about division by integer constant zero.
286      *  @param pos        Position to be used for error reporting.
287      */
warnDivZero(DiagnosticPosition pos)288     void warnDivZero(DiagnosticPosition pos) {
289         if (lint.isEnabled(LintCategory.DIVZERO))
290             log.warning(LintCategory.DIVZERO, pos, Warnings.DivZero);
291     }
292 
293     /**
294      * Report any deferred diagnostics.
295      */
reportDeferredDiagnostics()296     public void reportDeferredDiagnostics() {
297         deprecationHandler.reportDeferredDiagnostic();
298         removalHandler.reportDeferredDiagnostic();
299         uncheckedHandler.reportDeferredDiagnostic();
300         sunApiHandler.reportDeferredDiagnostic();
301     }
302 
303 
304     /** Report a failure to complete a class.
305      *  @param pos        Position to be used for error reporting.
306      *  @param ex         The failure to report.
307      */
completionError(DiagnosticPosition pos, CompletionFailure ex)308     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
309         log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, Errors.CantAccess(ex.sym, ex.getDetailValue()));
310         return syms.errType;
311     }
312 
313     /** Report an error that wrong type tag was found.
314      *  @param pos        Position to be used for error reporting.
315      *  @param required   An internationalized string describing the type tag
316      *                    required.
317      *  @param found      The type that was found.
318      */
typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found)319     Type typeTagError(DiagnosticPosition pos, JCDiagnostic required, Object found) {
320         // this error used to be raised by the parser,
321         // but has been delayed to this point:
322         if (found instanceof Type type && type.hasTag(VOID)) {
323             log.error(pos, Errors.IllegalStartOfType);
324             return syms.errType;
325         }
326         log.error(pos, Errors.TypeFoundReq(found, required));
327         return types.createErrorType(found instanceof Type type ? type : syms.errType);
328     }
329 
330     /** Report an error that symbol cannot be referenced before super
331      *  has been called.
332      *  @param pos        Position to be used for error reporting.
333      *  @param sym        The referenced symbol.
334      */
earlyRefError(DiagnosticPosition pos, Symbol sym)335     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
336         log.error(pos, Errors.CantRefBeforeCtorCalled(sym));
337     }
338 
339     /** Report duplicate declaration error.
340      */
duplicateError(DiagnosticPosition pos, Symbol sym)341     void duplicateError(DiagnosticPosition pos, Symbol sym) {
342         if (!sym.type.isErroneous()) {
343             Symbol location = sym.location();
344             if (location.kind == MTH &&
345                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
346                 log.error(pos,
347                           Errors.AlreadyDefinedInClinit(kindName(sym),
348                                                         sym,
349                                                         kindName(sym.location()),
350                                                         kindName(sym.location().enclClass()),
351                                                         sym.location().enclClass()));
352             } else {
353                 /* dont error if this is a duplicated parameter of a generated canonical constructor
354                  * as we should have issued an error for the duplicated fields
355                  */
356                 if (location.kind != MTH ||
357                         ((sym.owner.flags_field & GENERATEDCONSTR) == 0) ||
358                         ((sym.owner.flags_field & RECORD) == 0)) {
359                     log.error(pos,
360                             Errors.AlreadyDefined(kindName(sym),
361                                     sym,
362                                     kindName(sym.location()),
363                                     sym.location()));
364                 }
365             }
366         }
367     }
368 
369     /** Report array/varargs duplicate declaration
370      */
varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2)371     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
372         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
373             log.error(pos, Errors.ArrayAndVarargs(sym1, sym2, sym2.location()));
374         }
375     }
376 
377 /* ************************************************************************
378  * duplicate declaration checking
379  *************************************************************************/
380 
381     /** Check that variable does not hide variable with same name in
382      *  immediately enclosing local scope.
383      *  @param pos           Position for error reporting.
384      *  @param v             The symbol.
385      *  @param s             The scope.
386      */
checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s)387     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
388         for (Symbol sym : s.getSymbolsByName(v.name)) {
389             if (sym.owner != v.owner) break;
390             if (sym.kind == VAR &&
391                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
392                 v.name != names.error) {
393                 duplicateError(pos, sym);
394                 return;
395             }
396         }
397     }
398 
399     /** Check that a class or interface does not hide a class or
400      *  interface with same name in immediately enclosing local scope.
401      *  @param pos           Position for error reporting.
402      *  @param c             The symbol.
403      *  @param s             The scope.
404      */
checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s)405     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
406         for (Symbol sym : s.getSymbolsByName(c.name)) {
407             if (sym.owner != c.owner) break;
408             if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR) &&
409                 sym.owner.kind.matches(KindSelector.VAL_MTH) &&
410                 c.name != names.error) {
411                 duplicateError(pos, sym);
412                 return;
413             }
414         }
415     }
416 
417     /** Check that class does not have the same name as one of
418      *  its enclosing classes, or as a class defined in its enclosing scope.
419      *  return true if class is unique in its enclosing scope.
420      *  @param pos           Position for error reporting.
421      *  @param name          The class name.
422      *  @param s             The enclosing scope.
423      */
checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s)424     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
425         for (Symbol sym : s.getSymbolsByName(name, NON_RECURSIVE)) {
426             if (sym.kind == TYP && sym.name != names.error) {
427                 duplicateError(pos, sym);
428                 return false;
429             }
430         }
431         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
432             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
433                 duplicateError(pos, sym);
434                 return true;
435             }
436         }
437         return true;
438     }
439 
440 /* *************************************************************************
441  * Class name generation
442  **************************************************************************/
443 
444 
445     private Map<Pair<Name, Name>, Integer> localClassNameIndexes = new HashMap<>();
446 
447     /** Return name of local class.
448      *  This is of the form   {@code <enclClass> $ n <classname> }
449      *  where
450      *    enclClass is the flat name of the enclosing class,
451      *    classname is the simple name of the local class
452      */
localClassName(ClassSymbol c)453     public Name localClassName(ClassSymbol c) {
454         Name enclFlatname = c.owner.enclClass().flatname;
455         String enclFlatnameStr = enclFlatname.toString();
456         Pair<Name, Name> key = new Pair<>(enclFlatname, c.name);
457         Integer index = localClassNameIndexes.get(key);
458         for (int i = (index == null) ? 1 : index; ; i++) {
459             Name flatname = names.fromString(enclFlatnameStr
460                     + syntheticNameChar + i + c.name);
461             if (getCompiled(c.packge().modle, flatname) == null) {
462                 localClassNameIndexes.put(key, i + 1);
463                 return flatname;
464             }
465         }
466     }
467 
clearLocalClassNameIndexes(ClassSymbol c)468     public void clearLocalClassNameIndexes(ClassSymbol c) {
469         if (c.owner != null && c.owner.kind != NIL) {
470             localClassNameIndexes.remove(new Pair<>(
471                     c.owner.enclClass().flatname, c.name));
472         }
473     }
474 
newRound()475     public void newRound() {
476         compiled.clear();
477         localClassNameIndexes.clear();
478     }
479 
clear()480     public void clear() {
481         deprecationHandler.clear();
482         removalHandler.clear();
483         uncheckedHandler.clear();
484         sunApiHandler.clear();
485     }
486 
putCompiled(ClassSymbol csym)487     public void putCompiled(ClassSymbol csym) {
488         compiled.put(Pair.of(csym.packge().modle, csym.flatname), csym);
489     }
490 
getCompiled(ClassSymbol csym)491     public ClassSymbol getCompiled(ClassSymbol csym) {
492         return compiled.get(Pair.of(csym.packge().modle, csym.flatname));
493     }
494 
getCompiled(ModuleSymbol msym, Name flatname)495     public ClassSymbol getCompiled(ModuleSymbol msym, Name flatname) {
496         return compiled.get(Pair.of(msym, flatname));
497     }
498 
removeCompiled(ClassSymbol csym)499     public void removeCompiled(ClassSymbol csym) {
500         compiled.remove(Pair.of(csym.packge().modle, csym.flatname));
501     }
502 
503 /* *************************************************************************
504  * Type Checking
505  **************************************************************************/
506 
507     /**
508      * A check context is an object that can be used to perform compatibility
509      * checks - depending on the check context, meaning of 'compatibility' might
510      * vary significantly.
511      */
512     public interface CheckContext {
513         /**
514          * Is type 'found' compatible with type 'req' in given context
515          */
compatible(Type found, Type req, Warner warn)516         boolean compatible(Type found, Type req, Warner warn);
517         /**
518          * Report a check error
519          */
report(DiagnosticPosition pos, JCDiagnostic details)520         void report(DiagnosticPosition pos, JCDiagnostic details);
521         /**
522          * Obtain a warner for this check context
523          */
checkWarner(DiagnosticPosition pos, Type found, Type req)524         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
525 
inferenceContext()526         public InferenceContext inferenceContext();
527 
deferredAttrContext()528         public DeferredAttr.DeferredAttrContext deferredAttrContext();
529     }
530 
531     /**
532      * This class represent a check context that is nested within another check
533      * context - useful to check sub-expressions. The default behavior simply
534      * redirects all method calls to the enclosing check context leveraging
535      * the forwarding pattern.
536      */
537     static class NestedCheckContext implements CheckContext {
538         CheckContext enclosingContext;
539 
NestedCheckContext(CheckContext enclosingContext)540         NestedCheckContext(CheckContext enclosingContext) {
541             this.enclosingContext = enclosingContext;
542         }
543 
compatible(Type found, Type req, Warner warn)544         public boolean compatible(Type found, Type req, Warner warn) {
545             return enclosingContext.compatible(found, req, warn);
546         }
547 
report(DiagnosticPosition pos, JCDiagnostic details)548         public void report(DiagnosticPosition pos, JCDiagnostic details) {
549             enclosingContext.report(pos, details);
550         }
551 
checkWarner(DiagnosticPosition pos, Type found, Type req)552         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
553             return enclosingContext.checkWarner(pos, found, req);
554         }
555 
inferenceContext()556         public InferenceContext inferenceContext() {
557             return enclosingContext.inferenceContext();
558         }
559 
deferredAttrContext()560         public DeferredAttrContext deferredAttrContext() {
561             return enclosingContext.deferredAttrContext();
562         }
563     }
564 
565     /**
566      * Check context to be used when evaluating assignment/return statements
567      */
568     CheckContext basicHandler = new CheckContext() {
569         public void report(DiagnosticPosition pos, JCDiagnostic details) {
570             log.error(pos, Errors.ProbFoundReq(details));
571         }
572         public boolean compatible(Type found, Type req, Warner warn) {
573             return types.isAssignable(found, req, warn);
574         }
575 
576         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
577             return convertWarner(pos, found, req);
578         }
579 
580         public InferenceContext inferenceContext() {
581             return infer.emptyContext;
582         }
583 
584         public DeferredAttrContext deferredAttrContext() {
585             return deferredAttr.emptyDeferredAttrContext;
586         }
587 
588         @Override
589         public String toString() {
590             return "CheckContext: basicHandler";
591         }
592     };
593 
594     /** Check that a given type is assignable to a given proto-type.
595      *  If it is, return the type, otherwise return errType.
596      *  @param pos        Position to be used for error reporting.
597      *  @param found      The type that was found.
598      *  @param req        The type that was required.
599      */
checkType(DiagnosticPosition pos, Type found, Type req)600     public Type checkType(DiagnosticPosition pos, Type found, Type req) {
601         return checkType(pos, found, req, basicHandler);
602     }
603 
checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext)604     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
605         final InferenceContext inferenceContext = checkContext.inferenceContext();
606         if (inferenceContext.free(req) || inferenceContext.free(found)) {
607             inferenceContext.addFreeTypeListener(List.of(req, found),
608                     solvedContext -> checkType(pos, solvedContext.asInstType(found), solvedContext.asInstType(req), checkContext));
609         }
610         if (req.hasTag(ERROR))
611             return req;
612         if (req.hasTag(NONE))
613             return found;
614         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
615             return found;
616         } else {
617             if (found.isNumeric() && req.isNumeric()) {
618                 checkContext.report(pos, diags.fragment(Fragments.PossibleLossOfPrecision(found, req)));
619                 return types.createErrorType(found);
620             }
621             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
622             return types.createErrorType(found);
623         }
624     }
625 
626     /** Check that a given type can be cast to a given target type.
627      *  Return the result of the cast.
628      *  @param pos        Position to be used for error reporting.
629      *  @param found      The type that is being cast.
630      *  @param req        The target type of the cast.
631      */
checkCastable(DiagnosticPosition pos, Type found, Type req)632     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
633         return checkCastable(pos, found, req, basicHandler);
634     }
checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext)635     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
636         if (types.isCastable(found, req, castWarner(pos, found, req))) {
637             return req;
638         } else {
639             checkContext.report(pos, diags.fragment(Fragments.InconvertibleTypes(found, req)));
640             return types.createErrorType(found);
641         }
642     }
643 
644     /** Check for redundant casts (i.e. where source type is a subtype of target type)
645      * The problem should only be reported for non-292 cast
646      */
checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree)647     public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
648         if (!tree.type.isErroneous()
649                 && types.isSameType(tree.expr.type, tree.clazz.type)
650                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
651                 && !is292targetTypeCast(tree)) {
652             deferredLintHandler.report(() -> {
653                 if (lint.isEnabled(LintCategory.CAST))
654                     log.warning(LintCategory.CAST,
655                             tree.pos(), Warnings.RedundantCast(tree.clazz.type));
656             });
657         }
658     }
659     //where
is292targetTypeCast(JCTypeCast tree)660         private boolean is292targetTypeCast(JCTypeCast tree) {
661             boolean is292targetTypeCast = false;
662             JCExpression expr = TreeInfo.skipParens(tree.expr);
663             if (expr.hasTag(APPLY)) {
664                 JCMethodInvocation apply = (JCMethodInvocation)expr;
665                 Symbol sym = TreeInfo.symbol(apply.meth);
666                 is292targetTypeCast = sym != null &&
667                     sym.kind == MTH &&
668                     (sym.flags() & HYPOTHETICAL) != 0;
669             }
670             return is292targetTypeCast;
671         }
672 
673         private static final boolean ignoreAnnotatedCasts = true;
674 
675     /** Check that a type is within some bounds.
676      *
677      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
678      *  type argument.
679      *  @param a             The type that should be bounded by bs.
680      *  @param bound         The bound.
681      */
checkExtends(Type a, Type bound)682     private boolean checkExtends(Type a, Type bound) {
683          if (a.isUnbound()) {
684              return true;
685          } else if (!a.hasTag(WILDCARD)) {
686              a = types.cvarUpperBound(a);
687              return types.isSubtype(a, bound);
688          } else if (a.isExtendsBound()) {
689              return types.isCastable(bound, types.wildUpperBound(a), types.noWarnings);
690          } else if (a.isSuperBound()) {
691              return !types.notSoftSubtype(types.wildLowerBound(a), bound);
692          }
693          return true;
694      }
695 
696     /** Check that type is different from 'void'.
697      *  @param pos           Position to be used for error reporting.
698      *  @param t             The type to be checked.
699      */
checkNonVoid(DiagnosticPosition pos, Type t)700     Type checkNonVoid(DiagnosticPosition pos, Type t) {
701         if (t.hasTag(VOID)) {
702             log.error(pos, Errors.VoidNotAllowedHere);
703             return types.createErrorType(t);
704         } else {
705             return t;
706         }
707     }
708 
checkClassOrArrayType(DiagnosticPosition pos, Type t)709     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
710         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
711             return typeTagError(pos,
712                                 diags.fragment(Fragments.TypeReqClassArray),
713                                 asTypeParam(t));
714         } else {
715             return t;
716         }
717     }
718 
719     /** Check that type is a class or interface type.
720      *  @param pos           Position to be used for error reporting.
721      *  @param t             The type to be checked.
722      */
checkClassType(DiagnosticPosition pos, Type t)723     Type checkClassType(DiagnosticPosition pos, Type t) {
724         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
725             return typeTagError(pos,
726                                 diags.fragment(Fragments.TypeReqClass),
727                                 asTypeParam(t));
728         } else {
729             return t;
730         }
731     }
732     //where
asTypeParam(Type t)733         private Object asTypeParam(Type t) {
734             return (t.hasTag(TYPEVAR))
735                                     ? diags.fragment(Fragments.TypeParameter(t))
736                                     : t;
737         }
738 
739     /** Check that type is a valid qualifier for a constructor reference expression
740      */
checkConstructorRefType(DiagnosticPosition pos, Type t)741     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
742         t = checkClassOrArrayType(pos, t);
743         if (t.hasTag(CLASS)) {
744             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
745                 log.error(pos, Errors.AbstractCantBeInstantiated(t.tsym));
746                 t = types.createErrorType(t);
747             } else if ((t.tsym.flags() & ENUM) != 0) {
748                 log.error(pos, Errors.EnumCantBeInstantiated);
749                 t = types.createErrorType(t);
750             } else {
751                 t = checkClassType(pos, t, true);
752             }
753         } else if (t.hasTag(ARRAY)) {
754             if (!types.isReifiable(((ArrayType)t).elemtype)) {
755                 log.error(pos, Errors.GenericArrayCreation);
756                 t = types.createErrorType(t);
757             }
758         }
759         return t;
760     }
761 
762     /** Check that type is a class or interface type.
763      *  @param pos           Position to be used for error reporting.
764      *  @param t             The type to be checked.
765      *  @param noBounds    True if type bounds are illegal here.
766      */
checkClassType(DiagnosticPosition pos, Type t, boolean noBounds)767     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
768         t = checkClassType(pos, t);
769         if (noBounds && t.isParameterized()) {
770             List<Type> args = t.getTypeArguments();
771             while (args.nonEmpty()) {
772                 if (args.head.hasTag(WILDCARD))
773                     return typeTagError(pos,
774                                         diags.fragment(Fragments.TypeReqExact),
775                                         args.head);
776                 args = args.tail;
777             }
778         }
779         return t;
780     }
781 
782     /** Check that type is a reference type, i.e. a class, interface or array type
783      *  or a type variable.
784      *  @param pos           Position to be used for error reporting.
785      *  @param t             The type to be checked.
786      */
checkRefType(DiagnosticPosition pos, Type t)787     Type checkRefType(DiagnosticPosition pos, Type t) {
788         if (t.isReference())
789             return t;
790         else
791             return typeTagError(pos,
792                                 diags.fragment(Fragments.TypeReqRef),
793                                 t);
794     }
795 
796     /** Check that each type is a reference type, i.e. a class, interface or array type
797      *  or a type variable.
798      *  @param trees         Original trees, used for error reporting.
799      *  @param types         The types to be checked.
800      */
checkRefTypes(List<JCExpression> trees, List<Type> types)801     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
802         List<JCExpression> tl = trees;
803         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
804             l.head = checkRefType(tl.head.pos(), l.head);
805             tl = tl.tail;
806         }
807         return types;
808     }
809 
810     /** Check that type is a null or reference type.
811      *  @param pos           Position to be used for error reporting.
812      *  @param t             The type to be checked.
813      */
checkNullOrRefType(DiagnosticPosition pos, Type t)814     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
815         if (t.isReference() || t.hasTag(BOT))
816             return t;
817         else
818             return typeTagError(pos,
819                                 diags.fragment(Fragments.TypeReqRef),
820                                 t);
821     }
822 
823     /** Check that flag set does not contain elements of two conflicting sets. s
824      *  Return true if it doesn't.
825      *  @param pos           Position to be used for error reporting.
826      *  @param flags         The set of flags to be checked.
827      *  @param set1          Conflicting flags set #1.
828      *  @param set2          Conflicting flags set #2.
829      */
checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2)830     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
831         if ((flags & set1) != 0 && (flags & set2) != 0) {
832             log.error(pos,
833                       Errors.IllegalCombinationOfModifiers(asFlagSet(TreeInfo.firstFlag(flags & set1)),
834                                                            asFlagSet(TreeInfo.firstFlag(flags & set2))));
835             return false;
836         } else
837             return true;
838     }
839 
840     /** Check that usage of diamond operator is correct (i.e. diamond should not
841      * be used with non-generic classes or in anonymous class creation expressions)
842      */
checkDiamond(JCNewClass tree, Type t)843     Type checkDiamond(JCNewClass tree, Type t) {
844         if (!TreeInfo.isDiamond(tree) ||
845                 t.isErroneous()) {
846             return checkClassType(tree.clazz.pos(), t, true);
847         } else {
848             if (tree.def != null && !Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.allowedInSource(source)) {
849                 log.error(DiagnosticFlag.SOURCE_LEVEL, tree.clazz.pos(),
850                         Errors.CantApplyDiamond1(t, Feature.DIAMOND_WITH_ANONYMOUS_CLASS_CREATION.fragment(source.name)));
851             }
852             if (t.tsym.type.getTypeArguments().isEmpty()) {
853                 log.error(tree.clazz.pos(),
854                           Errors.CantApplyDiamond1(t,
855                                                    Fragments.DiamondNonGeneric(t)));
856                 return types.createErrorType(t);
857             } else if (tree.typeargs != null &&
858                     tree.typeargs.nonEmpty()) {
859                 log.error(tree.clazz.pos(),
860                           Errors.CantApplyDiamond1(t,
861                                                    Fragments.DiamondAndExplicitParams(t)));
862                 return types.createErrorType(t);
863             } else {
864                 return t;
865             }
866         }
867     }
868 
869     /** Check that the type inferred using the diamond operator does not contain
870      *  non-denotable types such as captured types or intersection types.
871      *  @param t the type inferred using the diamond operator
872      *  @return  the (possibly empty) list of non-denotable types.
873      */
checkDiamondDenotable(ClassType t)874     List<Type> checkDiamondDenotable(ClassType t) {
875         ListBuffer<Type> buf = new ListBuffer<>();
876         for (Type arg : t.allparams()) {
877             if (!checkDenotable(arg)) {
878                 buf.append(arg);
879             }
880         }
881         return buf.toList();
882     }
883 
checkDenotable(Type t)884     public boolean checkDenotable(Type t) {
885         return denotableChecker.visit(t, null);
886     }
887         // where
888 
889         /** diamondTypeChecker: A type visitor that descends down the given type looking for non-denotable
890          *  types. The visit methods return false as soon as a non-denotable type is encountered and true
891          *  otherwise.
892          */
893         private static final Types.SimpleVisitor<Boolean, Void> denotableChecker = new Types.SimpleVisitor<Boolean, Void>() {
894             @Override
895             public Boolean visitType(Type t, Void s) {
896                 return true;
897             }
898             @Override
899             public Boolean visitClassType(ClassType t, Void s) {
900                 if (t.isUnion() || t.isIntersection()) {
901                     return false;
902                 }
903                 for (Type targ : t.allparams()) {
904                     if (!visit(targ, s)) {
905                         return false;
906                     }
907                 }
908                 return true;
909             }
910 
911             @Override
912             public Boolean visitTypeVar(TypeVar t, Void s) {
913                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
914                   (i.e cannot have been produced by inference (18.4))
915                 */
916                 return (t.tsym.flags() & SYNTHETIC) == 0;
917             }
918 
919             @Override
920             public Boolean visitCapturedType(CapturedType t, Void s) {
921                 /* Any type variable mentioned in the inferred type must have been declared as a type parameter
922                   (i.e cannot have been produced by capture conversion (5.1.10))
923                 */
924                 return false;
925             }
926 
927             @Override
928             public Boolean visitArrayType(ArrayType t, Void s) {
929                 return visit(t.elemtype, s);
930             }
931 
932             @Override
933             public Boolean visitWildcardType(WildcardType t, Void s) {
934                 return visit(t.type, s);
935             }
936         };
937 
checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree)938     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
939         MethodSymbol m = tree.sym;
940         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
941         Type varargElemType = null;
942         if (m.isVarArgs()) {
943             varargElemType = types.elemtype(tree.params.last().type);
944         }
945         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
946             if (varargElemType != null) {
947                 JCDiagnostic msg = Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ?
948                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargs(m)) :
949                         diags.fragment(Fragments.VarargsTrustmeOnVirtualVarargsFinalOnly(m));
950                 log.error(tree,
951                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
952                                                            msg));
953             } else {
954                 log.error(tree,
955                           Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym,
956                                                            Fragments.VarargsTrustmeOnNonVarargsMeth(m)));
957             }
958         } else if (hasTrustMeAnno && varargElemType != null &&
959                             types.isReifiable(varargElemType)) {
960             warnUnsafeVararg(tree, Warnings.VarargsRedundantTrustmeAnno(
961                                 syms.trustMeType.tsym,
962                                 diags.fragment(Fragments.VarargsTrustmeOnReifiableVarargs(varargElemType))));
963         }
964         else if (!hasTrustMeAnno && varargElemType != null &&
965                 !types.isReifiable(varargElemType)) {
966             warnUnchecked(tree.params.head.pos(), Warnings.UncheckedVarargsNonReifiableType(varargElemType));
967         }
968     }
969     //where
isTrustMeAllowedOnMethod(Symbol s)970         private boolean isTrustMeAllowedOnMethod(Symbol s) {
971             return (s.flags() & VARARGS) != 0 &&
972                 (s.isConstructor() ||
973                     (s.flags() & (STATIC | FINAL |
974                                   (Feature.PRIVATE_SAFE_VARARGS.allowedInSource(source) ? PRIVATE : 0) )) != 0);
975         }
976 
checkLocalVarType(DiagnosticPosition pos, Type t, Name name)977     Type checkLocalVarType(DiagnosticPosition pos, Type t, Name name) {
978         //check that resulting type is not the null type
979         if (t.hasTag(BOT)) {
980             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferNull));
981             return types.createErrorType(t);
982         } else if (t.hasTag(VOID)) {
983             log.error(pos, Errors.CantInferLocalVarType(name, Fragments.LocalCantInferVoid));
984             return types.createErrorType(t);
985         }
986 
987         //upward project the initializer type
988         return types.upward(t, types.captures(t));
989     }
990 
checkMethod(final Type mtype, final Symbol sym, final Env<AttrContext> env, final List<JCExpression> argtrees, final List<Type> argtypes, final boolean useVarargs, InferenceContext inferenceContext)991     Type checkMethod(final Type mtype,
992             final Symbol sym,
993             final Env<AttrContext> env,
994             final List<JCExpression> argtrees,
995             final List<Type> argtypes,
996             final boolean useVarargs,
997             InferenceContext inferenceContext) {
998         // System.out.println("call   : " + env.tree);
999         // System.out.println("method : " + owntype);
1000         // System.out.println("actuals: " + argtypes);
1001         if (inferenceContext.free(mtype)) {
1002             inferenceContext.addFreeTypeListener(List.of(mtype),
1003                     solvedContext -> checkMethod(solvedContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, solvedContext));
1004             return mtype;
1005         }
1006         Type owntype = mtype;
1007         List<Type> formals = owntype.getParameterTypes();
1008         List<Type> nonInferred = sym.type.getParameterTypes();
1009         if (nonInferred.length() != formals.length()) nonInferred = formals;
1010         Type last = useVarargs ? formals.last() : null;
1011         if (sym.name == names.init && sym.owner == syms.enumSym) {
1012             formals = formals.tail.tail;
1013             nonInferred = nonInferred.tail.tail;
1014         }
1015         if ((sym.flags() & ANONCONSTR_BASED) != 0) {
1016             formals = formals.tail;
1017             nonInferred = nonInferred.tail;
1018         }
1019         List<JCExpression> args = argtrees;
1020         if (args != null) {
1021             //this is null when type-checking a method reference
1022             while (formals.head != last) {
1023                 JCTree arg = args.head;
1024                 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
1025                 assertConvertible(arg, arg.type, formals.head, warn);
1026                 args = args.tail;
1027                 formals = formals.tail;
1028                 nonInferred = nonInferred.tail;
1029             }
1030             if (useVarargs) {
1031                 Type varArg = types.elemtype(last);
1032                 while (args.tail != null) {
1033                     JCTree arg = args.head;
1034                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
1035                     assertConvertible(arg, arg.type, varArg, warn);
1036                     args = args.tail;
1037                 }
1038             } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS) {
1039                 // non-varargs call to varargs method
1040                 Type varParam = owntype.getParameterTypes().last();
1041                 Type lastArg = argtypes.last();
1042                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
1043                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
1044                     log.warning(argtrees.last().pos(),
1045                                 Warnings.InexactNonVarargsCall(types.elemtype(varParam),varParam));
1046             }
1047         }
1048         if (useVarargs) {
1049             Type argtype = owntype.getParameterTypes().last();
1050             if (!types.isReifiable(argtype) &&
1051                 (sym.baseSymbol().attribute(syms.trustMeType.tsym) == null ||
1052                  !isTrustMeAllowedOnMethod(sym))) {
1053                 warnUnchecked(env.tree.pos(), Warnings.UncheckedGenericArrayCreation(argtype));
1054             }
1055             TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
1056          }
1057          return owntype;
1058     }
1059     //where
assertConvertible(JCTree tree, Type actual, Type formal, Warner warn)1060     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
1061         if (types.isConvertible(actual, formal, warn))
1062             return;
1063 
1064         if (formal.isCompound()
1065             && types.isSubtype(actual, types.supertype(formal))
1066             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
1067             return;
1068     }
1069 
1070     /**
1071      * Check that type 't' is a valid instantiation of a generic class
1072      * (see JLS 4.5)
1073      *
1074      * @param t class type to be checked
1075      * @return true if 't' is well-formed
1076      */
checkValidGenericType(Type t)1077     public boolean checkValidGenericType(Type t) {
1078         return firstIncompatibleTypeArg(t) == null;
1079     }
1080     //WHERE
firstIncompatibleTypeArg(Type type)1081         private Type firstIncompatibleTypeArg(Type type) {
1082             List<Type> formals = type.tsym.type.allparams();
1083             List<Type> actuals = type.allparams();
1084             List<Type> args = type.getTypeArguments();
1085             List<Type> forms = type.tsym.type.getTypeArguments();
1086             ListBuffer<Type> bounds_buf = new ListBuffer<>();
1087 
1088             // For matching pairs of actual argument types `a' and
1089             // formal type parameters with declared bound `b' ...
1090             while (args.nonEmpty() && forms.nonEmpty()) {
1091                 // exact type arguments needs to know their
1092                 // bounds (for upper and lower bound
1093                 // calculations).  So we create new bounds where
1094                 // type-parameters are replaced with actuals argument types.
1095                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
1096                 args = args.tail;
1097                 forms = forms.tail;
1098             }
1099 
1100             args = type.getTypeArguments();
1101             List<Type> tvars_cap = types.substBounds(formals,
1102                                       formals,
1103                                       types.capture(type).allparams());
1104             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
1105                 // Let the actual arguments know their bound
1106                 args.head.withTypeVar((TypeVar)tvars_cap.head);
1107                 args = args.tail;
1108                 tvars_cap = tvars_cap.tail;
1109             }
1110 
1111             args = type.getTypeArguments();
1112             List<Type> bounds = bounds_buf.toList();
1113 
1114             while (args.nonEmpty() && bounds.nonEmpty()) {
1115                 Type actual = args.head;
1116                 if (!isTypeArgErroneous(actual) &&
1117                         !bounds.head.isErroneous() &&
1118                         !checkExtends(actual, bounds.head)) {
1119                     return args.head;
1120                 }
1121                 args = args.tail;
1122                 bounds = bounds.tail;
1123             }
1124 
1125             args = type.getTypeArguments();
1126             bounds = bounds_buf.toList();
1127 
1128             for (Type arg : types.capture(type).getTypeArguments()) {
1129                 if (arg.hasTag(TYPEVAR) &&
1130                         arg.getUpperBound().isErroneous() &&
1131                         !bounds.head.isErroneous() &&
1132                         !isTypeArgErroneous(args.head)) {
1133                     return args.head;
1134                 }
1135                 bounds = bounds.tail;
1136                 args = args.tail;
1137             }
1138 
1139             return null;
1140         }
1141         //where
isTypeArgErroneous(Type t)1142         boolean isTypeArgErroneous(Type t) {
1143             return isTypeArgErroneous.visit(t);
1144         }
1145 
1146         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
1147             public Boolean visitType(Type t, Void s) {
1148                 return t.isErroneous();
1149             }
1150             @Override
1151             public Boolean visitTypeVar(TypeVar t, Void s) {
1152                 return visit(t.getUpperBound());
1153             }
1154             @Override
1155             public Boolean visitCapturedType(CapturedType t, Void s) {
1156                 return visit(t.getUpperBound()) ||
1157                         visit(t.getLowerBound());
1158             }
1159             @Override
1160             public Boolean visitWildcardType(WildcardType t, Void s) {
1161                 return visit(t.type);
1162             }
1163         };
1164 
1165     /** Check that given modifiers are legal for given symbol and
1166      *  return modifiers together with any implicit modifiers for that symbol.
1167      *  Warning: we can't use flags() here since this method
1168      *  is called during class enter, when flags() would cause a premature
1169      *  completion.
1170      *  @param pos           Position to be used for error reporting.
1171      *  @param flags         The set of modifiers given in a definition.
1172      *  @param sym           The defined symbol.
1173      */
checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree)1174     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
1175         long mask;
1176         long implicit = 0;
1177 
1178         switch (sym.kind) {
1179         case VAR:
1180             if (TreeInfo.isReceiverParam(tree))
1181                 mask = ReceiverParamFlags;
1182             else if (sym.owner.kind != TYP)
1183                 mask = LocalVarFlags;
1184             else if ((sym.owner.flags_field & INTERFACE) != 0)
1185                 mask = implicit = InterfaceVarFlags;
1186             else
1187                 mask = VarFlags;
1188             break;
1189         case MTH:
1190             if (sym.name == names.init) {
1191                 if ((sym.owner.flags_field & ENUM) != 0) {
1192                     // enum constructors cannot be declared public or
1193                     // protected and must be implicitly or explicitly
1194                     // private
1195                     implicit = PRIVATE;
1196                     mask = PRIVATE;
1197                 } else
1198                     mask = ConstructorFlags;
1199             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
1200                 if ((sym.owner.flags_field & ANNOTATION) != 0) {
1201                     mask = AnnotationTypeElementMask;
1202                     implicit = PUBLIC | ABSTRACT;
1203                 } else if ((flags & (DEFAULT | STATIC | PRIVATE)) != 0) {
1204                     mask = InterfaceMethodMask;
1205                     implicit = (flags & PRIVATE) != 0 ? 0 : PUBLIC;
1206                     if ((flags & DEFAULT) != 0) {
1207                         implicit |= ABSTRACT;
1208                     }
1209                 } else {
1210                     mask = implicit = InterfaceMethodFlags;
1211                 }
1212             } else if ((sym.owner.flags_field & RECORD) != 0) {
1213                 mask = RecordMethodFlags;
1214             } else {
1215                 mask = MethodFlags;
1216             }
1217             if ((flags & STRICTFP) != 0) {
1218                 warnOnExplicitStrictfp(pos);
1219             }
1220             // Imply STRICTFP if owner has STRICTFP set.
1221             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
1222                 ((flags) & Flags.DEFAULT) != 0)
1223                 implicit |= sym.owner.flags_field & STRICTFP;
1224             break;
1225         case TYP:
1226             if (sym.owner.kind.matches(KindSelector.VAL_MTH) ||
1227                     (sym.isDirectlyOrIndirectlyLocal() && (flags & ANNOTATION) != 0)) {
1228                 boolean implicitlyStatic = !sym.isAnonymous() &&
1229                         ((flags & RECORD) != 0 || (flags & ENUM) != 0 || (flags & INTERFACE) != 0);
1230                 boolean staticOrImplicitlyStatic = (flags & STATIC) != 0 || implicitlyStatic;
1231                 // local statics are allowed only if records are allowed too
1232                 mask = staticOrImplicitlyStatic && allowRecords && (flags & ANNOTATION) == 0 ? StaticLocalFlags : LocalClassFlags;
1233                 implicit = implicitlyStatic ? STATIC : implicit;
1234             } else if (sym.owner.kind == TYP) {
1235                 // statics in inner classes are allowed only if records are allowed too
1236                 mask = ((flags & STATIC) != 0) && allowRecords && (flags & ANNOTATION) == 0 ? ExtendedMemberStaticClassFlags : ExtendedMemberClassFlags;
1237                 if (sym.owner.owner.kind == PCK ||
1238                     (sym.owner.flags_field & STATIC) != 0) {
1239                     mask |= STATIC;
1240                 } else if (!allowRecords && ((flags & ENUM) != 0 || (flags & RECORD) != 0)) {
1241                     log.error(pos, Errors.StaticDeclarationNotAllowedInInnerClasses);
1242                 }
1243                 // Nested interfaces and enums are always STATIC (Spec ???)
1244                 if ((flags & (INTERFACE | ENUM | RECORD)) != 0 ) implicit = STATIC;
1245             } else {
1246                 mask = ExtendedClassFlags;
1247             }
1248             // Interfaces are always ABSTRACT
1249             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
1250 
1251             if ((flags & ENUM) != 0) {
1252                 // enums can't be declared abstract, final, sealed or non-sealed
1253                 mask &= ~(ABSTRACT | FINAL | SEALED | NON_SEALED);
1254                 implicit |= implicitEnumFinalFlag(tree);
1255             }
1256             if ((flags & RECORD) != 0) {
1257                 // records can't be declared abstract
1258                 mask &= ~ABSTRACT;
1259                 implicit |= FINAL;
1260             }
1261             if ((flags & STRICTFP) != 0) {
1262                 warnOnExplicitStrictfp(pos);
1263             }
1264             // Imply STRICTFP if owner has STRICTFP set.
1265             implicit |= sym.owner.flags_field & STRICTFP;
1266             break;
1267         default:
1268             throw new AssertionError();
1269         }
1270         long illegal = flags & ExtendedStandardFlags & ~mask;
1271         if (illegal != 0) {
1272             if ((illegal & INTERFACE) != 0) {
1273                 log.error(pos, ((flags & ANNOTATION) != 0) ? Errors.AnnotationDeclNotAllowedHere : Errors.IntfNotAllowedHere);
1274                 mask |= INTERFACE;
1275             }
1276             else {
1277                 log.error(pos,
1278                         Errors.ModNotAllowedHere(asFlagSet(illegal)));
1279             }
1280         }
1281         else if ((sym.kind == TYP ||
1282                   // ISSUE: Disallowing abstract&private is no longer appropriate
1283                   // in the presence of inner classes. Should it be deleted here?
1284                   checkDisjoint(pos, flags,
1285                                 ABSTRACT,
1286                                 PRIVATE | STATIC | DEFAULT))
1287                  &&
1288                  checkDisjoint(pos, flags,
1289                                 STATIC | PRIVATE,
1290                                 DEFAULT)
1291                  &&
1292                  checkDisjoint(pos, flags,
1293                                ABSTRACT | INTERFACE,
1294                                FINAL | NATIVE | SYNCHRONIZED)
1295                  &&
1296                  checkDisjoint(pos, flags,
1297                                PUBLIC,
1298                                PRIVATE | PROTECTED)
1299                  &&
1300                  checkDisjoint(pos, flags,
1301                                PRIVATE,
1302                                PUBLIC | PROTECTED)
1303                  &&
1304                  checkDisjoint(pos, flags,
1305                                FINAL,
1306                                VOLATILE)
1307                  &&
1308                  (sym.kind == TYP ||
1309                   checkDisjoint(pos, flags,
1310                                 ABSTRACT | NATIVE,
1311                                 STRICTFP))
1312                  && checkDisjoint(pos, flags,
1313                                 FINAL,
1314                            SEALED | NON_SEALED)
1315                  && checkDisjoint(pos, flags,
1316                                 SEALED,
1317                            FINAL | NON_SEALED)
1318                  && checkDisjoint(pos, flags,
1319                                 SEALED,
1320                                 ANNOTATION)) {
1321             // skip
1322         }
1323         return flags & (mask | ~ExtendedStandardFlags) | implicit;
1324     }
1325 
warnOnExplicitStrictfp(DiagnosticPosition pos)1326     private void warnOnExplicitStrictfp(DiagnosticPosition pos) {
1327         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(pos);
1328         try {
1329             deferredLintHandler.report(() -> {
1330                                            if (lint.isEnabled(LintCategory.STRICTFP)) {
1331                                                log.warning(LintCategory.STRICTFP,
1332                                                            pos, Warnings.Strictfp); }
1333                                        });
1334         } finally {
1335             deferredLintHandler.setPos(prevLintPos);
1336         }
1337     }
1338 
1339 
1340     /** Determine if this enum should be implicitly final.
1341      *
1342      *  If the enum has no specialized enum constants, it is final.
1343      *
1344      *  If the enum does have specialized enum constants, it is
1345      *  <i>not</i> final.
1346      */
implicitEnumFinalFlag(JCTree tree)1347     private long implicitEnumFinalFlag(JCTree tree) {
1348         if (!tree.hasTag(CLASSDEF)) return 0;
1349         class SpecialTreeVisitor extends JCTree.Visitor {
1350             boolean specialized;
1351             SpecialTreeVisitor() {
1352                 this.specialized = false;
1353             }
1354 
1355             @Override
1356             public void visitTree(JCTree tree) { /* no-op */ }
1357 
1358             @Override
1359             public void visitVarDef(JCVariableDecl tree) {
1360                 if ((tree.mods.flags & ENUM) != 0) {
1361                     if (tree.init instanceof JCNewClass newClass && newClass.def != null) {
1362                         specialized = true;
1363                     }
1364                 }
1365             }
1366         }
1367 
1368         SpecialTreeVisitor sts = new SpecialTreeVisitor();
1369         JCClassDecl cdef = (JCClassDecl) tree;
1370         for (JCTree defs: cdef.defs) {
1371             defs.accept(sts);
1372             if (sts.specialized) return allowSealed ? SEALED : 0;
1373         }
1374         return FINAL;
1375     }
1376 
1377 /* *************************************************************************
1378  * Type Validation
1379  **************************************************************************/
1380 
1381     /** Validate a type expression. That is,
1382      *  check that all type arguments of a parametric type are within
1383      *  their bounds. This must be done in a second phase after type attribution
1384      *  since a class might have a subclass as type parameter bound. E.g:
1385      *
1386      *  <pre>{@code
1387      *  class B<A extends C> { ... }
1388      *  class C extends B<C> { ... }
1389      *  }</pre>
1390      *
1391      *  and we can't make sure that the bound is already attributed because
1392      *  of possible cycles.
1393      *
1394      * Visitor method: Validate a type expression, if it is not null, catching
1395      *  and reporting any completion failures.
1396      */
validate(JCTree tree, Env<AttrContext> env)1397     void validate(JCTree tree, Env<AttrContext> env) {
1398         validate(tree, env, true);
1399     }
validate(JCTree tree, Env<AttrContext> env, boolean checkRaw)1400     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
1401         new Validator(env).validateTree(tree, checkRaw, true);
1402     }
1403 
1404     /** Visitor method: Validate a list of type expressions.
1405      */
validate(List<? extends JCTree> trees, Env<AttrContext> env)1406     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
1407         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1408             validate(l.head, env);
1409     }
1410 
1411     /** A visitor class for type validation.
1412      */
1413     class Validator extends JCTree.Visitor {
1414 
1415         boolean checkRaw;
1416         boolean isOuter;
1417         Env<AttrContext> env;
1418 
Validator(Env<AttrContext> env)1419         Validator(Env<AttrContext> env) {
1420             this.env = env;
1421         }
1422 
1423         @Override
visitTypeArray(JCArrayTypeTree tree)1424         public void visitTypeArray(JCArrayTypeTree tree) {
1425             validateTree(tree.elemtype, checkRaw, isOuter);
1426         }
1427 
1428         @Override
visitTypeApply(JCTypeApply tree)1429         public void visitTypeApply(JCTypeApply tree) {
1430             if (tree.type.hasTag(CLASS)) {
1431                 List<JCExpression> args = tree.arguments;
1432                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
1433 
1434                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
1435                 if (incompatibleArg != null) {
1436                     for (JCTree arg : tree.arguments) {
1437                         if (arg.type == incompatibleArg) {
1438                             log.error(arg, Errors.NotWithinBounds(incompatibleArg, forms.head));
1439                         }
1440                         forms = forms.tail;
1441                      }
1442                  }
1443 
1444                 forms = tree.type.tsym.type.getTypeArguments();
1445 
1446                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
1447 
1448                 // For matching pairs of actual argument types `a' and
1449                 // formal type parameters with declared bound `b' ...
1450                 while (args.nonEmpty() && forms.nonEmpty()) {
1451                     validateTree(args.head,
1452                             !(isOuter && is_java_lang_Class),
1453                             false);
1454                     args = args.tail;
1455                     forms = forms.tail;
1456                 }
1457 
1458                 // Check that this type is either fully parameterized, or
1459                 // not parameterized at all.
1460                 if (tree.type.getEnclosingType().isRaw())
1461                     log.error(tree.pos(), Errors.ImproperlyFormedTypeInnerRawParam);
1462                 if (tree.clazz.hasTag(SELECT))
1463                     visitSelectInternal((JCFieldAccess)tree.clazz);
1464             }
1465         }
1466 
1467         @Override
visitTypeParameter(JCTypeParameter tree)1468         public void visitTypeParameter(JCTypeParameter tree) {
1469             validateTrees(tree.bounds, true, isOuter);
1470             checkClassBounds(tree.pos(), tree.type);
1471         }
1472 
1473         @Override
visitWildcard(JCWildcard tree)1474         public void visitWildcard(JCWildcard tree) {
1475             if (tree.inner != null)
1476                 validateTree(tree.inner, true, isOuter);
1477         }
1478 
1479         @Override
visitSelect(JCFieldAccess tree)1480         public void visitSelect(JCFieldAccess tree) {
1481             if (tree.type.hasTag(CLASS)) {
1482                 visitSelectInternal(tree);
1483 
1484                 // Check that this type is either fully parameterized, or
1485                 // not parameterized at all.
1486                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
1487                     log.error(tree.pos(), Errors.ImproperlyFormedTypeParamMissing);
1488             }
1489         }
1490 
visitSelectInternal(JCFieldAccess tree)1491         public void visitSelectInternal(JCFieldAccess tree) {
1492             if (tree.type.tsym.isStatic() &&
1493                 tree.selected.type.isParameterized()) {
1494                 // The enclosing type is not a class, so we are
1495                 // looking at a static member type.  However, the
1496                 // qualifying expression is parameterized.
1497                 log.error(tree.pos(), Errors.CantSelectStaticClassFromParamType);
1498             } else {
1499                 // otherwise validate the rest of the expression
1500                 tree.selected.accept(this);
1501             }
1502         }
1503 
1504         @Override
visitAnnotatedType(JCAnnotatedType tree)1505         public void visitAnnotatedType(JCAnnotatedType tree) {
1506             tree.underlyingType.accept(this);
1507         }
1508 
1509         @Override
visitTypeIdent(JCPrimitiveTypeTree that)1510         public void visitTypeIdent(JCPrimitiveTypeTree that) {
1511             if (that.type.hasTag(TypeTag.VOID)) {
1512                 log.error(that.pos(), Errors.VoidNotAllowedHere);
1513             }
1514             super.visitTypeIdent(that);
1515         }
1516 
1517         /** Default visitor method: do nothing.
1518          */
1519         @Override
visitTree(JCTree tree)1520         public void visitTree(JCTree tree) {
1521         }
1522 
validateTree(JCTree tree, boolean checkRaw, boolean isOuter)1523         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
1524             if (tree != null) {
1525                 boolean prevCheckRaw = this.checkRaw;
1526                 this.checkRaw = checkRaw;
1527                 this.isOuter = isOuter;
1528 
1529                 try {
1530                     tree.accept(this);
1531                     if (checkRaw)
1532                         checkRaw(tree, env);
1533                 } catch (CompletionFailure ex) {
1534                     completionError(tree.pos(), ex);
1535                 } finally {
1536                     this.checkRaw = prevCheckRaw;
1537                 }
1538             }
1539         }
1540 
validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter)1541         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
1542             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
1543                 validateTree(l.head, checkRaw, isOuter);
1544         }
1545     }
1546 
checkRaw(JCTree tree, Env<AttrContext> env)1547     void checkRaw(JCTree tree, Env<AttrContext> env) {
1548         if (lint.isEnabled(LintCategory.RAW) &&
1549             tree.type.hasTag(CLASS) &&
1550             !TreeInfo.isDiamond(tree) &&
1551             !withinAnonConstr(env) &&
1552             tree.type.isRaw()) {
1553             log.warning(LintCategory.RAW,
1554                     tree.pos(), Warnings.RawClassUse(tree.type, tree.type.tsym.type));
1555         }
1556     }
1557     //where
withinAnonConstr(Env<AttrContext> env)1558         private boolean withinAnonConstr(Env<AttrContext> env) {
1559             return env.enclClass.name.isEmpty() &&
1560                     env.enclMethod != null && env.enclMethod.name == names.init;
1561         }
1562 
1563 /* *************************************************************************
1564  * Exception checking
1565  **************************************************************************/
1566 
1567     /* The following methods treat classes as sets that contain
1568      * the class itself and all their subclasses
1569      */
1570 
1571     /** Is given type a subtype of some of the types in given list?
1572      */
subset(Type t, List<Type> ts)1573     boolean subset(Type t, List<Type> ts) {
1574         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1575             if (types.isSubtype(t, l.head)) return true;
1576         return false;
1577     }
1578 
1579     /** Is given type a subtype or supertype of
1580      *  some of the types in given list?
1581      */
intersects(Type t, List<Type> ts)1582     boolean intersects(Type t, List<Type> ts) {
1583         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1584             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
1585         return false;
1586     }
1587 
1588     /** Add type set to given type list, unless it is a subclass of some class
1589      *  in the list.
1590      */
incl(Type t, List<Type> ts)1591     List<Type> incl(Type t, List<Type> ts) {
1592         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
1593     }
1594 
1595     /** Remove type set from type set list.
1596      */
excl(Type t, List<Type> ts)1597     List<Type> excl(Type t, List<Type> ts) {
1598         if (ts.isEmpty()) {
1599             return ts;
1600         } else {
1601             List<Type> ts1 = excl(t, ts.tail);
1602             if (types.isSubtype(ts.head, t)) return ts1;
1603             else if (ts1 == ts.tail) return ts;
1604             else return ts1.prepend(ts.head);
1605         }
1606     }
1607 
1608     /** Form the union of two type set lists.
1609      */
union(List<Type> ts1, List<Type> ts2)1610     List<Type> union(List<Type> ts1, List<Type> ts2) {
1611         List<Type> ts = ts1;
1612         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1613             ts = incl(l.head, ts);
1614         return ts;
1615     }
1616 
1617     /** Form the difference of two type lists.
1618      */
diff(List<Type> ts1, List<Type> ts2)1619     List<Type> diff(List<Type> ts1, List<Type> ts2) {
1620         List<Type> ts = ts1;
1621         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1622             ts = excl(l.head, ts);
1623         return ts;
1624     }
1625 
1626     /** Form the intersection of two type lists.
1627      */
intersect(List<Type> ts1, List<Type> ts2)1628     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
1629         List<Type> ts = List.nil();
1630         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
1631             if (subset(l.head, ts2)) ts = incl(l.head, ts);
1632         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
1633             if (subset(l.head, ts1)) ts = incl(l.head, ts);
1634         return ts;
1635     }
1636 
1637     /** Is exc an exception symbol that need not be declared?
1638      */
isUnchecked(ClassSymbol exc)1639     boolean isUnchecked(ClassSymbol exc) {
1640         return
1641             exc.kind == ERR ||
1642             exc.isSubClass(syms.errorType.tsym, types) ||
1643             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
1644     }
1645 
1646     /** Is exc an exception type that need not be declared?
1647      */
isUnchecked(Type exc)1648     boolean isUnchecked(Type exc) {
1649         return
1650             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
1651             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
1652             exc.hasTag(BOT);
1653     }
1654 
isChecked(Type exc)1655     boolean isChecked(Type exc) {
1656         return !isUnchecked(exc);
1657     }
1658 
1659     /** Same, but handling completion failures.
1660      */
isUnchecked(DiagnosticPosition pos, Type exc)1661     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
1662         try {
1663             return isUnchecked(exc);
1664         } catch (CompletionFailure ex) {
1665             completionError(pos, ex);
1666             return true;
1667         }
1668     }
1669 
1670     /** Is exc handled by given exception list?
1671      */
isHandled(Type exc, List<Type> handled)1672     boolean isHandled(Type exc, List<Type> handled) {
1673         return isUnchecked(exc) || subset(exc, handled);
1674     }
1675 
1676     /** Return all exceptions in thrown list that are not in handled list.
1677      *  @param thrown     The list of thrown exceptions.
1678      *  @param handled    The list of handled exceptions.
1679      */
unhandled(List<Type> thrown, List<Type> handled)1680     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
1681         List<Type> unhandled = List.nil();
1682         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1683             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
1684         return unhandled;
1685     }
1686 
1687 /* *************************************************************************
1688  * Overriding/Implementation checking
1689  **************************************************************************/
1690 
1691     /** The level of access protection given by a flag set,
1692      *  where PRIVATE is highest and PUBLIC is lowest.
1693      */
protection(long flags)1694     static int protection(long flags) {
1695         switch ((short)(flags & AccessFlags)) {
1696         case PRIVATE: return 3;
1697         case PROTECTED: return 1;
1698         default:
1699         case PUBLIC: return 0;
1700         case 0: return 2;
1701         }
1702     }
1703 
1704     /** A customized "cannot override" error message.
1705      *  @param m      The overriding method.
1706      *  @param other  The overridden method.
1707      *  @return       An internationalized string.
1708      */
cannotOverride(MethodSymbol m, MethodSymbol other)1709     Fragment cannotOverride(MethodSymbol m, MethodSymbol other) {
1710         Symbol mloc = m.location();
1711         Symbol oloc = other.location();
1712 
1713         if ((other.owner.flags() & INTERFACE) == 0)
1714             return Fragments.CantOverride(m, mloc, other, oloc);
1715         else if ((m.owner.flags() & INTERFACE) == 0)
1716             return Fragments.CantImplement(m, mloc, other, oloc);
1717         else
1718             return Fragments.ClashesWith(m, mloc, other, oloc);
1719     }
1720 
1721     /** A customized "override" warning message.
1722      *  @param m      The overriding method.
1723      *  @param other  The overridden method.
1724      *  @return       An internationalized string.
1725      */
uncheckedOverrides(MethodSymbol m, MethodSymbol other)1726     Fragment uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
1727         Symbol mloc = m.location();
1728         Symbol oloc = other.location();
1729 
1730         if ((other.owner.flags() & INTERFACE) == 0)
1731             return Fragments.UncheckedOverride(m, mloc, other, oloc);
1732         else if ((m.owner.flags() & INTERFACE) == 0)
1733             return Fragments.UncheckedImplement(m, mloc, other, oloc);
1734         else
1735             return Fragments.UncheckedClashWith(m, mloc, other, oloc);
1736     }
1737 
1738     /** A customized "override" warning message.
1739      *  @param m      The overriding method.
1740      *  @param other  The overridden method.
1741      *  @return       An internationalized string.
1742      */
varargsOverrides(MethodSymbol m, MethodSymbol other)1743     Fragment varargsOverrides(MethodSymbol m, MethodSymbol other) {
1744         Symbol mloc = m.location();
1745         Symbol oloc = other.location();
1746 
1747         if ((other.owner.flags() & INTERFACE) == 0)
1748             return Fragments.VarargsOverride(m, mloc, other, oloc);
1749         else  if ((m.owner.flags() & INTERFACE) == 0)
1750             return Fragments.VarargsImplement(m, mloc, other, oloc);
1751         else
1752             return Fragments.VarargsClashWith(m, mloc, other, oloc);
1753     }
1754 
1755     /** Check that this method conforms with overridden method 'other'.
1756      *  where `origin' is the class where checking started.
1757      *  Complications:
1758      *  (1) Do not check overriding of synthetic methods
1759      *      (reason: they might be final).
1760      *      todo: check whether this is still necessary.
1761      *  (2) Admit the case where an interface proxy throws fewer exceptions
1762      *      than the method it implements. Augment the proxy methods with the
1763      *      undeclared exceptions in this case.
1764      *  (3) When generics are enabled, admit the case where an interface proxy
1765      *      has a result type
1766      *      extended by the result type of the method it implements.
1767      *      Change the proxies result type to the smaller type in this case.
1768      *
1769      *  @param tree         The tree from which positions
1770      *                      are extracted for errors.
1771      *  @param m            The overriding method.
1772      *  @param other        The overridden method.
1773      *  @param origin       The class of which the overriding method
1774      *                      is a member.
1775      */
checkOverride(JCTree tree, MethodSymbol m, MethodSymbol other, ClassSymbol origin)1776     void checkOverride(JCTree tree,
1777                        MethodSymbol m,
1778                        MethodSymbol other,
1779                        ClassSymbol origin) {
1780         // Don't check overriding of synthetic methods or by bridge methods.
1781         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
1782             return;
1783         }
1784 
1785         // Error if static method overrides instance method (JLS 8.4.6.2).
1786         if ((m.flags() & STATIC) != 0 &&
1787                    (other.flags() & STATIC) == 0) {
1788             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1789                       Errors.OverrideStatic(cannotOverride(m, other)));
1790             m.flags_field |= BAD_OVERRIDE;
1791             return;
1792         }
1793 
1794         // Error if instance method overrides static or final
1795         // method (JLS 8.4.6.1).
1796         if ((other.flags() & FINAL) != 0 ||
1797                  (m.flags() & STATIC) == 0 &&
1798                  (other.flags() & STATIC) != 0) {
1799             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1800                       Errors.OverrideMeth(cannotOverride(m, other),
1801                                           asFlagSet(other.flags() & (FINAL | STATIC))));
1802             m.flags_field |= BAD_OVERRIDE;
1803             return;
1804         }
1805 
1806         if ((m.owner.flags() & ANNOTATION) != 0) {
1807             // handled in validateAnnotationMethod
1808             return;
1809         }
1810 
1811         // Error if overriding method has weaker access (JLS 8.4.6.3).
1812         if (protection(m.flags()) > protection(other.flags())) {
1813             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1814                       (other.flags() & AccessFlags) == 0 ?
1815                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1816                                                           "package") :
1817                               Errors.OverrideWeakerAccess(cannotOverride(m, other),
1818                                                           asFlagSet(other.flags() & AccessFlags)));
1819             m.flags_field |= BAD_OVERRIDE;
1820             return;
1821         }
1822 
1823         Type mt = types.memberType(origin.type, m);
1824         Type ot = types.memberType(origin.type, other);
1825         // Error if overriding result type is different
1826         // (or, in the case of generics mode, not a subtype) of
1827         // overridden result type. We have to rename any type parameters
1828         // before comparing types.
1829         List<Type> mtvars = mt.getTypeArguments();
1830         List<Type> otvars = ot.getTypeArguments();
1831         Type mtres = mt.getReturnType();
1832         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
1833 
1834         overrideWarner.clear();
1835         boolean resultTypesOK =
1836             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
1837         if (!resultTypesOK) {
1838             if ((m.flags() & STATIC) != 0 && (other.flags() & STATIC) != 0) {
1839                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1840                           Errors.OverrideIncompatibleRet(Fragments.CantHide(m, m.location(), other,
1841                                         other.location()), mtres, otres));
1842                 m.flags_field |= BAD_OVERRIDE;
1843             } else {
1844                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
1845                           Errors.OverrideIncompatibleRet(cannotOverride(m, other), mtres, otres));
1846                 m.flags_field |= BAD_OVERRIDE;
1847             }
1848             return;
1849         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
1850             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1851                     Warnings.OverrideUncheckedRet(uncheckedOverrides(m, other), mtres, otres));
1852         }
1853 
1854         // Error if overriding method throws an exception not reported
1855         // by overridden method.
1856         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
1857         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
1858         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
1859         if (unhandledErased.nonEmpty()) {
1860             log.error(TreeInfo.diagnosticPositionFor(m, tree),
1861                       Errors.OverrideMethDoesntThrow(cannotOverride(m, other), unhandledUnerased.head));
1862             m.flags_field |= BAD_OVERRIDE;
1863             return;
1864         }
1865         else if (unhandledUnerased.nonEmpty()) {
1866             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
1867                           Warnings.OverrideUncheckedThrown(cannotOverride(m, other), unhandledUnerased.head));
1868             return;
1869         }
1870 
1871         // Optional warning if varargs don't agree
1872         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
1873             && lint.isEnabled(LintCategory.OVERRIDES)) {
1874             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1875                         ((m.flags() & Flags.VARARGS) != 0)
1876                         ? Warnings.OverrideVarargsMissing(varargsOverrides(m, other))
1877                         : Warnings.OverrideVarargsExtra(varargsOverrides(m, other)));
1878         }
1879 
1880         // Warn if instance method overrides bridge method (compiler spec ??)
1881         if ((other.flags() & BRIDGE) != 0) {
1882             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
1883                         Warnings.OverrideBridge(uncheckedOverrides(m, other)));
1884         }
1885 
1886         // Warn if a deprecated method overridden by a non-deprecated one.
1887         if (!isDeprecatedOverrideIgnorable(other, origin)) {
1888             Lint prevLint = setLint(lint.augment(m));
1889             try {
1890                 checkDeprecated(() -> TreeInfo.diagnosticPositionFor(m, tree), m, other);
1891             } finally {
1892                 setLint(prevLint);
1893             }
1894         }
1895     }
1896     // where
isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin)1897         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
1898             // If the method, m, is defined in an interface, then ignore the issue if the method
1899             // is only inherited via a supertype and also implemented in the supertype,
1900             // because in that case, we will rediscover the issue when examining the method
1901             // in the supertype.
1902             // If the method, m, is not defined in an interface, then the only time we need to
1903             // address the issue is when the method is the supertype implementation: any other
1904             // case, we will have dealt with when examining the supertype classes
1905             ClassSymbol mc = m.enclClass();
1906             Type st = types.supertype(origin.type);
1907             if (!st.hasTag(CLASS))
1908                 return true;
1909             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
1910 
1911             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
1912                 List<Type> intfs = types.interfaces(origin.type);
1913                 return (intfs.contains(mc.type) ? false : (stimpl != null));
1914             }
1915             else
1916                 return (stimpl != m);
1917         }
1918 
1919 
1920     // used to check if there were any unchecked conversions
1921     Warner overrideWarner = new Warner();
1922 
1923     /** Check that a class does not inherit two concrete methods
1924      *  with the same signature.
1925      *  @param pos          Position to be used for error reporting.
1926      *  @param site         The class type to be checked.
1927      */
checkCompatibleConcretes(DiagnosticPosition pos, Type site)1928     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
1929         Type sup = types.supertype(site);
1930         if (!sup.hasTag(CLASS)) return;
1931 
1932         for (Type t1 = sup;
1933              t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
1934              t1 = types.supertype(t1)) {
1935             for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
1936                 if (s1.kind != MTH ||
1937                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1938                     !s1.isInheritedIn(site.tsym, types) ||
1939                     ((MethodSymbol)s1).implementation(site.tsym,
1940                                                       types,
1941                                                       true) != s1)
1942                     continue;
1943                 Type st1 = types.memberType(t1, s1);
1944                 int s1ArgsLength = st1.getParameterTypes().length();
1945                 if (st1 == s1.type) continue;
1946 
1947                 for (Type t2 = sup;
1948                      t2.hasTag(CLASS);
1949                      t2 = types.supertype(t2)) {
1950                     for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
1951                         if (s2 == s1 ||
1952                             s2.kind != MTH ||
1953                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
1954                             s2.type.getParameterTypes().length() != s1ArgsLength ||
1955                             !s2.isInheritedIn(site.tsym, types) ||
1956                             ((MethodSymbol)s2).implementation(site.tsym,
1957                                                               types,
1958                                                               true) != s2)
1959                             continue;
1960                         Type st2 = types.memberType(t2, s2);
1961                         if (types.overrideEquivalent(st1, st2))
1962                             log.error(pos,
1963                                       Errors.ConcreteInheritanceConflict(s1, t1, s2, t2, sup));
1964                     }
1965                 }
1966             }
1967         }
1968     }
1969 
1970     /** Check that classes (or interfaces) do not each define an abstract
1971      *  method with same name and arguments but incompatible return types.
1972      *  @param pos          Position to be used for error reporting.
1973      *  @param t1           The first argument type.
1974      *  @param t2           The second argument type.
1975      */
checkCompatibleAbstracts(DiagnosticPosition pos, Type t1, Type t2, Type site)1976     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
1977                                             Type t1,
1978                                             Type t2,
1979                                             Type site) {
1980         if ((site.tsym.flags() & COMPOUND) != 0) {
1981             // special case for intersections: need to eliminate wildcards in supertypes
1982             t1 = types.capture(t1);
1983             t2 = types.capture(t2);
1984         }
1985         return firstIncompatibility(pos, t1, t2, site) == null;
1986     }
1987 
1988     /** Return the first method which is defined with same args
1989      *  but different return types in two given interfaces, or null if none
1990      *  exists.
1991      *  @param t1     The first type.
1992      *  @param t2     The second type.
1993      *  @param site   The most derived type.
1994      *  @return symbol from t2 that conflicts with one in t1.
1995      */
firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site)1996     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
1997         Map<TypeSymbol,Type> interfaces1 = new HashMap<>();
1998         closure(t1, interfaces1);
1999         Map<TypeSymbol,Type> interfaces2;
2000         if (t1 == t2)
2001             interfaces2 = interfaces1;
2002         else
2003             closure(t2, interfaces1, interfaces2 = new HashMap<>());
2004 
2005         for (Type t3 : interfaces1.values()) {
2006             for (Type t4 : interfaces2.values()) {
2007                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
2008                 if (s != null) return s;
2009             }
2010         }
2011         return null;
2012     }
2013 
2014     /** Compute all the supertypes of t, indexed by type symbol. */
closure(Type t, Map<TypeSymbol,Type> typeMap)2015     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
2016         if (!t.hasTag(CLASS)) return;
2017         if (typeMap.put(t.tsym, t) == null) {
2018             closure(types.supertype(t), typeMap);
2019             for (Type i : types.interfaces(t))
2020                 closure(i, typeMap);
2021         }
2022     }
2023 
2024     /** Compute all the supertypes of t, indexed by type symbol (except those in typesSkip). */
closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap)2025     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
2026         if (!t.hasTag(CLASS)) return;
2027         if (typesSkip.get(t.tsym) != null) return;
2028         if (typeMap.put(t.tsym, t) == null) {
2029             closure(types.supertype(t), typesSkip, typeMap);
2030             for (Type i : types.interfaces(t))
2031                 closure(i, typesSkip, typeMap);
2032         }
2033     }
2034 
2035     /** Return the first method in t2 that conflicts with a method from t1. */
firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site)2036     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
2037         for (Symbol s1 : t1.tsym.members().getSymbols(NON_RECURSIVE)) {
2038             Type st1 = null;
2039             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
2040                     (s1.flags() & SYNTHETIC) != 0) continue;
2041             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
2042             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
2043             for (Symbol s2 : t2.tsym.members().getSymbolsByName(s1.name)) {
2044                 if (s1 == s2) continue;
2045                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
2046                         (s2.flags() & SYNTHETIC) != 0) continue;
2047                 if (st1 == null) st1 = types.memberType(t1, s1);
2048                 Type st2 = types.memberType(t2, s2);
2049                 if (types.overrideEquivalent(st1, st2)) {
2050                     List<Type> tvars1 = st1.getTypeArguments();
2051                     List<Type> tvars2 = st2.getTypeArguments();
2052                     Type rt1 = st1.getReturnType();
2053                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
2054                     boolean compat =
2055                         types.isSameType(rt1, rt2) ||
2056                         !rt1.isPrimitiveOrVoid() &&
2057                         !rt2.isPrimitiveOrVoid() &&
2058                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
2059                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
2060                          checkCommonOverriderIn(s1,s2,site);
2061                     if (!compat) {
2062                         log.error(pos, Errors.TypesIncompatible(t1, t2,
2063                                 Fragments.IncompatibleDiffRet(s2.name, types.memberType(t2, s2).getParameterTypes())));
2064                         return s2;
2065                     }
2066                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
2067                         !checkCommonOverriderIn(s1, s2, site)) {
2068                     log.error(pos, Errors.NameClashSameErasureNoOverride(
2069                             s1.name, types.memberType(site, s1).asMethodType().getParameterTypes(), s1.location(),
2070                             s2.name, types.memberType(site, s2).asMethodType().getParameterTypes(), s2.location()));
2071                     return s2;
2072                 }
2073             }
2074         }
2075         return null;
2076     }
2077     //WHERE
checkCommonOverriderIn(Symbol s1, Symbol s2, Type site)2078     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
2079         Map<TypeSymbol,Type> supertypes = new HashMap<>();
2080         Type st1 = types.memberType(site, s1);
2081         Type st2 = types.memberType(site, s2);
2082         closure(site, supertypes);
2083         for (Type t : supertypes.values()) {
2084             for (Symbol s3 : t.tsym.members().getSymbolsByName(s1.name)) {
2085                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
2086                 Type st3 = types.memberType(site,s3);
2087                 if (types.overrideEquivalent(st3, st1) &&
2088                         types.overrideEquivalent(st3, st2) &&
2089                         types.returnTypeSubstitutable(st3, st1) &&
2090                         types.returnTypeSubstitutable(st3, st2)) {
2091                     return true;
2092                 }
2093             }
2094         }
2095         return false;
2096     }
2097 
2098     /** Check that a given method conforms with any method it overrides.
2099      *  @param tree         The tree from which positions are extracted
2100      *                      for errors.
2101      *  @param m            The overriding method.
2102      */
checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m)2103     void checkOverride(Env<AttrContext> env, JCMethodDecl tree, MethodSymbol m) {
2104         ClassSymbol origin = (ClassSymbol)m.owner;
2105         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name)) {
2106             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
2107                 log.error(tree.pos(), Errors.EnumNoFinalize);
2108                 return;
2109             }
2110         }
2111         if (allowRecords && origin.isRecord()) {
2112             // let's find out if this is a user defined accessor in which case the @Override annotation is acceptable
2113             Optional<? extends RecordComponent> recordComponent = origin.getRecordComponents().stream()
2114                     .filter(rc -> rc.accessor == tree.sym && (rc.accessor.flags_field & GENERATED_MEMBER) == 0).findFirst();
2115             if (recordComponent.isPresent()) {
2116                 return;
2117             }
2118         }
2119 
2120         for (Type t = origin.type; t.hasTag(CLASS);
2121              t = types.supertype(t)) {
2122             if (t != origin.type) {
2123                 checkOverride(tree, t, origin, m);
2124             }
2125             for (Type t2 : types.interfaces(t)) {
2126                 checkOverride(tree, t2, origin, m);
2127             }
2128         }
2129 
2130         final boolean explicitOverride = m.attribute(syms.overrideType.tsym) != null;
2131         // Check if this method must override a super method due to being annotated with @Override
2132         // or by virtue of being a member of a diamond inferred anonymous class. Latter case is to
2133         // be treated "as if as they were annotated" with @Override.
2134         boolean mustOverride = explicitOverride ||
2135                 (env.info.isAnonymousDiamond && !m.isConstructor() && !m.isPrivate());
2136         if (mustOverride && !isOverrider(m)) {
2137             DiagnosticPosition pos = tree.pos();
2138             for (JCAnnotation a : tree.getModifiers().annotations) {
2139                 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
2140                     pos = a.pos();
2141                     break;
2142                 }
2143             }
2144             log.error(pos,
2145                       explicitOverride ? (m.isStatic() ? Errors.StaticMethodsCannotBeAnnotatedWithOverride : Errors.MethodDoesNotOverrideSuperclass) :
2146                                 Errors.AnonymousDiamondMethodDoesNotOverrideSuperclass(Fragments.DiamondAnonymousMethodsImplicitlyOverride));
2147         }
2148     }
2149 
checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m)2150     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
2151         TypeSymbol c = site.tsym;
2152         for (Symbol sym : c.members().getSymbolsByName(m.name)) {
2153             if (m.overrides(sym, origin, types, false)) {
2154                 if ((sym.flags() & ABSTRACT) == 0) {
2155                     checkOverride(tree, m, (MethodSymbol)sym, origin);
2156                 }
2157             }
2158         }
2159     }
2160 
2161     private Predicate<Symbol> equalsHasCodeFilter = s -> MethodSymbol.implementation_filter.test(s) &&
2162             (s.flags() & BAD_OVERRIDE) == 0;
2163 
checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos, ClassSymbol someClass)2164     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
2165             ClassSymbol someClass) {
2166         /* At present, annotations cannot possibly have a method that is override
2167          * equivalent with Object.equals(Object) but in any case the condition is
2168          * fine for completeness.
2169          */
2170         if (someClass == (ClassSymbol)syms.objectType.tsym ||
2171             someClass.isInterface() || someClass.isEnum() ||
2172             (someClass.flags() & ANNOTATION) != 0 ||
2173             (someClass.flags() & ABSTRACT) != 0) return;
2174         //anonymous inner classes implementing interfaces need especial treatment
2175         if (someClass.isAnonymous()) {
2176             List<Type> interfaces =  types.interfaces(someClass.type);
2177             if (interfaces != null && !interfaces.isEmpty() &&
2178                 interfaces.head.tsym == syms.comparatorType.tsym) return;
2179         }
2180         checkClassOverrideEqualsAndHash(pos, someClass);
2181     }
2182 
checkClassOverrideEqualsAndHash(DiagnosticPosition pos, ClassSymbol someClass)2183     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
2184             ClassSymbol someClass) {
2185         if (lint.isEnabled(LintCategory.OVERRIDES)) {
2186             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
2187                     .tsym.members().findFirst(names.equals);
2188             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
2189                     .tsym.members().findFirst(names.hashCode);
2190             MethodSymbol equalsImpl = types.implementation(equalsAtObject,
2191                     someClass, false, equalsHasCodeFilter);
2192             boolean overridesEquals = equalsImpl != null &&
2193                                       equalsImpl.owner == someClass;
2194             boolean overridesHashCode = types.implementation(hashCodeAtObject,
2195                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
2196 
2197             if (overridesEquals && !overridesHashCode) {
2198                 log.warning(LintCategory.OVERRIDES, pos,
2199                             Warnings.OverrideEqualsButNotHashcode(someClass));
2200             }
2201         }
2202     }
2203 
checkModuleName(JCModuleDecl tree)2204     public void checkModuleName (JCModuleDecl tree) {
2205         Name moduleName = tree.sym.name;
2206         Assert.checkNonNull(moduleName);
2207         if (lint.isEnabled(LintCategory.MODULE)) {
2208             JCExpression qualId = tree.qualId;
2209             while (qualId != null) {
2210                 Name componentName;
2211                 DiagnosticPosition pos;
2212                 switch (qualId.getTag()) {
2213                     case SELECT:
2214                         JCFieldAccess selectNode = ((JCFieldAccess) qualId);
2215                         componentName = selectNode.name;
2216                         pos = selectNode.pos();
2217                         qualId = selectNode.selected;
2218                         break;
2219                     case IDENT:
2220                         componentName = ((JCIdent) qualId).name;
2221                         pos = qualId.pos();
2222                         qualId = null;
2223                         break;
2224                     default:
2225                         throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
2226                 }
2227                 if (componentName != null) {
2228                     String moduleNameComponentString = componentName.toString();
2229                     int nameLength = moduleNameComponentString.length();
2230                     if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
2231                         log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
2232                     }
2233                 }
2234             }
2235         }
2236     }
2237 
checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2)2238     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
2239         ClashFilter cf = new ClashFilter(origin.type);
2240         return (cf.test(s1) &&
2241                 cf.test(s2) &&
2242                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
2243     }
2244 
2245 
2246     /** Check that all abstract members of given class have definitions.
2247      *  @param pos          Position to be used for error reporting.
2248      *  @param c            The class.
2249      */
checkAllDefined(DiagnosticPosition pos, ClassSymbol c)2250     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
2251         MethodSymbol undef = types.firstUnimplementedAbstract(c);
2252         if (undef != null) {
2253             MethodSymbol undef1 =
2254                 new MethodSymbol(undef.flags(), undef.name,
2255                                  types.memberType(c.type, undef), undef.owner);
2256             log.error(pos,
2257                       Errors.DoesNotOverrideAbstract(c, undef1, undef1.location()));
2258         }
2259     }
2260 
checkNonCyclicDecl(JCClassDecl tree)2261     void checkNonCyclicDecl(JCClassDecl tree) {
2262         CycleChecker cc = new CycleChecker();
2263         cc.scan(tree);
2264         if (!cc.errorFound && !cc.partialCheck) {
2265             tree.sym.flags_field |= ACYCLIC;
2266         }
2267     }
2268 
2269     class CycleChecker extends TreeScanner {
2270 
2271         Set<Symbol> seenClasses = new HashSet<>();
2272         boolean errorFound = false;
2273         boolean partialCheck = false;
2274 
checkSymbol(DiagnosticPosition pos, Symbol sym)2275         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
2276             if (sym != null && sym.kind == TYP) {
2277                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
2278                 if (classEnv != null) {
2279                     DiagnosticSource prevSource = log.currentSource();
2280                     try {
2281                         log.useSource(classEnv.toplevel.sourcefile);
2282                         scan(classEnv.tree);
2283                     }
2284                     finally {
2285                         log.useSource(prevSource.getFile());
2286                     }
2287                 } else if (sym.kind == TYP) {
2288                     checkClass(pos, sym, List.nil());
2289                 }
2290             } else if (sym == null || sym.kind != PCK) {
2291                 //not completed yet
2292                 partialCheck = true;
2293             }
2294         }
2295 
2296         @Override
visitSelect(JCFieldAccess tree)2297         public void visitSelect(JCFieldAccess tree) {
2298             super.visitSelect(tree);
2299             checkSymbol(tree.pos(), tree.sym);
2300         }
2301 
2302         @Override
visitIdent(JCIdent tree)2303         public void visitIdent(JCIdent tree) {
2304             checkSymbol(tree.pos(), tree.sym);
2305         }
2306 
2307         @Override
visitTypeApply(JCTypeApply tree)2308         public void visitTypeApply(JCTypeApply tree) {
2309             scan(tree.clazz);
2310         }
2311 
2312         @Override
visitTypeArray(JCArrayTypeTree tree)2313         public void visitTypeArray(JCArrayTypeTree tree) {
2314             scan(tree.elemtype);
2315         }
2316 
2317         @Override
visitClassDef(JCClassDecl tree)2318         public void visitClassDef(JCClassDecl tree) {
2319             List<JCTree> supertypes = List.nil();
2320             if (tree.getExtendsClause() != null) {
2321                 supertypes = supertypes.prepend(tree.getExtendsClause());
2322             }
2323             if (tree.getImplementsClause() != null) {
2324                 for (JCTree intf : tree.getImplementsClause()) {
2325                     supertypes = supertypes.prepend(intf);
2326                 }
2327             }
2328             checkClass(tree.pos(), tree.sym, supertypes);
2329         }
2330 
checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes)2331         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
2332             if ((c.flags_field & ACYCLIC) != 0)
2333                 return;
2334             if (seenClasses.contains(c)) {
2335                 errorFound = true;
2336                 noteCyclic(pos, (ClassSymbol)c);
2337             } else if (!c.type.isErroneous()) {
2338                 try {
2339                     seenClasses.add(c);
2340                     if (c.type.hasTag(CLASS)) {
2341                         if (supertypes.nonEmpty()) {
2342                             scan(supertypes);
2343                         }
2344                         else {
2345                             ClassType ct = (ClassType)c.type;
2346                             if (ct.supertype_field == null ||
2347                                     ct.interfaces_field == null) {
2348                                 //not completed yet
2349                                 partialCheck = true;
2350                                 return;
2351                             }
2352                             checkSymbol(pos, ct.supertype_field.tsym);
2353                             for (Type intf : ct.interfaces_field) {
2354                                 checkSymbol(pos, intf.tsym);
2355                             }
2356                         }
2357                         if (c.owner.kind == TYP) {
2358                             checkSymbol(pos, c.owner);
2359                         }
2360                     }
2361                 } finally {
2362                     seenClasses.remove(c);
2363                 }
2364             }
2365         }
2366     }
2367 
2368     /** Check for cyclic references. Issue an error if the
2369      *  symbol of the type referred to has a LOCKED flag set.
2370      *
2371      *  @param pos      Position to be used for error reporting.
2372      *  @param t        The type referred to.
2373      */
checkNonCyclic(DiagnosticPosition pos, Type t)2374     void checkNonCyclic(DiagnosticPosition pos, Type t) {
2375         checkNonCyclicInternal(pos, t);
2376     }
2377 
2378 
checkNonCyclic(DiagnosticPosition pos, TypeVar t)2379     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
2380         checkNonCyclic1(pos, t, List.nil());
2381     }
2382 
checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen)2383     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
2384         final TypeVar tv;
2385         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
2386             return;
2387         if (seen.contains(t)) {
2388             tv = (TypeVar)t;
2389             tv.setUpperBound(types.createErrorType(t));
2390             log.error(pos, Errors.CyclicInheritance(t));
2391         } else if (t.hasTag(TYPEVAR)) {
2392             tv = (TypeVar)t;
2393             seen = seen.prepend(tv);
2394             for (Type b : types.getBounds(tv))
2395                 checkNonCyclic1(pos, b, seen);
2396         }
2397     }
2398 
2399     /** Check for cyclic references. Issue an error if the
2400      *  symbol of the type referred to has a LOCKED flag set.
2401      *
2402      *  @param pos      Position to be used for error reporting.
2403      *  @param t        The type referred to.
2404      *  @returns        True if the check completed on all attributed classes
2405      */
checkNonCyclicInternal(DiagnosticPosition pos, Type t)2406     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
2407         boolean complete = true; // was the check complete?
2408         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
2409         Symbol c = t.tsym;
2410         if ((c.flags_field & ACYCLIC) != 0) return true;
2411 
2412         if ((c.flags_field & LOCKED) != 0) {
2413             noteCyclic(pos, (ClassSymbol)c);
2414         } else if (!c.type.isErroneous()) {
2415             try {
2416                 c.flags_field |= LOCKED;
2417                 if (c.type.hasTag(CLASS)) {
2418                     ClassType clazz = (ClassType)c.type;
2419                     if (clazz.interfaces_field != null)
2420                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
2421                             complete &= checkNonCyclicInternal(pos, l.head);
2422                     if (clazz.supertype_field != null) {
2423                         Type st = clazz.supertype_field;
2424                         if (st != null && st.hasTag(CLASS))
2425                             complete &= checkNonCyclicInternal(pos, st);
2426                     }
2427                     if (c.owner.kind == TYP)
2428                         complete &= checkNonCyclicInternal(pos, c.owner.type);
2429                 }
2430             } finally {
2431                 c.flags_field &= ~LOCKED;
2432             }
2433         }
2434         if (complete)
2435             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.isCompleted();
2436         if (complete) c.flags_field |= ACYCLIC;
2437         return complete;
2438     }
2439 
2440     /** Note that we found an inheritance cycle. */
noteCyclic(DiagnosticPosition pos, ClassSymbol c)2441     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
2442         log.error(pos, Errors.CyclicInheritance(c));
2443         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
2444             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
2445         Type st = types.supertype(c.type);
2446         if (st.hasTag(CLASS))
2447             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
2448         c.type = types.createErrorType(c, c.type);
2449         c.flags_field |= ACYCLIC;
2450     }
2451 
2452     /** Check that all methods which implement some
2453      *  method conform to the method they implement.
2454      *  @param tree         The class definition whose members are checked.
2455      */
checkImplementations(JCClassDecl tree)2456     void checkImplementations(JCClassDecl tree) {
2457         checkImplementations(tree, tree.sym, tree.sym);
2458     }
2459     //where
2460         /** Check that all methods which implement some
2461          *  method in `ic' conform to the method they implement.
2462          */
checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic)2463         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
2464             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
2465                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
2466                 if ((lc.flags() & ABSTRACT) != 0) {
2467                     for (Symbol sym : lc.members().getSymbols(NON_RECURSIVE)) {
2468                         if (sym.kind == MTH &&
2469                             (sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
2470                             MethodSymbol absmeth = (MethodSymbol)sym;
2471                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
2472                             if (implmeth != null && implmeth != absmeth &&
2473                                 (implmeth.owner.flags() & INTERFACE) ==
2474                                 (origin.flags() & INTERFACE)) {
2475                                 // don't check if implmeth is in a class, yet
2476                                 // origin is an interface. This case arises only
2477                                 // if implmeth is declared in Object. The reason is
2478                                 // that interfaces really don't inherit from
2479                                 // Object it's just that the compiler represents
2480                                 // things that way.
2481                                 checkOverride(tree, implmeth, absmeth, origin);
2482                             }
2483                         }
2484                     }
2485                 }
2486             }
2487         }
2488 
2489     /** Check that all abstract methods implemented by a class are
2490      *  mutually compatible.
2491      *  @param pos          Position to be used for error reporting.
2492      *  @param c            The class whose interfaces are checked.
2493      */
checkCompatibleSupertypes(DiagnosticPosition pos, Type c)2494     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
2495         List<Type> supertypes = types.interfaces(c);
2496         Type supertype = types.supertype(c);
2497         if (supertype.hasTag(CLASS) &&
2498             (supertype.tsym.flags() & ABSTRACT) != 0)
2499             supertypes = supertypes.prepend(supertype);
2500         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
2501             if (!l.head.getTypeArguments().isEmpty() &&
2502                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
2503                 return;
2504             for (List<Type> m = supertypes; m != l; m = m.tail)
2505                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
2506                     return;
2507         }
2508         checkCompatibleConcretes(pos, c);
2509     }
2510 
2511     /** Check that all non-override equivalent methods accessible from 'site'
2512      *  are mutually compatible (JLS 8.4.8/9.4.1).
2513      *
2514      *  @param pos  Position to be used for error reporting.
2515      *  @param site The class whose methods are checked.
2516      *  @param sym  The method symbol to be checked.
2517      */
checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym)2518     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2519          ClashFilter cf = new ClashFilter(site);
2520         //for each method m1 that is overridden (directly or indirectly)
2521         //by method 'sym' in 'site'...
2522 
2523         List<MethodSymbol> potentiallyAmbiguousList = List.nil();
2524         boolean overridesAny = false;
2525         ArrayList<Symbol> symbolsByName = new ArrayList<>();
2526         types.membersClosure(site, false).getSymbolsByName(sym.name, cf).forEach(symbolsByName::add);
2527         for (Symbol m1 : symbolsByName) {
2528             if (!sym.overrides(m1, site.tsym, types, false)) {
2529                 if (m1 == sym) {
2530                     continue;
2531                 }
2532 
2533                 if (!overridesAny) {
2534                     potentiallyAmbiguousList = potentiallyAmbiguousList.prepend((MethodSymbol)m1);
2535                 }
2536                 continue;
2537             }
2538 
2539             if (m1 != sym) {
2540                 overridesAny = true;
2541                 potentiallyAmbiguousList = List.nil();
2542             }
2543 
2544             //...check each method m2 that is a member of 'site'
2545             for (Symbol m2 : symbolsByName) {
2546                 if (m2 == m1) continue;
2547                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2548                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
2549                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), Feature.STRICT_METHOD_CLASH_CHECK.allowedInSource(source)) &&
2550                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
2551                     sym.flags_field |= CLASH;
2552                     if (m1 == sym) {
2553                         log.error(pos, Errors.NameClashSameErasureNoOverride(
2554                             m1.name, types.memberType(site, m1).asMethodType().getParameterTypes(), m1.location(),
2555                             m2.name, types.memberType(site, m2).asMethodType().getParameterTypes(), m2.location()));
2556                     } else {
2557                         ClassType ct = (ClassType)site;
2558                         String kind = ct.isInterface() ? "interface" : "class";
2559                         log.error(pos, Errors.NameClashSameErasureNoOverride1(
2560                             kind,
2561                             ct.tsym.name,
2562                             m1.name,
2563                             types.memberType(site, m1).asMethodType().getParameterTypes(),
2564                             m1.location(),
2565                             m2.name,
2566                             types.memberType(site, m2).asMethodType().getParameterTypes(),
2567                             m2.location()));
2568                     }
2569                     return;
2570                 }
2571             }
2572         }
2573 
2574         if (!overridesAny) {
2575             for (MethodSymbol m: potentiallyAmbiguousList) {
2576                 checkPotentiallyAmbiguousOverloads(pos, site, sym, m);
2577             }
2578         }
2579     }
2580 
2581     /** Check that all static methods accessible from 'site' are
2582      *  mutually compatible (JLS 8.4.8).
2583      *
2584      *  @param pos  Position to be used for error reporting.
2585      *  @param site The class whose methods are checked.
2586      *  @param sym  The method symbol to be checked.
2587      */
checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym)2588     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
2589         ClashFilter cf = new ClashFilter(site);
2590         //for each method m1 that is a member of 'site'...
2591         for (Symbol s : types.membersClosure(site, true).getSymbolsByName(sym.name, cf)) {
2592             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
2593             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
2594             if (!types.isSubSignature(sym.type, types.memberType(site, s), Feature.STRICT_METHOD_CLASH_CHECK.allowedInSource(source))) {
2595                 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
2596                     log.error(pos,
2597                               Errors.NameClashSameErasureNoHide(sym, sym.location(), s, s.location()));
2598                     return;
2599                 } else {
2600                     checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s);
2601                 }
2602             }
2603          }
2604      }
2605 
2606      //where
2607      private class ClashFilter implements Predicate<Symbol> {
2608 
2609          Type site;
2610 
ClashFilter(Type site)2611          ClashFilter(Type site) {
2612              this.site = site;
2613          }
2614 
shouldSkip(Symbol s)2615          boolean shouldSkip(Symbol s) {
2616              return (s.flags() & CLASH) != 0 &&
2617                 s.owner == site.tsym;
2618          }
2619 
2620          @Override
test(Symbol s)2621          public boolean test(Symbol s) {
2622              return s.kind == MTH &&
2623                      (s.flags() & SYNTHETIC) == 0 &&
2624                      !shouldSkip(s) &&
2625                      s.isInheritedIn(site.tsym, types) &&
2626                      !s.isConstructor();
2627          }
2628      }
2629 
checkDefaultMethodClashes(DiagnosticPosition pos, Type site)2630     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
2631         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
2632         for (Symbol m : types.membersClosure(site, false).getSymbols(dcf)) {
2633             Assert.check(m.kind == MTH);
2634             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
2635             if (prov.size() > 1) {
2636                 ListBuffer<Symbol> abstracts = new ListBuffer<>();
2637                 ListBuffer<Symbol> defaults = new ListBuffer<>();
2638                 for (MethodSymbol provSym : prov) {
2639                     if ((provSym.flags() & DEFAULT) != 0) {
2640                         defaults = defaults.append(provSym);
2641                     } else if ((provSym.flags() & ABSTRACT) != 0) {
2642                         abstracts = abstracts.append(provSym);
2643                     }
2644                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
2645                         //strong semantics - issue an error if two sibling interfaces
2646                         //have two override-equivalent defaults - or if one is abstract
2647                         //and the other is default
2648                         Fragment diagKey;
2649                         Symbol s1 = defaults.first();
2650                         Symbol s2;
2651                         if (defaults.size() > 1) {
2652                             s2 = defaults.toList().tail.head;
2653                             diagKey = Fragments.IncompatibleUnrelatedDefaults(Kinds.kindName(site.tsym), site,
2654                                     m.name, types.memberType(site, m).getParameterTypes(),
2655                                     s1.location(), s2.location());
2656 
2657                         } else {
2658                             s2 = abstracts.first();
2659                             diagKey = Fragments.IncompatibleAbstractDefault(Kinds.kindName(site.tsym), site,
2660                                     m.name, types.memberType(site, m).getParameterTypes(),
2661                                     s1.location(), s2.location());
2662                         }
2663                         log.error(pos, Errors.TypesIncompatible(s1.location().type, s2.location().type, diagKey));
2664                         break;
2665                     }
2666                 }
2667             }
2668         }
2669     }
2670 
2671     //where
2672      private class DefaultMethodClashFilter implements Predicate<Symbol> {
2673 
2674          Type site;
2675 
DefaultMethodClashFilter(Type site)2676          DefaultMethodClashFilter(Type site) {
2677              this.site = site;
2678          }
2679 
2680          @Override
test(Symbol s)2681          public boolean test(Symbol s) {
2682              return s.kind == MTH &&
2683                      (s.flags() & DEFAULT) != 0 &&
2684                      s.isInheritedIn(site.tsym, types) &&
2685                      !s.isConstructor();
2686          }
2687      }
2688 
2689     /**
2690       * Report warnings for potentially ambiguous method declarations. Two declarations
2691       * are potentially ambiguous if they feature two unrelated functional interface
2692       * in same argument position (in which case, a call site passing an implicit
2693       * lambda would be ambiguous).
2694       */
checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site, MethodSymbol msym1, MethodSymbol msym2)2695     void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
2696             MethodSymbol msym1, MethodSymbol msym2) {
2697         if (msym1 != msym2 &&
2698                 Feature.DEFAULT_METHODS.allowedInSource(source) &&
2699                 lint.isEnabled(LintCategory.OVERLOADS) &&
2700                 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
2701                 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
2702             Type mt1 = types.memberType(site, msym1);
2703             Type mt2 = types.memberType(site, msym2);
2704             //if both generic methods, adjust type variables
2705             if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
2706                     types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
2707                 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
2708             }
2709             //expand varargs methods if needed
2710             int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
2711             List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
2712             List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
2713             //if arities don't match, exit
2714             if (args1.length() != args2.length()) return;
2715             boolean potentiallyAmbiguous = false;
2716             while (args1.nonEmpty() && args2.nonEmpty()) {
2717                 Type s = args1.head;
2718                 Type t = args2.head;
2719                 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
2720                     if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
2721                             types.findDescriptorType(s).getParameterTypes().length() > 0 &&
2722                             types.findDescriptorType(s).getParameterTypes().length() ==
2723                             types.findDescriptorType(t).getParameterTypes().length()) {
2724                         potentiallyAmbiguous = true;
2725                     } else {
2726                         return;
2727                     }
2728                 }
2729                 args1 = args1.tail;
2730                 args2 = args2.tail;
2731             }
2732             if (potentiallyAmbiguous) {
2733                 //we found two incompatible functional interfaces with same arity
2734                 //this means a call site passing an implicit lambda would be ambiguous
2735                 msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
2736                 msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
2737                 log.warning(LintCategory.OVERLOADS, pos,
2738                             Warnings.PotentiallyAmbiguousOverload(msym1, msym1.location(),
2739                                                                   msym2, msym2.location()));
2740                 return;
2741             }
2742         }
2743     }
2744 
checkAccessFromSerializableElement(final JCTree tree, boolean isLambda)2745     void checkAccessFromSerializableElement(final JCTree tree, boolean isLambda) {
2746         if (warnOnAnyAccessToMembers ||
2747             (lint.isEnabled(LintCategory.SERIAL) &&
2748             !lint.isSuppressed(LintCategory.SERIAL) &&
2749             isLambda)) {
2750             Symbol sym = TreeInfo.symbol(tree);
2751             if (!sym.kind.matches(KindSelector.VAL_MTH)) {
2752                 return;
2753             }
2754 
2755             if (sym.kind == VAR) {
2756                 if ((sym.flags() & PARAMETER) != 0 ||
2757                     sym.isDirectlyOrIndirectlyLocal() ||
2758                     sym.name == names._this ||
2759                     sym.name == names._super) {
2760                     return;
2761                 }
2762             }
2763 
2764             if (!types.isSubtype(sym.owner.type, syms.serializableType) &&
2765                 isEffectivelyNonPublic(sym)) {
2766                 if (isLambda) {
2767                     if (belongsToRestrictedPackage(sym)) {
2768                         log.warning(LintCategory.SERIAL, tree.pos(),
2769                                     Warnings.AccessToMemberFromSerializableLambda(sym));
2770                     }
2771                 } else {
2772                     log.warning(tree.pos(),
2773                                 Warnings.AccessToMemberFromSerializableElement(sym));
2774                 }
2775             }
2776         }
2777     }
2778 
isEffectivelyNonPublic(Symbol sym)2779     private boolean isEffectivelyNonPublic(Symbol sym) {
2780         if (sym.packge() == syms.rootPackage) {
2781             return false;
2782         }
2783 
2784         while (sym.kind != PCK) {
2785             if ((sym.flags() & PUBLIC) == 0) {
2786                 return true;
2787             }
2788             sym = sym.owner;
2789         }
2790         return false;
2791     }
2792 
belongsToRestrictedPackage(Symbol sym)2793     private boolean belongsToRestrictedPackage(Symbol sym) {
2794         String fullName = sym.packge().fullname.toString();
2795         return fullName.startsWith("java.") ||
2796                 fullName.startsWith("javax.") ||
2797                 fullName.startsWith("sun.") ||
2798                 fullName.contains(".internal.");
2799     }
2800 
2801     /** Check that class c does not implement directly or indirectly
2802      *  the same parameterized interface with two different argument lists.
2803      *  @param pos          Position to be used for error reporting.
2804      *  @param type         The type whose interfaces are checked.
2805      */
checkClassBounds(DiagnosticPosition pos, Type type)2806     void checkClassBounds(DiagnosticPosition pos, Type type) {
2807         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
2808     }
2809 //where
2810         /** Enter all interfaces of type `type' into the hash table `seensofar'
2811          *  with their class symbol as key and their type as value. Make
2812          *  sure no class is entered with two different types.
2813          */
checkClassBounds(DiagnosticPosition pos, Map<TypeSymbol,Type> seensofar, Type type)2814         void checkClassBounds(DiagnosticPosition pos,
2815                               Map<TypeSymbol,Type> seensofar,
2816                               Type type) {
2817             if (type.isErroneous()) return;
2818             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
2819                 Type it = l.head;
2820                 if (type.hasTag(CLASS) && !it.hasTag(CLASS)) continue; // JLS 8.1.5
2821 
2822                 Type oldit = seensofar.put(it.tsym, it);
2823                 if (oldit != null) {
2824                     List<Type> oldparams = oldit.allparams();
2825                     List<Type> newparams = it.allparams();
2826                     if (!types.containsTypeEquivalent(oldparams, newparams))
2827                         log.error(pos,
2828                                   Errors.CantInheritDiffArg(it.tsym,
2829                                                             Type.toString(oldparams),
2830                                                             Type.toString(newparams)));
2831                 }
2832                 checkClassBounds(pos, seensofar, it);
2833             }
2834             Type st = types.supertype(type);
2835             if (type.hasTag(CLASS) && !st.hasTag(CLASS)) return; // JLS 8.1.4
2836             if (st != Type.noType) checkClassBounds(pos, seensofar, st);
2837         }
2838 
2839     /** Enter interface into into set.
2840      *  If it existed already, issue a "repeated interface" error.
2841      */
checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its)2842     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
2843         if (its.contains(it))
2844             log.error(pos, Errors.RepeatedInterface);
2845         else {
2846             its.add(it);
2847         }
2848     }
2849 
2850 /* *************************************************************************
2851  * Check annotations
2852  **************************************************************************/
2853 
2854     /**
2855      * Recursively validate annotations values
2856      */
validateAnnotationTree(JCTree tree)2857     void validateAnnotationTree(JCTree tree) {
2858         class AnnotationValidator extends TreeScanner {
2859             @Override
2860             public void visitAnnotation(JCAnnotation tree) {
2861                 if (!tree.type.isErroneous() && tree.type.tsym.isAnnotationType()) {
2862                     super.visitAnnotation(tree);
2863                     validateAnnotation(tree);
2864                 }
2865             }
2866         }
2867         tree.accept(new AnnotationValidator());
2868     }
2869 
2870     /**
2871      *  {@literal
2872      *  Annotation types are restricted to primitives, String, an
2873      *  enum, an annotation, Class, Class<?>, Class<? extends
2874      *  Anything>, arrays of the preceding.
2875      *  }
2876      */
validateAnnotationType(JCTree restype)2877     void validateAnnotationType(JCTree restype) {
2878         // restype may be null if an error occurred, so don't bother validating it
2879         if (restype != null) {
2880             validateAnnotationType(restype.pos(), restype.type);
2881         }
2882     }
2883 
validateAnnotationType(DiagnosticPosition pos, Type type)2884     void validateAnnotationType(DiagnosticPosition pos, Type type) {
2885         if (type.isPrimitive()) return;
2886         if (types.isSameType(type, syms.stringType)) return;
2887         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
2888         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
2889         if (types.cvarLowerBound(type).tsym == syms.classType.tsym) return;
2890         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
2891             validateAnnotationType(pos, types.elemtype(type));
2892             return;
2893         }
2894         log.error(pos, Errors.InvalidAnnotationMemberType);
2895     }
2896 
2897     /**
2898      * "It is also a compile-time error if any method declared in an
2899      * annotation type has a signature that is override-equivalent to
2900      * that of any public or protected method declared in class Object
2901      * or in the interface annotation.Annotation."
2902      *
2903      * @jls 9.6 Annotation Types
2904      */
validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m)2905     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
2906         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
2907             Scope s = sup.tsym.members();
2908             for (Symbol sym : s.getSymbolsByName(m.name)) {
2909                 if (sym.kind == MTH &&
2910                     (sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
2911                     types.overrideEquivalent(m.type, sym.type))
2912                     log.error(pos, Errors.IntfAnnotationMemberClash(sym, sup));
2913             }
2914         }
2915     }
2916 
2917     /** Check the annotations of a symbol.
2918      */
validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s)2919     public void validateAnnotations(List<JCAnnotation> annotations, JCTree declarationTree, Symbol s) {
2920         for (JCAnnotation a : annotations)
2921             validateAnnotation(a, declarationTree, s);
2922     }
2923 
2924     /** Check the type annotations.
2925      */
validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter)2926     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
2927         for (JCAnnotation a : annotations)
2928             validateTypeAnnotation(a, isTypeParameter);
2929     }
2930 
2931     /** Check an annotation of a symbol.
2932      */
validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s)2933     private void validateAnnotation(JCAnnotation a, JCTree declarationTree, Symbol s) {
2934         validateAnnotationTree(a);
2935         boolean isRecordMember = ((s.flags_field & RECORD) != 0 || s.enclClass() != null && s.enclClass().isRecord());
2936 
2937         boolean isRecordField = (s.flags_field & RECORD) != 0 &&
2938                 declarationTree.hasTag(VARDEF) &&
2939                 s.owner.kind == TYP;
2940 
2941         if (isRecordField) {
2942             // first we need to check if the annotation is applicable to records
2943             Name[] targets = getTargetNames(a);
2944             boolean appliesToRecords = false;
2945             for (Name target : targets) {
2946                 appliesToRecords =
2947                                 target == names.FIELD ||
2948                                 target == names.PARAMETER ||
2949                                 target == names.METHOD ||
2950                                 target == names.TYPE_USE ||
2951                                 target == names.RECORD_COMPONENT;
2952                 if (appliesToRecords) {
2953                     break;
2954                 }
2955             }
2956             if (!appliesToRecords) {
2957                 log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
2958             } else {
2959                 /* lets now find the annotations in the field that are targeted to record components and append them to
2960                  * the corresponding record component
2961                  */
2962                 ClassSymbol recordClass = (ClassSymbol) s.owner;
2963                 RecordComponent rc = recordClass.getRecordComponent((VarSymbol)s);
2964                 SymbolMetadata metadata = rc.getMetadata();
2965                 if (metadata == null || metadata.isEmpty()) {
2966                     /* if not is empty then we have already been here, which is the case if multiple annotations are applied
2967                      * to the record component declaration
2968                      */
2969                     rc.appendAttributes(s.getRawAttributes().stream().filter(anno ->
2970                             Arrays.stream(getTargetNames(anno.type.tsym)).anyMatch(name -> name == names.RECORD_COMPONENT)
2971                     ).collect(List.collector()));
2972                     rc.setTypeAttributes(s.getRawTypeAttributes());
2973                     // to get all the type annotations applied to the type
2974                     rc.type = s.type;
2975                 }
2976             }
2977         }
2978 
2979         /* the section below is tricky. Annotations applied to record components are propagated to the corresponding
2980          * record member so if an annotation has target: FIELD, it is propagated to the corresponding FIELD, if it has
2981          * target METHOD, it is propagated to the accessor and so on. But at the moment when method members are generated
2982          * there is no enough information to propagate only the right annotations. So all the annotations are propagated
2983          * to all the possible locations.
2984          *
2985          * At this point we need to remove all the annotations that are not in place before going on with the annotation
2986          * party. On top of the above there is the issue that there is no AST representing record components, just symbols
2987          * so the corresponding field has been holding all the annotations and it's metadata has been modified as if it
2988          * was both a field and a record component.
2989          *
2990          * So there are two places where we need to trim annotations from: the metadata of the symbol and / or the modifiers
2991          * in the AST. Whatever is in the metadata will be written to the class file, whatever is in the modifiers could
2992          * be see by annotation processors.
2993          *
2994          * The metadata contains both type annotations and declaration annotations. At this point of the game we don't
2995          * need to care about type annotations, they are all in the right place. But we could need to remove declaration
2996          * annotations. So for declaration annotations if they are not applicable to the record member, excluding type
2997          * annotations which are already correct, then we will remove it. For the AST modifiers if the annotation is not
2998          * applicable either as type annotation and or declaration annotation, only in that case it will be removed.
2999          *
3000          * So it could be that annotation is removed as a declaration annotation but it is kept in the AST modifier for
3001          * further inspection by annotation processors.
3002          *
3003          * For example:
3004          *
3005          *     import java.lang.annotation.*;
3006          *
3007          *     @Target({ElementType.TYPE_USE, ElementType.RECORD_COMPONENT})
3008          *     @Retention(RetentionPolicy.RUNTIME)
3009          *     @interface Anno { }
3010          *
3011          *     record R(@Anno String s) {}
3012          *
3013          * at this point we will have for the case of the generated field:
3014          *   - @Anno in the modifier
3015          *   - @Anno as a type annotation
3016          *   - @Anno as a declaration annotation
3017          *
3018          * the last one should be removed because the annotation has not FIELD as target but it was applied as a
3019          * declaration annotation because the field was being treated both as a field and as a record component
3020          * as we have already copied the annotations to the record component, now the field doesn't need to hold
3021          * annotations that are not intended for it anymore. Still @Anno has to be kept in the AST's modifiers as it
3022          * is applicable as a type annotation to the type of the field.
3023          */
3024 
3025         if (a.type.tsym.isAnnotationType()) {
3026             Optional<Set<Name>> applicableTargetsOp = getApplicableTargets(a, s);
3027             if (!applicableTargetsOp.isEmpty()) {
3028                 Set<Name> applicableTargets = applicableTargetsOp.get();
3029                 boolean notApplicableOrIsTypeUseOnly = applicableTargets.isEmpty() ||
3030                         applicableTargets.size() == 1 && applicableTargets.contains(names.TYPE_USE);
3031                 boolean isCompGeneratedRecordElement = isRecordMember && (s.flags_field & Flags.GENERATED_MEMBER) != 0;
3032                 boolean isCompRecordElementWithNonApplicableDeclAnno = isCompGeneratedRecordElement && notApplicableOrIsTypeUseOnly;
3033 
3034                 if (applicableTargets.isEmpty() || isCompRecordElementWithNonApplicableDeclAnno) {
3035                     if (isCompRecordElementWithNonApplicableDeclAnno) {
3036                             /* so we have found an annotation that is not applicable to a record member that was generated by the
3037                              * compiler. This was intentionally done at TypeEnter, now is the moment strip away the annotations
3038                              * that are not applicable to the given record member
3039                              */
3040                         JCModifiers modifiers = TreeInfo.getModifiers(declarationTree);
3041                             /* lets first remove the annotation from the modifier if it is not applicable, we have to check again as
3042                              * it could be a type annotation
3043                              */
3044                         if (modifiers != null && applicableTargets.isEmpty()) {
3045                             ListBuffer<JCAnnotation> newAnnotations = new ListBuffer<>();
3046                             for (JCAnnotation anno : modifiers.annotations) {
3047                                 if (anno != a) {
3048                                     newAnnotations.add(anno);
3049                                 }
3050                             }
3051                             modifiers.annotations = newAnnotations.toList();
3052                         }
3053                         // now lets remove it from the symbol
3054                         s.getMetadata().removeDeclarationMetadata(a.attribute);
3055                     } else {
3056                         log.error(a.pos(), Errors.AnnotationTypeNotApplicable);
3057                     }
3058                 }
3059                 /* if we are seeing the @SafeVarargs annotation applied to a compiler generated accessor,
3060                  * then this is an error as we know that no compiler generated accessor will be a varargs
3061                  * method, better to fail asap
3062                  */
3063                 if (isCompGeneratedRecordElement && !isRecordField && a.type.tsym == syms.trustMeType.tsym && declarationTree.hasTag(METHODDEF)) {
3064                     log.error(a.pos(), Errors.VarargsInvalidTrustmeAnno(syms.trustMeType.tsym, Fragments.VarargsTrustmeOnNonVarargsAccessor(s)));
3065                 }
3066             }
3067         }
3068 
3069         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3070             if (s.kind != TYP) {
3071                 log.error(a.pos(), Errors.BadFunctionalIntfAnno);
3072             } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
3073                 log.error(a.pos(), Errors.BadFunctionalIntfAnno1(Fragments.NotAFunctionalIntf(s)));
3074             }
3075         }
3076     }
3077 
validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter)3078     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3079         Assert.checkNonNull(a.type);
3080         validateAnnotationTree(a);
3081 
3082         if (a.hasTag(TYPE_ANNOTATION) &&
3083                 !a.annotationType.type.isErroneous() &&
3084                 !isTypeAnnotation(a, isTypeParameter)) {
3085             log.error(a.pos(), Errors.AnnotationTypeNotApplicableToType(a.type));
3086         }
3087     }
3088 
3089     /**
3090      * Validate the proposed container 'repeatable' on the
3091      * annotation type symbol 's'. Report errors at position
3092      * 'pos'.
3093      *
3094      * @param s The (annotation)type declaration annotated with a @Repeatable
3095      * @param repeatable the @Repeatable on 's'
3096      * @param pos where to report errors
3097      */
validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos)3098     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
3099         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
3100 
3101         Type t = null;
3102         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
3103         if (!l.isEmpty()) {
3104             Assert.check(l.head.fst.name == names.value);
3105             t = ((Attribute.Class)l.head.snd).getValue();
3106         }
3107 
3108         if (t == null) {
3109             // errors should already have been reported during Annotate
3110             return;
3111         }
3112 
3113         validateValue(t.tsym, s, pos);
3114         validateRetention(t.tsym, s, pos);
3115         validateDocumented(t.tsym, s, pos);
3116         validateInherited(t.tsym, s, pos);
3117         validateTarget(t.tsym, s, pos);
3118         validateDefault(t.tsym, pos);
3119     }
3120 
validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos)3121     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3122         Symbol sym = container.members().findFirst(names.value);
3123         if (sym != null && sym.kind == MTH) {
3124             MethodSymbol m = (MethodSymbol) sym;
3125             Type ret = m.getReturnType();
3126             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
3127                 log.error(pos,
3128                           Errors.InvalidRepeatableAnnotationValueReturn(container,
3129                                                                         ret,
3130                                                                         types.makeArrayType(contained.type)));
3131             }
3132         } else {
3133             log.error(pos, Errors.InvalidRepeatableAnnotationNoValue(container));
3134         }
3135     }
3136 
validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos)3137     private void validateRetention(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3138         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
3139         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
3140 
3141         boolean error = false;
3142         switch (containedRetention) {
3143         case RUNTIME:
3144             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
3145                 error = true;
3146             }
3147             break;
3148         case CLASS:
3149             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
3150                 error = true;
3151             }
3152         }
3153         if (error ) {
3154             log.error(pos,
3155                       Errors.InvalidRepeatableAnnotationRetention(container,
3156                                                                   containerRetention.name(),
3157                                                                   contained,
3158                                                                   containedRetention.name()));
3159         }
3160     }
3161 
validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos)3162     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
3163         if (contained.attribute(syms.documentedType.tsym) != null) {
3164             if (container.attribute(syms.documentedType.tsym) == null) {
3165                 log.error(pos, Errors.InvalidRepeatableAnnotationNotDocumented(container, contained));
3166             }
3167         }
3168     }
3169 
validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos)3170     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
3171         if (contained.attribute(syms.inheritedType.tsym) != null) {
3172             if (container.attribute(syms.inheritedType.tsym) == null) {
3173                 log.error(pos, Errors.InvalidRepeatableAnnotationNotInherited(container, contained));
3174             }
3175         }
3176     }
3177 
validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos)3178     private void validateTarget(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
3179         // The set of targets the container is applicable to must be a subset
3180         // (with respect to annotation target semantics) of the set of targets
3181         // the contained is applicable to. The target sets may be implicit or
3182         // explicit.
3183 
3184         Set<Name> containerTargets;
3185         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
3186         if (containerTarget == null) {
3187             containerTargets = getDefaultTargetSet();
3188         } else {
3189             containerTargets = new HashSet<>();
3190             for (Attribute app : containerTarget.values) {
3191                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3192                     continue; // recovery
3193                 }
3194                 containerTargets.add(attributeEnum.value.name);
3195             }
3196         }
3197 
3198         Set<Name> containedTargets;
3199         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
3200         if (containedTarget == null) {
3201             containedTargets = getDefaultTargetSet();
3202         } else {
3203             containedTargets = new HashSet<>();
3204             for (Attribute app : containedTarget.values) {
3205                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3206                     continue; // recovery
3207                 }
3208                 containedTargets.add(attributeEnum.value.name);
3209             }
3210         }
3211 
3212         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
3213             log.error(pos, Errors.InvalidRepeatableAnnotationIncompatibleTarget(container, contained));
3214         }
3215     }
3216 
3217     /* get a set of names for the default target */
getDefaultTargetSet()3218     private Set<Name> getDefaultTargetSet() {
3219         if (defaultTargets == null) {
3220             defaultTargets = Set.of(defaultTargetMetaInfo());
3221         }
3222 
3223         return defaultTargets;
3224     }
3225     private Set<Name> defaultTargets;
3226 
3227 
3228     /** Checks that s is a subset of t, with respect to ElementType
3229      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE},
3230      * and {TYPE_USE} covers the set {ANNOTATION_TYPE, TYPE, TYPE_USE,
3231      * TYPE_PARAMETER}.
3232      */
isTargetSubsetOf(Set<Name> s, Set<Name> t)3233     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
3234         // Check that all elements in s are present in t
3235         for (Name n2 : s) {
3236             boolean currentElementOk = false;
3237             for (Name n1 : t) {
3238                 if (n1 == n2) {
3239                     currentElementOk = true;
3240                     break;
3241                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
3242                     currentElementOk = true;
3243                     break;
3244                 } else if (n1 == names.TYPE_USE &&
3245                         (n2 == names.TYPE ||
3246                          n2 == names.ANNOTATION_TYPE ||
3247                          n2 == names.TYPE_PARAMETER)) {
3248                     currentElementOk = true;
3249                     break;
3250                 }
3251             }
3252             if (!currentElementOk)
3253                 return false;
3254         }
3255         return true;
3256     }
3257 
validateDefault(Symbol container, DiagnosticPosition pos)3258     private void validateDefault(Symbol container, DiagnosticPosition pos) {
3259         // validate that all other elements of containing type has defaults
3260         Scope scope = container.members();
3261         for(Symbol elm : scope.getSymbols()) {
3262             if (elm.name != names.value &&
3263                 elm.kind == MTH &&
3264                 ((MethodSymbol)elm).defaultValue == null) {
3265                 log.error(pos,
3266                           Errors.InvalidRepeatableAnnotationElemNondefault(container, elm));
3267             }
3268         }
3269     }
3270 
3271     /** Is s a method symbol that overrides a method in a superclass? */
isOverrider(Symbol s)3272     boolean isOverrider(Symbol s) {
3273         if (s.kind != MTH || s.isStatic())
3274             return false;
3275         MethodSymbol m = (MethodSymbol)s;
3276         TypeSymbol owner = (TypeSymbol)m.owner;
3277         for (Type sup : types.closure(owner.type)) {
3278             if (sup == owner.type)
3279                 continue; // skip "this"
3280             Scope scope = sup.tsym.members();
3281             for (Symbol sym : scope.getSymbolsByName(m.name)) {
3282                 if (!sym.isStatic() && m.overrides(sym, owner, types, true))
3283                     return true;
3284             }
3285         }
3286         return false;
3287     }
3288 
3289     /** Is the annotation applicable to types? */
isTypeAnnotation(JCAnnotation a, boolean isTypeParameter)3290     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
3291         List<Attribute> targets = typeAnnotations.annotationTargets(a.annotationType.type.tsym);
3292         return (targets == null) ?
3293                 false :
3294                 targets.stream()
3295                         .anyMatch(attr -> isTypeAnnotation(attr, isTypeParameter));
3296     }
3297     //where
isTypeAnnotation(Attribute a, boolean isTypeParameter)3298         boolean isTypeAnnotation(Attribute a, boolean isTypeParameter) {
3299             Attribute.Enum e = (Attribute.Enum)a;
3300             return (e.value.name == names.TYPE_USE ||
3301                     (isTypeParameter && e.value.name == names.TYPE_PARAMETER));
3302         }
3303 
3304     /** Is the annotation applicable to the symbol? */
getTargetNames(JCAnnotation a)3305     Name[] getTargetNames(JCAnnotation a) {
3306         return getTargetNames(a.annotationType.type.tsym);
3307     }
3308 
getTargetNames(TypeSymbol annoSym)3309     public Name[] getTargetNames(TypeSymbol annoSym) {
3310         Attribute.Array arr = getAttributeTargetAttribute(annoSym);
3311         Name[] targets;
3312         if (arr == null) {
3313             targets = defaultTargetMetaInfo();
3314         } else {
3315             // TODO: can we optimize this?
3316             targets = new Name[arr.values.length];
3317             for (int i=0; i<arr.values.length; ++i) {
3318                 Attribute app = arr.values[i];
3319                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3320                     return new Name[0];
3321                 }
3322                 targets[i] = attributeEnum.value.name;
3323             }
3324         }
3325         return targets;
3326     }
3327 
annotationApplicable(JCAnnotation a, Symbol s)3328     boolean annotationApplicable(JCAnnotation a, Symbol s) {
3329         Optional<Set<Name>> targets = getApplicableTargets(a, s);
3330         /* the optional could be emtpy if the annotation is unknown in that case
3331          * we return that it is applicable and if it is erroneous that should imply
3332          * an error at the declaration site
3333          */
3334         return targets.isEmpty() || targets.isPresent() && !targets.get().isEmpty();
3335     }
3336 
getApplicableTargets(JCAnnotation a, Symbol s)3337     Optional<Set<Name>> getApplicableTargets(JCAnnotation a, Symbol s) {
3338         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
3339         Name[] targets;
3340         Set<Name> applicableTargets = new HashSet<>();
3341 
3342         if (arr == null) {
3343             targets = defaultTargetMetaInfo();
3344         } else {
3345             // TODO: can we optimize this?
3346             targets = new Name[arr.values.length];
3347             for (int i=0; i<arr.values.length; ++i) {
3348                 Attribute app = arr.values[i];
3349                 if (!(app instanceof Attribute.Enum attributeEnum)) {
3350                     // recovery
3351                     return Optional.empty();
3352                 }
3353                 targets[i] = attributeEnum.value.name;
3354             }
3355         }
3356         for (Name target : targets) {
3357             if (target == names.TYPE) {
3358                 if (s.kind == TYP)
3359                     applicableTargets.add(names.TYPE);
3360             } else if (target == names.FIELD) {
3361                 if (s.kind == VAR && s.owner.kind != MTH)
3362                     applicableTargets.add(names.FIELD);
3363             } else if (target == names.RECORD_COMPONENT) {
3364                 if (s.getKind() == ElementKind.RECORD_COMPONENT) {
3365                     applicableTargets.add(names.RECORD_COMPONENT);
3366                 }
3367             } else if (target == names.METHOD) {
3368                 if (s.kind == MTH && !s.isConstructor())
3369                     applicableTargets.add(names.METHOD);
3370             } else if (target == names.PARAMETER) {
3371                 if (s.kind == VAR &&
3372                     (s.owner.kind == MTH && (s.flags() & PARAMETER) != 0)) {
3373                     applicableTargets.add(names.PARAMETER);
3374                 }
3375             } else if (target == names.CONSTRUCTOR) {
3376                 if (s.kind == MTH && s.isConstructor())
3377                     applicableTargets.add(names.CONSTRUCTOR);
3378             } else if (target == names.LOCAL_VARIABLE) {
3379                 if (s.kind == VAR && s.owner.kind == MTH &&
3380                       (s.flags() & PARAMETER) == 0) {
3381                     applicableTargets.add(names.LOCAL_VARIABLE);
3382                 }
3383             } else if (target == names.ANNOTATION_TYPE) {
3384                 if (s.kind == TYP && (s.flags() & ANNOTATION) != 0) {
3385                     applicableTargets.add(names.ANNOTATION_TYPE);
3386                 }
3387             } else if (target == names.PACKAGE) {
3388                 if (s.kind == PCK)
3389                     applicableTargets.add(names.PACKAGE);
3390             } else if (target == names.TYPE_USE) {
3391                 if (s.kind == VAR && s.owner.kind == MTH && s.type.hasTag(NONE)) {
3392                     //cannot type annotate implicitly typed locals
3393                     continue;
3394                 } else if (s.kind == TYP || s.kind == VAR ||
3395                         (s.kind == MTH && !s.isConstructor() &&
3396                                 !s.type.getReturnType().hasTag(VOID)) ||
3397                         (s.kind == MTH && s.isConstructor())) {
3398                     applicableTargets.add(names.TYPE_USE);
3399                 }
3400             } else if (target == names.TYPE_PARAMETER) {
3401                 if (s.kind == TYP && s.type.hasTag(TYPEVAR))
3402                     applicableTargets.add(names.TYPE_PARAMETER);
3403             } else if (target == names.MODULE) {
3404                 if (s.kind == MDL)
3405                     applicableTargets.add(names.MODULE);
3406             } else
3407                 return Optional.empty(); // Unknown ElementType. This should be an error at declaration site,
3408                                          // assume applicable.
3409         }
3410         return Optional.of(applicableTargets);
3411     }
3412 
getAttributeTargetAttribute(TypeSymbol s)3413     Attribute.Array getAttributeTargetAttribute(TypeSymbol s) {
3414         Attribute.Compound atTarget = s.getAnnotationTypeMetadata().getTarget();
3415         if (atTarget == null) return null; // ok, is applicable
3416         Attribute atValue = atTarget.member(names.value);
3417         return (atValue instanceof Attribute.Array attributeArray) ? attributeArray : null;
3418     }
3419 
3420     private Name[] dfltTargetMeta;
defaultTargetMetaInfo()3421     private Name[] defaultTargetMetaInfo() {
3422         if (dfltTargetMeta == null) {
3423             ArrayList<Name> defaultTargets = new ArrayList<>();
3424             defaultTargets.add(names.PACKAGE);
3425             defaultTargets.add(names.TYPE);
3426             defaultTargets.add(names.FIELD);
3427             defaultTargets.add(names.METHOD);
3428             defaultTargets.add(names.CONSTRUCTOR);
3429             defaultTargets.add(names.ANNOTATION_TYPE);
3430             defaultTargets.add(names.LOCAL_VARIABLE);
3431             defaultTargets.add(names.PARAMETER);
3432             if (allowRecords) {
3433               defaultTargets.add(names.RECORD_COMPONENT);
3434             }
3435             if (allowModules) {
3436               defaultTargets.add(names.MODULE);
3437             }
3438             dfltTargetMeta = defaultTargets.toArray(new Name[0]);
3439         }
3440         return dfltTargetMeta;
3441     }
3442 
3443     /** Check an annotation value.
3444      *
3445      * @param a The annotation tree to check
3446      * @return true if this annotation tree is valid, otherwise false
3447      */
validateAnnotationDeferErrors(JCAnnotation a)3448     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
3449         boolean res = false;
3450         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
3451         try {
3452             res = validateAnnotation(a);
3453         } finally {
3454             log.popDiagnosticHandler(diagHandler);
3455         }
3456         return res;
3457     }
3458 
validateAnnotation(JCAnnotation a)3459     private boolean validateAnnotation(JCAnnotation a) {
3460         boolean isValid = true;
3461         AnnotationTypeMetadata metadata = a.annotationType.type.tsym.getAnnotationTypeMetadata();
3462 
3463         // collect an inventory of the annotation elements
3464         Set<MethodSymbol> elements = metadata.getAnnotationElements();
3465 
3466         // remove the ones that are assigned values
3467         for (JCTree arg : a.args) {
3468             if (!arg.hasTag(ASSIGN)) continue; // recovery
3469             JCAssign assign = (JCAssign)arg;
3470             Symbol m = TreeInfo.symbol(assign.lhs);
3471             if (m == null || m.type.isErroneous()) continue;
3472             if (!elements.remove(m)) {
3473                 isValid = false;
3474                 log.error(assign.lhs.pos(),
3475                           Errors.DuplicateAnnotationMemberValue(m.name, a.type));
3476             }
3477         }
3478 
3479         // all the remaining ones better have default values
3480         List<Name> missingDefaults = List.nil();
3481         Set<MethodSymbol> membersWithDefault = metadata.getAnnotationElementsWithDefault();
3482         for (MethodSymbol m : elements) {
3483             if (m.type.isErroneous())
3484                 continue;
3485 
3486             if (!membersWithDefault.contains(m))
3487                 missingDefaults = missingDefaults.append(m.name);
3488         }
3489         missingDefaults = missingDefaults.reverse();
3490         if (missingDefaults.nonEmpty()) {
3491             isValid = false;
3492             Error errorKey = (missingDefaults.size() > 1)
3493                     ? Errors.AnnotationMissingDefaultValue1(a.type, missingDefaults)
3494                     : Errors.AnnotationMissingDefaultValue(a.type, missingDefaults);
3495             log.error(a.pos(), errorKey);
3496         }
3497 
3498         return isValid && validateTargetAnnotationValue(a);
3499     }
3500 
3501     /* Validate the special java.lang.annotation.Target annotation */
validateTargetAnnotationValue(JCAnnotation a)3502     boolean validateTargetAnnotationValue(JCAnnotation a) {
3503         // special case: java.lang.annotation.Target must not have
3504         // repeated values in its value member
3505         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
3506                 a.args.tail == null)
3507             return true;
3508 
3509         boolean isValid = true;
3510         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
3511         JCAssign assign = (JCAssign) a.args.head;
3512         Symbol m = TreeInfo.symbol(assign.lhs);
3513         if (m.name != names.value) return false;
3514         JCTree rhs = assign.rhs;
3515         if (!rhs.hasTag(NEWARRAY)) return false;
3516         JCNewArray na = (JCNewArray) rhs;
3517         Set<Symbol> targets = new HashSet<>();
3518         for (JCTree elem : na.elems) {
3519             if (!targets.add(TreeInfo.symbol(elem))) {
3520                 isValid = false;
3521                 log.error(elem.pos(), Errors.RepeatedAnnotationTarget);
3522             }
3523         }
3524         return isValid;
3525     }
3526 
checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s)3527     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
3528         if (lint.isEnabled(LintCategory.DEP_ANN) && s.isDeprecatableViaAnnotation() &&
3529             (s.flags() & DEPRECATED) != 0 &&
3530             !syms.deprecatedType.isErroneous() &&
3531             s.attribute(syms.deprecatedType.tsym) == null) {
3532             log.warning(LintCategory.DEP_ANN,
3533                     pos, Warnings.MissingDeprecatedAnnotation);
3534         }
3535         // Note: @Deprecated has no effect on local variables, parameters and package decls.
3536         if (lint.isEnabled(LintCategory.DEPRECATION) && !s.isDeprecatableViaAnnotation()) {
3537             if (!syms.deprecatedType.isErroneous() && s.attribute(syms.deprecatedType.tsym) != null) {
3538                 log.warning(LintCategory.DEPRECATION, pos,
3539                             Warnings.DeprecatedAnnotationHasNoEffect(Kinds.kindName(s)));
3540             }
3541         }
3542     }
3543 
checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s)3544     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
3545         checkDeprecated(() -> pos, other, s);
3546     }
3547 
checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s)3548     void checkDeprecated(Supplier<DiagnosticPosition> pos, final Symbol other, final Symbol s) {
3549         if ( (s.isDeprecatedForRemoval()
3550                 || s.isDeprecated() && !other.isDeprecated())
3551                 && (s.outermostClass() != other.outermostClass() || s.outermostClass() == null)
3552                 && s.kind != Kind.PCK) {
3553             deferredLintHandler.report(() -> warnDeprecated(pos.get(), s));
3554         }
3555     }
3556 
checkSunAPI(final DiagnosticPosition pos, final Symbol s)3557     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
3558         if ((s.flags() & PROPRIETARY) != 0) {
3559             deferredLintHandler.report(() -> {
3560                 log.mandatoryWarning(pos, Warnings.SunProprietary(s));
3561             });
3562         }
3563     }
3564 
checkProfile(final DiagnosticPosition pos, final Symbol s)3565     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
3566         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
3567             log.error(pos, Errors.NotInProfile(s, profile));
3568         }
3569     }
3570 
checkPreview(DiagnosticPosition pos, Symbol other, Symbol s)3571     void checkPreview(DiagnosticPosition pos, Symbol other, Symbol s) {
3572         if ((s.flags() & PREVIEW_API) != 0 && s.packge().modle != other.packge().modle) {
3573             if ((s.flags() & PREVIEW_REFLECTIVE) == 0) {
3574                 if (!preview.isEnabled()) {
3575                     log.error(pos, Errors.IsPreview(s));
3576                 } else {
3577                     preview.markUsesPreview(pos);
3578                     deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreview(s)));
3579                 }
3580             } else {
3581                     deferredLintHandler.report(() -> warnPreviewAPI(pos, Warnings.IsPreviewReflective(s)));
3582             }
3583         }
3584         if (preview.declaredUsingPreviewFeature(s)) {
3585             if (preview.isEnabled()) {
3586                 //for preview disabled do presumably so not need to do anything?
3587                 //If "s" is compiled from source, then there was an error for it already;
3588                 //if "s" is from classfile, there already was an error for the classfile.
3589                 preview.markUsesPreview(pos);
3590                 deferredLintHandler.report(() -> warnDeclaredUsingPreview(pos, s));
3591             }
3592         }
3593     }
3594 
3595 /* *************************************************************************
3596  * Check for recursive annotation elements.
3597  **************************************************************************/
3598 
3599     /** Check for cycles in the graph of annotation elements.
3600      */
checkNonCyclicElements(JCClassDecl tree)3601     void checkNonCyclicElements(JCClassDecl tree) {
3602         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
3603         Assert.check((tree.sym.flags_field & LOCKED) == 0);
3604         try {
3605             tree.sym.flags_field |= LOCKED;
3606             for (JCTree def : tree.defs) {
3607                 if (!def.hasTag(METHODDEF)) continue;
3608                 JCMethodDecl meth = (JCMethodDecl)def;
3609                 checkAnnotationResType(meth.pos(), meth.restype.type);
3610             }
3611         } finally {
3612             tree.sym.flags_field &= ~LOCKED;
3613             tree.sym.flags_field |= ACYCLIC_ANN;
3614         }
3615     }
3616 
checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym)3617     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
3618         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
3619             return;
3620         if ((tsym.flags_field & LOCKED) != 0) {
3621             log.error(pos, Errors.CyclicAnnotationElement(tsym));
3622             return;
3623         }
3624         try {
3625             tsym.flags_field |= LOCKED;
3626             for (Symbol s : tsym.members().getSymbols(NON_RECURSIVE)) {
3627                 if (s.kind != MTH)
3628                     continue;
3629                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
3630             }
3631         } finally {
3632             tsym.flags_field &= ~LOCKED;
3633             tsym.flags_field |= ACYCLIC_ANN;
3634         }
3635     }
3636 
checkAnnotationResType(DiagnosticPosition pos, Type type)3637     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
3638         switch (type.getTag()) {
3639         case CLASS:
3640             if ((type.tsym.flags() & ANNOTATION) != 0)
3641                 checkNonCyclicElementsInternal(pos, type.tsym);
3642             break;
3643         case ARRAY:
3644             checkAnnotationResType(pos, types.elemtype(type));
3645             break;
3646         default:
3647             break; // int etc
3648         }
3649     }
3650 
3651 /* *************************************************************************
3652  * Check for cycles in the constructor call graph.
3653  **************************************************************************/
3654 
3655     /** Check for cycles in the graph of constructors calling other
3656      *  constructors.
3657      */
checkCyclicConstructors(JCClassDecl tree)3658     void checkCyclicConstructors(JCClassDecl tree) {
3659         Map<Symbol,Symbol> callMap = new HashMap<>();
3660 
3661         // enter each constructor this-call into the map
3662         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
3663             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
3664             if (app == null) continue;
3665             JCMethodDecl meth = (JCMethodDecl) l.head;
3666             if (TreeInfo.name(app.meth) == names._this) {
3667                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
3668             } else {
3669                 meth.sym.flags_field |= ACYCLIC;
3670             }
3671         }
3672 
3673         // Check for cycles in the map
3674         Symbol[] ctors = new Symbol[0];
3675         ctors = callMap.keySet().toArray(ctors);
3676         for (Symbol caller : ctors) {
3677             checkCyclicConstructor(tree, caller, callMap);
3678         }
3679     }
3680 
3681     /** Look in the map to see if the given constructor is part of a
3682      *  call cycle.
3683      */
checkCyclicConstructor(JCClassDecl tree, Symbol ctor, Map<Symbol,Symbol> callMap)3684     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
3685                                         Map<Symbol,Symbol> callMap) {
3686         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
3687             if ((ctor.flags_field & LOCKED) != 0) {
3688                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
3689                           Errors.RecursiveCtorInvocation);
3690             } else {
3691                 ctor.flags_field |= LOCKED;
3692                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
3693                 ctor.flags_field &= ~LOCKED;
3694             }
3695             ctor.flags_field |= ACYCLIC;
3696         }
3697     }
3698 
3699 /* *************************************************************************
3700  * Miscellaneous
3701  **************************************************************************/
3702 
3703     /**
3704      *  Check for division by integer constant zero
3705      *  @param pos           Position for error reporting.
3706      *  @param operator      The operator for the expression
3707      *  @param operand       The right hand operand for the expression
3708      */
checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand)3709     void checkDivZero(final DiagnosticPosition pos, Symbol operator, Type operand) {
3710         if (operand.constValue() != null
3711             && operand.getTag().isSubRangeOf(LONG)
3712             && ((Number) (operand.constValue())).longValue() == 0) {
3713             int opc = ((OperatorSymbol)operator).opcode;
3714             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
3715                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
3716                 deferredLintHandler.report(() -> warnDivZero(pos));
3717             }
3718         }
3719     }
3720 
3721     /**
3722      * Check for empty statements after if
3723      */
checkEmptyIf(JCIf tree)3724     void checkEmptyIf(JCIf tree) {
3725         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
3726                 lint.isEnabled(LintCategory.EMPTY))
3727             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), Warnings.EmptyIf);
3728     }
3729 
3730     /** Check that symbol is unique in given scope.
3731      *  @param pos           Position for error reporting.
3732      *  @param sym           The symbol.
3733      *  @param s             The scope.
3734      */
checkUnique(DiagnosticPosition pos, Symbol sym, Scope s)3735     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
3736         if (sym.type.isErroneous())
3737             return true;
3738         if (sym.owner.name == names.any) return false;
3739         for (Symbol byName : s.getSymbolsByName(sym.name, NON_RECURSIVE)) {
3740             if (sym != byName &&
3741                     (byName.flags() & CLASH) == 0 &&
3742                     sym.kind == byName.kind &&
3743                     sym.name != names.error &&
3744                     (sym.kind != MTH ||
3745                      types.hasSameArgs(sym.type, byName.type) ||
3746                      types.hasSameArgs(types.erasure(sym.type), types.erasure(byName.type)))) {
3747                 if ((sym.flags() & VARARGS) != (byName.flags() & VARARGS)) {
3748                     sym.flags_field |= CLASH;
3749                     varargsDuplicateError(pos, sym, byName);
3750                     return true;
3751                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, byName.type, false)) {
3752                     duplicateErasureError(pos, sym, byName);
3753                     sym.flags_field |= CLASH;
3754                     return true;
3755                 } else if ((sym.flags() & MATCH_BINDING) != 0 &&
3756                            (byName.flags() & MATCH_BINDING) != 0 &&
3757                            (byName.flags() & MATCH_BINDING_TO_OUTER) == 0) {
3758                     if (!sym.type.isErroneous()) {
3759                         log.error(pos, Errors.MatchBindingExists);
3760                         sym.flags_field |= CLASH;
3761                     }
3762                     return false;
3763                 } else {
3764                     duplicateError(pos, byName);
3765                     return false;
3766                 }
3767             }
3768         }
3769         return true;
3770     }
3771 
3772     /** Report duplicate declaration error.
3773      */
duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2)3774     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
3775         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
3776             log.error(pos, Errors.NameClashSameErasure(sym1, sym2));
3777         }
3778     }
3779 
3780     /**Check that types imported through the ordinary imports don't clash with types imported
3781      * by other (static or ordinary) imports. Note that two static imports may import two clashing
3782      * types without an error on the imports.
3783      * @param toplevel       The toplevel tree for which the test should be performed.
3784      */
checkImportsUnique(JCCompilationUnit toplevel)3785     void checkImportsUnique(JCCompilationUnit toplevel) {
3786         WriteableScope ordinallyImportedSoFar = WriteableScope.create(toplevel.packge);
3787         WriteableScope staticallyImportedSoFar = WriteableScope.create(toplevel.packge);
3788         WriteableScope topLevelScope = toplevel.toplevelScope;
3789 
3790         for (JCTree def : toplevel.defs) {
3791             if (!def.hasTag(IMPORT))
3792                 continue;
3793 
3794             JCImport imp = (JCImport) def;
3795 
3796             if (imp.importScope == null)
3797                 continue;
3798 
3799             for (Symbol sym : imp.importScope.getSymbols(sym -> sym.kind == TYP)) {
3800                 if (imp.isStatic()) {
3801                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, true);
3802                     staticallyImportedSoFar.enter(sym);
3803                 } else {
3804                     checkUniqueImport(imp.pos(), ordinallyImportedSoFar, staticallyImportedSoFar, topLevelScope, sym, false);
3805                     ordinallyImportedSoFar.enter(sym);
3806                 }
3807             }
3808 
3809             imp.importScope = null;
3810         }
3811     }
3812 
3813     /** Check that single-type import is not already imported or top-level defined,
3814      *  but make an exception for two single-type imports which denote the same type.
3815      *  @param pos                     Position for error reporting.
3816      *  @param ordinallyImportedSoFar  A Scope containing types imported so far through
3817      *                                 ordinary imports.
3818      *  @param staticallyImportedSoFar A Scope containing types imported so far through
3819      *                                 static imports.
3820      *  @param topLevelScope           The current file's top-level Scope
3821      *  @param sym                     The symbol.
3822      *  @param staticImport            Whether or not this was a static import
3823      */
checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar, Scope staticallyImportedSoFar, Scope topLevelScope, Symbol sym, boolean staticImport)3824     private boolean checkUniqueImport(DiagnosticPosition pos, Scope ordinallyImportedSoFar,
3825                                       Scope staticallyImportedSoFar, Scope topLevelScope,
3826                                       Symbol sym, boolean staticImport) {
3827         Predicate<Symbol> duplicates = candidate -> candidate != sym && !candidate.type.isErroneous();
3828         Symbol ordinaryClashing = ordinallyImportedSoFar.findFirst(sym.name, duplicates);
3829         Symbol staticClashing = null;
3830         if (ordinaryClashing == null && !staticImport) {
3831             staticClashing = staticallyImportedSoFar.findFirst(sym.name, duplicates);
3832         }
3833         if (ordinaryClashing != null || staticClashing != null) {
3834             if (ordinaryClashing != null)
3835                 log.error(pos, Errors.AlreadyDefinedSingleImport(ordinaryClashing));
3836             else
3837                 log.error(pos, Errors.AlreadyDefinedStaticSingleImport(staticClashing));
3838             return false;
3839         }
3840         Symbol clashing = topLevelScope.findFirst(sym.name, duplicates);
3841         if (clashing != null) {
3842             log.error(pos, Errors.AlreadyDefinedThisUnit(clashing));
3843             return false;
3844         }
3845         return true;
3846     }
3847 
3848     /** Check that a qualified name is in canonical form (for import decls).
3849      */
checkCanonical(JCTree tree)3850     public void checkCanonical(JCTree tree) {
3851         if (!isCanonical(tree))
3852             log.error(tree.pos(),
3853                       Errors.ImportRequiresCanonical(TreeInfo.symbol(tree)));
3854     }
3855         // where
isCanonical(JCTree tree)3856         private boolean isCanonical(JCTree tree) {
3857             while (tree.hasTag(SELECT)) {
3858                 JCFieldAccess s = (JCFieldAccess) tree;
3859                 if (s.sym.owner.getQualifiedName() != TreeInfo.symbol(s.selected).getQualifiedName())
3860                     return false;
3861                 tree = s.selected;
3862             }
3863             return true;
3864         }
3865 
3866     /** Check that an auxiliary class is not accessed from any other file than its own.
3867      */
checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c)3868     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
3869         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
3870             (c.flags() & AUXILIARY) != 0 &&
3871             rs.isAccessible(env, c) &&
3872             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
3873         {
3874             log.warning(pos,
3875                         Warnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
3876         }
3877     }
3878 
3879     /**
3880      * Check for a default constructor in an exported package.
3881      */
checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos)3882     void checkDefaultConstructor(ClassSymbol c, DiagnosticPosition pos) {
3883         if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR) &&
3884             ((c.flags() & (ENUM | RECORD)) == 0) &&
3885             !c.isAnonymous() &&
3886             ((c.flags() & (PUBLIC | PROTECTED)) != 0) &&
3887             Feature.MODULES.allowedInSource(source)) {
3888             NestingKind nestingKind = c.getNestingKind();
3889             switch (nestingKind) {
3890                 case ANONYMOUS,
3891                      LOCAL -> {return;}
3892                 case TOP_LEVEL -> {;} // No additional checks needed
3893                 case MEMBER -> {
3894                     // For nested member classes, all the enclosing
3895                     // classes must be public or protected.
3896                     Symbol owner = c.owner;
3897                     while (owner != null && owner.kind == TYP) {
3898                         if ((owner.flags() & (PUBLIC | PROTECTED)) == 0)
3899                             return;
3900                         owner = owner.owner;
3901                     }
3902                 }
3903             }
3904 
3905             // Only check classes in named packages exported by its module
3906             PackageSymbol pkg = c.packge();
3907             if (!pkg.isUnnamed()) {
3908                 ModuleSymbol modle = pkg.modle;
3909                 for (ExportsDirective exportDir : modle.exports) {
3910                     // Report warning only if the containing
3911                     // package is unconditionally exported
3912                     if (exportDir.packge.equals(pkg)) {
3913                         if (exportDir.modules == null || exportDir.modules.isEmpty()) {
3914                             // Warning may be suppressed by
3915                             // annotations; check again for being
3916                             // enabled in the deferred context.
3917                             deferredLintHandler.report(() -> {
3918                                 if (lint.isEnabled(LintCategory.MISSING_EXPLICIT_CTOR))
3919                                    log.warning(LintCategory.MISSING_EXPLICIT_CTOR,
3920                                                pos, Warnings.MissingExplicitCtor(c, pkg, modle));
3921                                                        });
3922                         } else {
3923                             return;
3924                         }
3925                     }
3926                 }
3927             }
3928         }
3929         return;
3930     }
3931 
3932     private class ConversionWarner extends Warner {
3933         final String uncheckedKey;
3934         final Type found;
3935         final Type expected;
ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected)3936         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
3937             super(pos);
3938             this.uncheckedKey = uncheckedKey;
3939             this.found = found;
3940             this.expected = expected;
3941         }
3942 
3943         @Override
warn(LintCategory lint)3944         public void warn(LintCategory lint) {
3945             boolean warned = this.warned;
3946             super.warn(lint);
3947             if (warned) return; // suppress redundant diagnostics
3948             switch (lint) {
3949                 case UNCHECKED:
3950                     Check.this.warnUnchecked(pos(), Warnings.ProbFoundReq(diags.fragment(uncheckedKey), found, expected));
3951                     break;
3952                 case VARARGS:
3953                     if (method != null &&
3954                             method.attribute(syms.trustMeType.tsym) != null &&
3955                             isTrustMeAllowedOnMethod(method) &&
3956                             !types.isReifiable(method.type.getParameterTypes().last())) {
3957                         Check.this.warnUnsafeVararg(pos(), Warnings.VarargsUnsafeUseVarargsParam(method.params.last()));
3958                     }
3959                     break;
3960                 default:
3961                     throw new AssertionError("Unexpected lint: " + lint);
3962             }
3963         }
3964     }
3965 
castWarner(DiagnosticPosition pos, Type found, Type expected)3966     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
3967         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
3968     }
3969 
convertWarner(DiagnosticPosition pos, Type found, Type expected)3970     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
3971         return new ConversionWarner(pos, "unchecked.assign", found, expected);
3972     }
3973 
checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs)3974     public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
3975         Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
3976 
3977         if (functionalType != null) {
3978             try {
3979                 types.findDescriptorSymbol((TypeSymbol)cs);
3980             } catch (Types.FunctionDescriptorLookupError ex) {
3981                 DiagnosticPosition pos = tree.pos();
3982                 for (JCAnnotation a : tree.getModifiers().annotations) {
3983                     if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
3984                         pos = a.pos();
3985                         break;
3986                     }
3987                 }
3988                 log.error(pos, Errors.BadFunctionalIntfAnno1(ex.getDiagnostic()));
3989             }
3990         }
3991     }
3992 
checkImportsResolvable(final JCCompilationUnit toplevel)3993     public void checkImportsResolvable(final JCCompilationUnit toplevel) {
3994         for (final JCImport imp : toplevel.getImports()) {
3995             if (!imp.staticImport || !imp.qualid.hasTag(SELECT))
3996                 continue;
3997             final JCFieldAccess select = (JCFieldAccess) imp.qualid;
3998             final Symbol origin;
3999             if (select.name == names.asterisk || (origin = TreeInfo.symbol(select.selected)) == null || origin.kind != TYP)
4000                 continue;
4001 
4002             TypeSymbol site = (TypeSymbol) TreeInfo.symbol(select.selected);
4003             if (!checkTypeContainsImportableElement(site, site, toplevel.packge, select.name, new HashSet<Symbol>())) {
4004                 log.error(imp.pos(),
4005                           Errors.CantResolveLocation(KindName.STATIC,
4006                                                      select.name,
4007                                                      null,
4008                                                      null,
4009                                                      Fragments.Location(kindName(site),
4010                                                                         site,
4011                                                                         null)));
4012             }
4013         }
4014     }
4015 
4016     // Check that packages imported are in scope (JLS 7.4.3, 6.3, 6.5.3.1, 6.5.3.2)
checkImportedPackagesObservable(final JCCompilationUnit toplevel)4017     public void checkImportedPackagesObservable(final JCCompilationUnit toplevel) {
4018         OUTER: for (JCImport imp : toplevel.getImports()) {
4019             if (!imp.staticImport && TreeInfo.name(imp.qualid) == names.asterisk) {
4020                 TypeSymbol tsym = ((JCFieldAccess)imp.qualid).selected.type.tsym;
4021                 if (tsym.kind == PCK && tsym.members().isEmpty() &&
4022                     !(Feature.IMPORT_ON_DEMAND_OBSERVABLE_PACKAGES.allowedInSource(source) && tsym.exists())) {
4023                     log.error(DiagnosticFlag.RESOLVE_ERROR, imp.pos, Errors.DoesntExist(tsym));
4024                 }
4025             }
4026         }
4027     }
4028 
checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed)4029     private boolean checkTypeContainsImportableElement(TypeSymbol tsym, TypeSymbol origin, PackageSymbol packge, Name name, Set<Symbol> processed) {
4030         if (tsym == null || !processed.add(tsym))
4031             return false;
4032 
4033             // also search through inherited names
4034         if (checkTypeContainsImportableElement(types.supertype(tsym.type).tsym, origin, packge, name, processed))
4035             return true;
4036 
4037         for (Type t : types.interfaces(tsym.type))
4038             if (checkTypeContainsImportableElement(t.tsym, origin, packge, name, processed))
4039                 return true;
4040 
4041         for (Symbol sym : tsym.members().getSymbolsByName(name)) {
4042             if (sym.isStatic() &&
4043                 importAccessible(sym, packge) &&
4044                 sym.isMemberOf(origin, types)) {
4045                 return true;
4046             }
4047         }
4048 
4049         return false;
4050     }
4051 
4052     // is the sym accessible everywhere in packge?
importAccessible(Symbol sym, PackageSymbol packge)4053     public boolean importAccessible(Symbol sym, PackageSymbol packge) {
4054         try {
4055             int flags = (int)(sym.flags() & AccessFlags);
4056             switch (flags) {
4057             default:
4058             case PUBLIC:
4059                 return true;
4060             case PRIVATE:
4061                 return false;
4062             case 0:
4063             case PROTECTED:
4064                 return sym.packge() == packge;
4065             }
4066         } catch (ClassFinder.BadClassFile err) {
4067             throw err;
4068         } catch (CompletionFailure ex) {
4069             return false;
4070         }
4071     }
4072 
checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check)4073     public void checkLeaksNotAccessible(Env<AttrContext> env, JCClassDecl check) {
4074         JCCompilationUnit toplevel = env.toplevel;
4075 
4076         if (   toplevel.modle == syms.unnamedModule
4077             || toplevel.modle == syms.noModule
4078             || (check.sym.flags() & COMPOUND) != 0) {
4079             return ;
4080         }
4081 
4082         ExportsDirective currentExport = findExport(toplevel.packge);
4083 
4084         if (   currentExport == null //not exported
4085             || currentExport.modules != null) //don't check classes in qualified export
4086             return ;
4087 
4088         new TreeScanner() {
4089             Lint lint = env.info.lint;
4090             boolean inSuperType;
4091 
4092             @Override
4093             public void visitBlock(JCBlock tree) {
4094             }
4095             @Override
4096             public void visitMethodDef(JCMethodDecl tree) {
4097                 if (!isAPISymbol(tree.sym))
4098                     return;
4099                 Lint prevLint = lint;
4100                 try {
4101                     lint = lint.augment(tree.sym);
4102                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4103                         super.visitMethodDef(tree);
4104                     }
4105                 } finally {
4106                     lint = prevLint;
4107                 }
4108             }
4109             @Override
4110             public void visitVarDef(JCVariableDecl tree) {
4111                 if (!isAPISymbol(tree.sym) && tree.sym.owner.kind != MTH)
4112                     return;
4113                 Lint prevLint = lint;
4114                 try {
4115                     lint = lint.augment(tree.sym);
4116                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4117                         scan(tree.mods);
4118                         scan(tree.vartype);
4119                     }
4120                 } finally {
4121                     lint = prevLint;
4122                 }
4123             }
4124             @Override
4125             public void visitClassDef(JCClassDecl tree) {
4126                 if (tree != check)
4127                     return ;
4128 
4129                 if (!isAPISymbol(tree.sym))
4130                     return ;
4131 
4132                 Lint prevLint = lint;
4133                 try {
4134                     lint = lint.augment(tree.sym);
4135                     if (lint.isEnabled(LintCategory.EXPORTS)) {
4136                         scan(tree.mods);
4137                         scan(tree.typarams);
4138                         try {
4139                             inSuperType = true;
4140                             scan(tree.extending);
4141                             scan(tree.implementing);
4142                         } finally {
4143                             inSuperType = false;
4144                         }
4145                         scan(tree.defs);
4146                     }
4147                 } finally {
4148                     lint = prevLint;
4149                 }
4150             }
4151             @Override
4152             public void visitTypeApply(JCTypeApply tree) {
4153                 scan(tree.clazz);
4154                 boolean oldInSuperType = inSuperType;
4155                 try {
4156                     inSuperType = false;
4157                     scan(tree.arguments);
4158                 } finally {
4159                     inSuperType = oldInSuperType;
4160                 }
4161             }
4162             @Override
4163             public void visitIdent(JCIdent tree) {
4164                 Symbol sym = TreeInfo.symbol(tree);
4165                 if (sym.kind == TYP && !sym.type.hasTag(TYPEVAR)) {
4166                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4167                 }
4168             }
4169 
4170             @Override
4171             public void visitSelect(JCFieldAccess tree) {
4172                 Symbol sym = TreeInfo.symbol(tree);
4173                 Symbol sitesym = TreeInfo.symbol(tree.selected);
4174                 if (sym.kind == TYP && sitesym.kind == PCK) {
4175                     checkVisible(tree.pos(), sym, toplevel.packge, inSuperType);
4176                 } else {
4177                     super.visitSelect(tree);
4178                 }
4179             }
4180 
4181             @Override
4182             public void visitAnnotation(JCAnnotation tree) {
4183                 if (tree.attribute.type.tsym.getAnnotation(java.lang.annotation.Documented.class) != null)
4184                     super.visitAnnotation(tree);
4185             }
4186 
4187         }.scan(check);
4188     }
4189         //where:
findExport(PackageSymbol pack)4190         private ExportsDirective findExport(PackageSymbol pack) {
4191             for (ExportsDirective d : pack.modle.exports) {
4192                 if (d.packge == pack)
4193                     return d;
4194             }
4195 
4196             return null;
4197         }
isAPISymbol(Symbol sym)4198         private boolean isAPISymbol(Symbol sym) {
4199             while (sym.kind != PCK) {
4200                 if ((sym.flags() & Flags.PUBLIC) == 0 && (sym.flags() & Flags.PROTECTED) == 0) {
4201                     return false;
4202                 }
4203                 sym = sym.owner;
4204             }
4205             return true;
4206         }
checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType)4207         private void checkVisible(DiagnosticPosition pos, Symbol what, PackageSymbol inPackage, boolean inSuperType) {
4208             if (!isAPISymbol(what) && !inSuperType) { //package private/private element
4209                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessible(kindName(what), what, what.packge().modle));
4210                 return ;
4211             }
4212 
4213             PackageSymbol whatPackage = what.packge();
4214             ExportsDirective whatExport = findExport(whatPackage);
4215             ExportsDirective inExport = findExport(inPackage);
4216 
4217             if (whatExport == null) { //package not exported:
4218                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexported(kindName(what), what, what.packge().modle));
4219                 return ;
4220             }
4221 
4222             if (whatExport.modules != null) {
4223                 if (inExport.modules == null || !whatExport.modules.containsAll(inExport.modules)) {
4224                     log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleUnexportedQualified(kindName(what), what, what.packge().modle));
4225                 }
4226             }
4227 
4228             if (whatPackage.modle != inPackage.modle && whatPackage.modle != syms.java_base) {
4229                 //check that relativeTo.modle requires transitive what.modle, somehow:
4230                 List<ModuleSymbol> todo = List.of(inPackage.modle);
4231 
4232                 while (todo.nonEmpty()) {
4233                     ModuleSymbol current = todo.head;
4234                     todo = todo.tail;
4235                     if (current == whatPackage.modle)
4236                         return ; //OK
4237                     if ((current.flags() & Flags.AUTOMATIC_MODULE) != 0)
4238                         continue; //for automatic modules, don't look into their dependencies
4239                     for (RequiresDirective req : current.requires) {
4240                         if (req.isTransitive()) {
4241                             todo = todo.prepend(req.module);
4242                         }
4243                     }
4244                 }
4245 
4246                 log.warning(LintCategory.EXPORTS, pos, Warnings.LeaksNotAccessibleNotRequiredTransitive(kindName(what), what, what.packge().modle));
4247             }
4248         }
4249 
checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym)4250     void checkModuleExists(final DiagnosticPosition pos, ModuleSymbol msym) {
4251         if (msym.kind != MDL) {
4252             deferredLintHandler.report(() -> {
4253                 if (lint.isEnabled(LintCategory.MODULE))
4254                     log.warning(LintCategory.MODULE, pos, Warnings.ModuleNotFound(msym));
4255             });
4256         }
4257     }
4258 
checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge)4259     void checkPackageExistsForOpens(final DiagnosticPosition pos, PackageSymbol packge) {
4260         if (packge.members().isEmpty() &&
4261             ((packge.flags() & Flags.HAS_RESOURCE) == 0)) {
4262             deferredLintHandler.report(() -> {
4263                 if (lint.isEnabled(LintCategory.OPENS))
4264                     log.warning(pos, Warnings.PackageEmptyOrNotFound(packge));
4265             });
4266         }
4267     }
4268 
checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd)4269     void checkModuleRequires(final DiagnosticPosition pos, final RequiresDirective rd) {
4270         if ((rd.module.flags() & Flags.AUTOMATIC_MODULE) != 0) {
4271             deferredLintHandler.report(() -> {
4272                 if (rd.isTransitive() && lint.isEnabled(LintCategory.REQUIRES_TRANSITIVE_AUTOMATIC)) {
4273                     log.warning(pos, Warnings.RequiresTransitiveAutomatic);
4274                 } else if (lint.isEnabled(LintCategory.REQUIRES_AUTOMATIC)) {
4275                     log.warning(pos, Warnings.RequiresAutomatic);
4276                 }
4277             });
4278         }
4279     }
4280 
4281     /**
4282      * Verify the case labels conform to the constraints. Checks constraints related
4283      * combinations of patterns and other labels.
4284      *
4285      * @param cases the cases that should be checked.
4286      */
checkSwitchCaseStructure(List<JCCase> cases)4287     void checkSwitchCaseStructure(List<JCCase> cases) {
4288         boolean wasConstant = false;          // Seen a constant in the same case label
4289         boolean wasDefault = false;           // Seen a default in the same case label
4290         boolean wasNullPattern = false;       // Seen a null pattern in the same case label,
4291                                               //or fall through from a null pattern
4292         boolean wasPattern = false;           // Seen a pattern in the same case label
4293                                               //or fall through from a pattern
4294         boolean wasTypePattern = false;       // Seen a pattern in the same case label
4295                                               //or fall through from a type pattern
4296         boolean wasNonEmptyFallThrough = false;
4297         for (List<JCCase> l = cases; l.nonEmpty(); l = l.tail) {
4298             JCCase c = l.head;
4299             for (JCCaseLabel pat : c.labels) {
4300                 if (pat.isExpression()) {
4301                     JCExpression expr = (JCExpression) pat;
4302                     if (TreeInfo.isNull(expr)) {
4303                         if (wasPattern && !wasTypePattern && !wasNonEmptyFallThrough) {
4304                             log.error(pat.pos(), Errors.FlowsThroughFromPattern);
4305                         }
4306                         wasNullPattern = true;
4307                     } else {
4308                         if (wasPattern && !wasNonEmptyFallThrough) {
4309                             log.error(pat.pos(), Errors.FlowsThroughFromPattern);
4310                         }
4311                         wasConstant = true;
4312                     }
4313                 } else if (pat.hasTag(DEFAULTCASELABEL)) {
4314                     if (wasPattern && !wasNonEmptyFallThrough) {
4315                         log.error(pat.pos(), Errors.FlowsThroughFromPattern);
4316                     }
4317                     wasDefault = true;
4318                 } else {
4319                     boolean isTypePattern = pat.hasTag(BINDINGPATTERN);
4320                     if (wasPattern || wasConstant || wasDefault ||
4321                         (wasNullPattern && (!isTypePattern || wasNonEmptyFallThrough))) {
4322                         log.error(pat.pos(), Errors.FlowsThroughToPattern);
4323                     }
4324                     wasPattern = true;
4325                     wasTypePattern = isTypePattern;
4326                 }
4327             }
4328 
4329             boolean completesNormally = c.caseKind == CaseTree.CaseKind.STATEMENT ? c.completesNormally
4330                                                                                   : false;
4331 
4332             if (c.stats.nonEmpty()) {
4333                 wasConstant = false;
4334                 wasDefault = false;
4335                 wasNullPattern &= completesNormally;
4336                 wasPattern &= completesNormally;
4337                 wasTypePattern &= completesNormally;
4338             }
4339 
4340             wasNonEmptyFallThrough = c.stats.nonEmpty() && completesNormally;
4341         }
4342     }
4343 }
4344