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