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