src/share/classes/com/sun/tools/javac/comp/Check.java

Wed, 17 Jul 2013 14:19:25 +0100

author
mcimadamore
date
Wed, 17 Jul 2013 14:19:25 +0100
changeset 1904
b577222ef7b3
parent 1864
e42c27026290
child 1907
e990e6bcecbe
permissions
-rw-r--r--

8019340: varargs-related warnings are meaningless on signature-polymorphic methods such as MethodHandle.invokeExact
Summary: Disable certain varargs warnings when compiling polymorphic signature calls
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, 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  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import javax.tools.JavaFileManager;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.jvm.*;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.util.*;
    36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    37 import com.sun.tools.javac.util.List;
    39 import com.sun.tools.javac.code.Lint;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    44 import com.sun.tools.javac.comp.Infer.InferenceContext;
    45 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    46 import com.sun.tools.javac.tree.JCTree.*;
    47 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    49 import static com.sun.tools.javac.code.Flags.*;
    50 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    51 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    52 import static com.sun.tools.javac.code.Kinds.*;
    53 import static com.sun.tools.javac.code.TypeTag.*;
    54 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    56 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    58 /** Type checking helper class for the attribution phase.
    59  *
    60  *  <p><b>This is NOT part of any supported API.
    61  *  If you write code that depends on this, you do so at your own risk.
    62  *  This code and its internal interfaces are subject to change or
    63  *  deletion without notice.</b>
    64  */
    65 public class Check {
    66     protected static final Context.Key<Check> checkKey =
    67         new Context.Key<Check>();
    69     private final Names names;
    70     private final Log log;
    71     private final Resolve rs;
    72     private final Symtab syms;
    73     private final Enter enter;
    74     private final DeferredAttr deferredAttr;
    75     private final Infer infer;
    76     private final Types types;
    77     private final JCDiagnostic.Factory diags;
    78     private boolean warnOnSyntheticConflicts;
    79     private boolean suppressAbortOnBadClassFile;
    80     private boolean enableSunApiLintControl;
    81     private final TreeInfo treeinfo;
    82     private final JavaFileManager fileManager;
    83     private final Profile profile;
    85     // The set of lint options currently in effect. It is initialized
    86     // from the context, and then is set/reset as needed by Attr as it
    87     // visits all the various parts of the trees during attribution.
    88     private Lint lint;
    90     // The method being analyzed in Attr - it is set/reset as needed by
    91     // Attr as it visits new method declarations.
    92     private MethodSymbol method;
    94     public static Check instance(Context context) {
    95         Check instance = context.get(checkKey);
    96         if (instance == null)
    97             instance = new Check(context);
    98         return instance;
    99     }
   101     protected Check(Context context) {
   102         context.put(checkKey, this);
   104         names = Names.instance(context);
   105         dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE,
   106             names.FIELD, names.METHOD, names.CONSTRUCTOR,
   107             names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER};
   108         log = Log.instance(context);
   109         rs = Resolve.instance(context);
   110         syms = Symtab.instance(context);
   111         enter = Enter.instance(context);
   112         deferredAttr = DeferredAttr.instance(context);
   113         infer = Infer.instance(context);
   114         types = Types.instance(context);
   115         diags = JCDiagnostic.Factory.instance(context);
   116         Options options = Options.instance(context);
   117         lint = Lint.instance(context);
   118         treeinfo = TreeInfo.instance(context);
   119         fileManager = context.get(JavaFileManager.class);
   121         Source source = Source.instance(context);
   122         allowGenerics = source.allowGenerics();
   123         allowVarargs = source.allowVarargs();
   124         allowAnnotations = source.allowAnnotations();
   125         allowCovariantReturns = source.allowCovariantReturns();
   126         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   127         allowDefaultMethods = source.allowDefaultMethods();
   128         allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
   129         complexInference = options.isSet("complexinference");
   130         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   131         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   132         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   134         Target target = Target.instance(context);
   135         syntheticNameChar = target.syntheticNameChar();
   137         profile = Profile.instance(context);
   139         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   140         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   141         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   142         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   144         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   145                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   146         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   147                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   148         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   149                 enforceMandatoryWarnings, "sunapi", null);
   151         deferredLintHandler = DeferredLintHandler.immediateHandler;
   152     }
   154     /** Switch: generics enabled?
   155      */
   156     boolean allowGenerics;
   158     /** Switch: varargs enabled?
   159      */
   160     boolean allowVarargs;
   162     /** Switch: annotations enabled?
   163      */
   164     boolean allowAnnotations;
   166     /** Switch: covariant returns enabled?
   167      */
   168     boolean allowCovariantReturns;
   170     /** Switch: simplified varargs enabled?
   171      */
   172     boolean allowSimplifiedVarargs;
   174     /** Switch: default methods enabled?
   175      */
   176     boolean allowDefaultMethods;
   178     /** Switch: should unrelated return types trigger a method clash?
   179      */
   180     boolean allowStrictMethodClashCheck;
   182     /** Switch: -complexinference option set?
   183      */
   184     boolean complexInference;
   186     /** Character for synthetic names
   187      */
   188     char syntheticNameChar;
   190     /** A table mapping flat names of all compiled classes in this run to their
   191      *  symbols; maintained from outside.
   192      */
   193     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   195     /** A handler for messages about deprecated usage.
   196      */
   197     private MandatoryWarningHandler deprecationHandler;
   199     /** A handler for messages about unchecked or unsafe usage.
   200      */
   201     private MandatoryWarningHandler uncheckedHandler;
   203     /** A handler for messages about using proprietary API.
   204      */
   205     private MandatoryWarningHandler sunApiHandler;
   207     /** A handler for deferred lint warnings.
   208      */
   209     private DeferredLintHandler deferredLintHandler;
   211 /* *************************************************************************
   212  * Errors and Warnings
   213  **************************************************************************/
   215     Lint setLint(Lint newLint) {
   216         Lint prev = lint;
   217         lint = newLint;
   218         return prev;
   219     }
   221     /*  This idiom should be used only in cases when it is needed to set the lint
   222      *  of an environment that has been created in a phase previous to annotations
   223      *  processing.
   224      */
   225     Lint getLint() {
   226         return lint;
   227     }
   229     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   230         DeferredLintHandler prev = deferredLintHandler;
   231         deferredLintHandler = newDeferredLintHandler;
   232         return prev;
   233     }
   235     MethodSymbol setMethod(MethodSymbol newMethod) {
   236         MethodSymbol prev = method;
   237         method = newMethod;
   238         return prev;
   239     }
   241     /** Warn about deprecated symbol.
   242      *  @param pos        Position to be used for error reporting.
   243      *  @param sym        The deprecated symbol.
   244      */
   245     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   246         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   247             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   248     }
   250     /** Warn about unchecked operation.
   251      *  @param pos        Position to be used for error reporting.
   252      *  @param msg        A string describing the problem.
   253      */
   254     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   255         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   256             uncheckedHandler.report(pos, msg, args);
   257     }
   259     /** Warn about unsafe vararg method decl.
   260      *  @param pos        Position to be used for error reporting.
   261      */
   262     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   263         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   264             log.warning(LintCategory.VARARGS, pos, key, args);
   265     }
   267     /** Warn about using proprietary API.
   268      *  @param pos        Position to be used for error reporting.
   269      *  @param msg        A string describing the problem.
   270      */
   271     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   272         if (!lint.isSuppressed(LintCategory.SUNAPI))
   273             sunApiHandler.report(pos, msg, args);
   274     }
   276     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   277         if (lint.isEnabled(LintCategory.STATIC))
   278             log.warning(LintCategory.STATIC, pos, msg, args);
   279     }
   281     /**
   282      * Report any deferred diagnostics.
   283      */
   284     public void reportDeferredDiagnostics() {
   285         deprecationHandler.reportDeferredDiagnostic();
   286         uncheckedHandler.reportDeferredDiagnostic();
   287         sunApiHandler.reportDeferredDiagnostic();
   288     }
   291     /** Report a failure to complete a class.
   292      *  @param pos        Position to be used for error reporting.
   293      *  @param ex         The failure to report.
   294      */
   295     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   296         log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue());
   297         if (ex instanceof ClassReader.BadClassFile
   298                 && !suppressAbortOnBadClassFile) throw new Abort();
   299         else return syms.errType;
   300     }
   302     /** Report an error that wrong type tag was found.
   303      *  @param pos        Position to be used for error reporting.
   304      *  @param required   An internationalized string describing the type tag
   305      *                    required.
   306      *  @param found      The type that was found.
   307      */
   308     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   309         // this error used to be raised by the parser,
   310         // but has been delayed to this point:
   311         if (found instanceof Type && ((Type)found).hasTag(VOID)) {
   312             log.error(pos, "illegal.start.of.type");
   313             return syms.errType;
   314         }
   315         log.error(pos, "type.found.req", found, required);
   316         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   317     }
   319     /** Report an error that symbol cannot be referenced before super
   320      *  has been called.
   321      *  @param pos        Position to be used for error reporting.
   322      *  @param sym        The referenced symbol.
   323      */
   324     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   325         log.error(pos, "cant.ref.before.ctor.called", sym);
   326     }
   328     /** Report duplicate declaration error.
   329      */
   330     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   331         if (!sym.type.isErroneous()) {
   332             Symbol location = sym.location();
   333             if (location.kind == MTH &&
   334                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   335                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   336                         kindName(sym.location()), kindName(sym.location().enclClass()),
   337                         sym.location().enclClass());
   338             } else {
   339                 log.error(pos, "already.defined", kindName(sym), sym,
   340                         kindName(sym.location()), sym.location());
   341             }
   342         }
   343     }
   345     /** Report array/varargs duplicate declaration
   346      */
   347     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   348         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   349             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   350         }
   351     }
   353 /* ************************************************************************
   354  * duplicate declaration checking
   355  *************************************************************************/
   357     /** Check that variable does not hide variable with same name in
   358      *  immediately enclosing local scope.
   359      *  @param pos           Position for error reporting.
   360      *  @param v             The symbol.
   361      *  @param s             The scope.
   362      */
   363     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   364         if (s.next != null) {
   365             for (Scope.Entry e = s.next.lookup(v.name);
   366                  e.scope != null && e.sym.owner == v.owner;
   367                  e = e.next()) {
   368                 if (e.sym.kind == VAR &&
   369                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   370                     v.name != names.error) {
   371                     duplicateError(pos, e.sym);
   372                     return;
   373                 }
   374             }
   375         }
   376     }
   378     /** Check that a class or interface does not hide a class or
   379      *  interface with same name in immediately enclosing local scope.
   380      *  @param pos           Position for error reporting.
   381      *  @param c             The symbol.
   382      *  @param s             The scope.
   383      */
   384     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   385         if (s.next != null) {
   386             for (Scope.Entry e = s.next.lookup(c.name);
   387                  e.scope != null && e.sym.owner == c.owner;
   388                  e = e.next()) {
   389                 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
   390                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   391                     c.name != names.error) {
   392                     duplicateError(pos, e.sym);
   393                     return;
   394                 }
   395             }
   396         }
   397     }
   399     /** Check that class does not have the same name as one of
   400      *  its enclosing classes, or as a class defined in its enclosing scope.
   401      *  return true if class is unique in its enclosing scope.
   402      *  @param pos           Position for error reporting.
   403      *  @param name          The class name.
   404      *  @param s             The enclosing scope.
   405      */
   406     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   407         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   408             if (e.sym.kind == TYP && e.sym.name != names.error) {
   409                 duplicateError(pos, e.sym);
   410                 return false;
   411             }
   412         }
   413         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   414             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   415                 duplicateError(pos, sym);
   416                 return true;
   417             }
   418         }
   419         return true;
   420     }
   422 /* *************************************************************************
   423  * Class name generation
   424  **************************************************************************/
   426     /** Return name of local class.
   427      *  This is of the form   {@code <enclClass> $ n <classname> }
   428      *  where
   429      *    enclClass is the flat name of the enclosing class,
   430      *    classname is the simple name of the local class
   431      */
   432     Name localClassName(ClassSymbol c) {
   433         for (int i=1; ; i++) {
   434             Name flatname = names.
   435                 fromString("" + c.owner.enclClass().flatname +
   436                            syntheticNameChar + i +
   437                            c.name);
   438             if (compiled.get(flatname) == null) return flatname;
   439         }
   440     }
   442 /* *************************************************************************
   443  * Type Checking
   444  **************************************************************************/
   446     /**
   447      * A check context is an object that can be used to perform compatibility
   448      * checks - depending on the check context, meaning of 'compatibility' might
   449      * vary significantly.
   450      */
   451     public interface CheckContext {
   452         /**
   453          * Is type 'found' compatible with type 'req' in given context
   454          */
   455         boolean compatible(Type found, Type req, Warner warn);
   456         /**
   457          * Report a check error
   458          */
   459         void report(DiagnosticPosition pos, JCDiagnostic details);
   460         /**
   461          * Obtain a warner for this check context
   462          */
   463         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   465         public Infer.InferenceContext inferenceContext();
   467         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   468     }
   470     /**
   471      * This class represent a check context that is nested within another check
   472      * context - useful to check sub-expressions. The default behavior simply
   473      * redirects all method calls to the enclosing check context leveraging
   474      * the forwarding pattern.
   475      */
   476     static class NestedCheckContext implements CheckContext {
   477         CheckContext enclosingContext;
   479         NestedCheckContext(CheckContext enclosingContext) {
   480             this.enclosingContext = enclosingContext;
   481         }
   483         public boolean compatible(Type found, Type req, Warner warn) {
   484             return enclosingContext.compatible(found, req, warn);
   485         }
   487         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   488             enclosingContext.report(pos, details);
   489         }
   491         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   492             return enclosingContext.checkWarner(pos, found, req);
   493         }
   495         public Infer.InferenceContext inferenceContext() {
   496             return enclosingContext.inferenceContext();
   497         }
   499         public DeferredAttrContext deferredAttrContext() {
   500             return enclosingContext.deferredAttrContext();
   501         }
   502     }
   504     /**
   505      * Check context to be used when evaluating assignment/return statements
   506      */
   507     CheckContext basicHandler = new CheckContext() {
   508         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   509             log.error(pos, "prob.found.req", details);
   510         }
   511         public boolean compatible(Type found, Type req, Warner warn) {
   512             return types.isAssignable(found, req, warn);
   513         }
   515         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   516             return convertWarner(pos, found, req);
   517         }
   519         public InferenceContext inferenceContext() {
   520             return infer.emptyContext;
   521         }
   523         public DeferredAttrContext deferredAttrContext() {
   524             return deferredAttr.emptyDeferredAttrContext;
   525         }
   526     };
   528     /** Check that a given type is assignable to a given proto-type.
   529      *  If it is, return the type, otherwise return errType.
   530      *  @param pos        Position to be used for error reporting.
   531      *  @param found      The type that was found.
   532      *  @param req        The type that was required.
   533      */
   534     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   535         return checkType(pos, found, req, basicHandler);
   536     }
   538     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   539         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   540         if (inferenceContext.free(req)) {
   541             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   542                 @Override
   543                 public void typesInferred(InferenceContext inferenceContext) {
   544                     checkType(pos, found, inferenceContext.asInstType(req), checkContext);
   545                 }
   546             });
   547         }
   548         if (req.hasTag(ERROR))
   549             return req;
   550         if (req.hasTag(NONE))
   551             return found;
   552         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   553             return found;
   554         } else {
   555             if (found.isNumeric() && req.isNumeric()) {
   556                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   557                 return types.createErrorType(found);
   558             }
   559             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   560             return types.createErrorType(found);
   561         }
   562     }
   564     /** Check that a given type can be cast to a given target type.
   565      *  Return the result of the cast.
   566      *  @param pos        Position to be used for error reporting.
   567      *  @param found      The type that is being cast.
   568      *  @param req        The target type of the cast.
   569      */
   570     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   571         return checkCastable(pos, found, req, basicHandler);
   572     }
   573     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   574         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   575             return req;
   576         } else {
   577             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   578             return types.createErrorType(found);
   579         }
   580     }
   582     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   583      * The problem should only be reported for non-292 cast
   584      */
   585     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   586         if (!tree.type.isErroneous() &&
   587                 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   588                 && types.isSameType(tree.expr.type, tree.clazz.type)
   589                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
   590                 && !is292targetTypeCast(tree)) {
   591             log.warning(Lint.LintCategory.CAST,
   592                     tree.pos(), "redundant.cast", tree.expr.type);
   593         }
   594     }
   595     //where
   596         private boolean is292targetTypeCast(JCTypeCast tree) {
   597             boolean is292targetTypeCast = false;
   598             JCExpression expr = TreeInfo.skipParens(tree.expr);
   599             if (expr.hasTag(APPLY)) {
   600                 JCMethodInvocation apply = (JCMethodInvocation)expr;
   601                 Symbol sym = TreeInfo.symbol(apply.meth);
   602                 is292targetTypeCast = sym != null &&
   603                     sym.kind == MTH &&
   604                     (sym.flags() & HYPOTHETICAL) != 0;
   605             }
   606             return is292targetTypeCast;
   607         }
   609         private static final boolean ignoreAnnotatedCasts = true;
   611     /** Check that a type is within some bounds.
   612      *
   613      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
   614      *  type argument.
   615      *  @param a             The type that should be bounded by bs.
   616      *  @param bound         The bound.
   617      */
   618     private boolean checkExtends(Type a, Type bound) {
   619          if (a.isUnbound()) {
   620              return true;
   621          } else if (!a.hasTag(WILDCARD)) {
   622              a = types.upperBound(a);
   623              return types.isSubtype(a, bound);
   624          } else if (a.isExtendsBound()) {
   625              return types.isCastable(bound, types.upperBound(a), types.noWarnings);
   626          } else if (a.isSuperBound()) {
   627              return !types.notSoftSubtype(types.lowerBound(a), bound);
   628          }
   629          return true;
   630      }
   632     /** Check that type is different from 'void'.
   633      *  @param pos           Position to be used for error reporting.
   634      *  @param t             The type to be checked.
   635      */
   636     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   637         if (t.hasTag(VOID)) {
   638             log.error(pos, "void.not.allowed.here");
   639             return types.createErrorType(t);
   640         } else {
   641             return t;
   642         }
   643     }
   645     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
   646         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
   647             return typeTagError(pos,
   648                                 diags.fragment("type.req.class.array"),
   649                                 asTypeParam(t));
   650         } else {
   651             return t;
   652         }
   653     }
   655     /** Check that type is a class or interface type.
   656      *  @param pos           Position to be used for error reporting.
   657      *  @param t             The type to be checked.
   658      */
   659     Type checkClassType(DiagnosticPosition pos, Type t) {
   660         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
   661             return typeTagError(pos,
   662                                 diags.fragment("type.req.class"),
   663                                 asTypeParam(t));
   664         } else {
   665             return t;
   666         }
   667     }
   668     //where
   669         private Object asTypeParam(Type t) {
   670             return (t.hasTag(TYPEVAR))
   671                                     ? diags.fragment("type.parameter", t)
   672                                     : t;
   673         }
   675     /** Check that type is a valid qualifier for a constructor reference expression
   676      */
   677     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
   678         t = checkClassOrArrayType(pos, t);
   679         if (t.hasTag(CLASS)) {
   680             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
   681                 log.error(pos, "abstract.cant.be.instantiated", t.tsym);
   682                 t = types.createErrorType(t);
   683             } else if ((t.tsym.flags() & ENUM) != 0) {
   684                 log.error(pos, "enum.cant.be.instantiated");
   685                 t = types.createErrorType(t);
   686             } else {
   687                 t = checkClassType(pos, t, true);
   688             }
   689         } else if (t.hasTag(ARRAY)) {
   690             if (!types.isReifiable(((ArrayType)t).elemtype)) {
   691                 log.error(pos, "generic.array.creation");
   692                 t = types.createErrorType(t);
   693             }
   694         }
   695         return t;
   696     }
   698     /** Check that type is a class or interface type.
   699      *  @param pos           Position to be used for error reporting.
   700      *  @param t             The type to be checked.
   701      *  @param noBounds    True if type bounds are illegal here.
   702      */
   703     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   704         t = checkClassType(pos, t);
   705         if (noBounds && t.isParameterized()) {
   706             List<Type> args = t.getTypeArguments();
   707             while (args.nonEmpty()) {
   708                 if (args.head.hasTag(WILDCARD))
   709                     return typeTagError(pos,
   710                                         diags.fragment("type.req.exact"),
   711                                         args.head);
   712                 args = args.tail;
   713             }
   714         }
   715         return t;
   716     }
   718     /** Check that type is a reifiable class, interface or array type.
   719      *  @param pos           Position to be used for error reporting.
   720      *  @param t             The type to be checked.
   721      */
   722     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   723         t = checkClassOrArrayType(pos, t);
   724         if (!t.isErroneous() && !types.isReifiable(t)) {
   725             log.error(pos, "illegal.generic.type.for.instof");
   726             return types.createErrorType(t);
   727         } else {
   728             return t;
   729         }
   730     }
   732     /** Check that type is a reference type, i.e. a class, interface or array type
   733      *  or a type variable.
   734      *  @param pos           Position to be used for error reporting.
   735      *  @param t             The type to be checked.
   736      */
   737     Type checkRefType(DiagnosticPosition pos, Type t) {
   738         if (t.isReference())
   739             return t;
   740         else
   741             return typeTagError(pos,
   742                                 diags.fragment("type.req.ref"),
   743                                 t);
   744     }
   746     /** Check that each type is a reference type, i.e. a class, interface or array type
   747      *  or a type variable.
   748      *  @param trees         Original trees, used for error reporting.
   749      *  @param types         The types to be checked.
   750      */
   751     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   752         List<JCExpression> tl = trees;
   753         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   754             l.head = checkRefType(tl.head.pos(), l.head);
   755             tl = tl.tail;
   756         }
   757         return types;
   758     }
   760     /** Check that type is a null or reference type.
   761      *  @param pos           Position to be used for error reporting.
   762      *  @param t             The type to be checked.
   763      */
   764     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   765         if (t.isReference() || t.hasTag(BOT))
   766             return t;
   767         else
   768             return typeTagError(pos,
   769                                 diags.fragment("type.req.ref"),
   770                                 t);
   771     }
   773     /** Check that flag set does not contain elements of two conflicting sets. s
   774      *  Return true if it doesn't.
   775      *  @param pos           Position to be used for error reporting.
   776      *  @param flags         The set of flags to be checked.
   777      *  @param set1          Conflicting flags set #1.
   778      *  @param set2          Conflicting flags set #2.
   779      */
   780     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   781         if ((flags & set1) != 0 && (flags & set2) != 0) {
   782             log.error(pos,
   783                       "illegal.combination.of.modifiers",
   784                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   785                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   786             return false;
   787         } else
   788             return true;
   789     }
   791     /** Check that usage of diamond operator is correct (i.e. diamond should not
   792      * be used with non-generic classes or in anonymous class creation expressions)
   793      */
   794     Type checkDiamond(JCNewClass tree, Type t) {
   795         if (!TreeInfo.isDiamond(tree) ||
   796                 t.isErroneous()) {
   797             return checkClassType(tree.clazz.pos(), t, true);
   798         } else if (tree.def != null) {
   799             log.error(tree.clazz.pos(),
   800                     "cant.apply.diamond.1",
   801                     t, diags.fragment("diamond.and.anon.class", t));
   802             return types.createErrorType(t);
   803         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   804             log.error(tree.clazz.pos(),
   805                 "cant.apply.diamond.1",
   806                 t, diags.fragment("diamond.non.generic", t));
   807             return types.createErrorType(t);
   808         } else if (tree.typeargs != null &&
   809                 tree.typeargs.nonEmpty()) {
   810             log.error(tree.clazz.pos(),
   811                 "cant.apply.diamond.1",
   812                 t, diags.fragment("diamond.and.explicit.params", t));
   813             return types.createErrorType(t);
   814         } else {
   815             return t;
   816         }
   817     }
   819     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   820         MethodSymbol m = tree.sym;
   821         if (!allowSimplifiedVarargs) return;
   822         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   823         Type varargElemType = null;
   824         if (m.isVarArgs()) {
   825             varargElemType = types.elemtype(tree.params.last().type);
   826         }
   827         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   828             if (varargElemType != null) {
   829                 log.error(tree,
   830                         "varargs.invalid.trustme.anno",
   831                         syms.trustMeType.tsym,
   832                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   833             } else {
   834                 log.error(tree,
   835                             "varargs.invalid.trustme.anno",
   836                             syms.trustMeType.tsym,
   837                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   838             }
   839         } else if (hasTrustMeAnno && varargElemType != null &&
   840                             types.isReifiable(varargElemType)) {
   841             warnUnsafeVararg(tree,
   842                             "varargs.redundant.trustme.anno",
   843                             syms.trustMeType.tsym,
   844                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   845         }
   846         else if (!hasTrustMeAnno && varargElemType != null &&
   847                 !types.isReifiable(varargElemType)) {
   848             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   849         }
   850     }
   851     //where
   852         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   853             return (s.flags() & VARARGS) != 0 &&
   854                 (s.isConstructor() ||
   855                     (s.flags() & (STATIC | FINAL)) != 0);
   856         }
   858     Type checkMethod(final Type mtype,
   859             final Symbol sym,
   860             final Env<AttrContext> env,
   861             final List<JCExpression> argtrees,
   862             final List<Type> argtypes,
   863             final boolean useVarargs,
   864             InferenceContext inferenceContext) {
   865         // System.out.println("call   : " + env.tree);
   866         // System.out.println("method : " + owntype);
   867         // System.out.println("actuals: " + argtypes);
   868         if (inferenceContext.free(mtype)) {
   869             inferenceContext.addFreeTypeListener(List.of(mtype), new FreeTypeListener() {
   870                 public void typesInferred(InferenceContext inferenceContext) {
   871                     checkMethod(inferenceContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, inferenceContext);
   872                 }
   873             });
   874             return mtype;
   875         }
   876         Type owntype = mtype;
   877         List<Type> formals = owntype.getParameterTypes();
   878         Type last = useVarargs ? formals.last() : null;
   879         if (sym.name == names.init &&
   880                 sym.owner == syms.enumSym)
   881                 formals = formals.tail.tail;
   882         List<JCExpression> args = argtrees;
   883         if (args != null) {
   884             //this is null when type-checking a method reference
   885             while (formals.head != last) {
   886                 JCTree arg = args.head;
   887                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   888                 assertConvertible(arg, arg.type, formals.head, warn);
   889                 args = args.tail;
   890                 formals = formals.tail;
   891             }
   892             if (useVarargs) {
   893                 Type varArg = types.elemtype(last);
   894                 while (args.tail != null) {
   895                     JCTree arg = args.head;
   896                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   897                     assertConvertible(arg, arg.type, varArg, warn);
   898                     args = args.tail;
   899                 }
   900             } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS &&
   901                     allowVarargs) {
   902                 // non-varargs call to varargs method
   903                 Type varParam = owntype.getParameterTypes().last();
   904                 Type lastArg = argtypes.last();
   905                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   906                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   907                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   908                             types.elemtype(varParam), varParam);
   909             }
   910         }
   911         if (useVarargs) {
   912             Type argtype = owntype.getParameterTypes().last();
   913             if (!types.isReifiable(argtype) &&
   914                     (!allowSimplifiedVarargs ||
   915                     sym.attribute(syms.trustMeType.tsym) == null ||
   916                     !isTrustMeAllowedOnMethod(sym))) {
   917                 warnUnchecked(env.tree.pos(),
   918                                   "unchecked.generic.array.creation",
   919                                   argtype);
   920             }
   921             if ((sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) == 0) {
   922                 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
   923             }
   924          }
   925          PolyKind pkind = (sym.type.hasTag(FORALL) &&
   926                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
   927                  PolyKind.POLY : PolyKind.STANDALONE;
   928          TreeInfo.setPolyKind(env.tree, pkind);
   929          return owntype;
   930     }
   931     //where
   932         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   933             if (types.isConvertible(actual, formal, warn))
   934                 return;
   936             if (formal.isCompound()
   937                 && types.isSubtype(actual, types.supertype(formal))
   938                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   939                 return;
   940         }
   942     /**
   943      * Check that type 't' is a valid instantiation of a generic class
   944      * (see JLS 4.5)
   945      *
   946      * @param t class type to be checked
   947      * @return true if 't' is well-formed
   948      */
   949     public boolean checkValidGenericType(Type t) {
   950         return firstIncompatibleTypeArg(t) == null;
   951     }
   952     //WHERE
   953         private Type firstIncompatibleTypeArg(Type type) {
   954             List<Type> formals = type.tsym.type.allparams();
   955             List<Type> actuals = type.allparams();
   956             List<Type> args = type.getTypeArguments();
   957             List<Type> forms = type.tsym.type.getTypeArguments();
   958             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   960             // For matching pairs of actual argument types `a' and
   961             // formal type parameters with declared bound `b' ...
   962             while (args.nonEmpty() && forms.nonEmpty()) {
   963                 // exact type arguments needs to know their
   964                 // bounds (for upper and lower bound
   965                 // calculations).  So we create new bounds where
   966                 // type-parameters are replaced with actuals argument types.
   967                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   968                 args = args.tail;
   969                 forms = forms.tail;
   970             }
   972             args = type.getTypeArguments();
   973             List<Type> tvars_cap = types.substBounds(formals,
   974                                       formals,
   975                                       types.capture(type).allparams());
   976             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   977                 // Let the actual arguments know their bound
   978                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   979                 args = args.tail;
   980                 tvars_cap = tvars_cap.tail;
   981             }
   983             args = type.getTypeArguments();
   984             List<Type> bounds = bounds_buf.toList();
   986             while (args.nonEmpty() && bounds.nonEmpty()) {
   987                 Type actual = args.head;
   988                 if (!isTypeArgErroneous(actual) &&
   989                         !bounds.head.isErroneous() &&
   990                         !checkExtends(actual, bounds.head)) {
   991                     return args.head;
   992                 }
   993                 args = args.tail;
   994                 bounds = bounds.tail;
   995             }
   997             args = type.getTypeArguments();
   998             bounds = bounds_buf.toList();
  1000             for (Type arg : types.capture(type).getTypeArguments()) {
  1001                 if (arg.hasTag(TYPEVAR) &&
  1002                         arg.getUpperBound().isErroneous() &&
  1003                         !bounds.head.isErroneous() &&
  1004                         !isTypeArgErroneous(args.head)) {
  1005                     return args.head;
  1007                 bounds = bounds.tail;
  1008                 args = args.tail;
  1011             return null;
  1013         //where
  1014         boolean isTypeArgErroneous(Type t) {
  1015             return isTypeArgErroneous.visit(t);
  1018         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1019             public Boolean visitType(Type t, Void s) {
  1020                 return t.isErroneous();
  1022             @Override
  1023             public Boolean visitTypeVar(TypeVar t, Void s) {
  1024                 return visit(t.getUpperBound());
  1026             @Override
  1027             public Boolean visitCapturedType(CapturedType t, Void s) {
  1028                 return visit(t.getUpperBound()) ||
  1029                         visit(t.getLowerBound());
  1031             @Override
  1032             public Boolean visitWildcardType(WildcardType t, Void s) {
  1033                 return visit(t.type);
  1035         };
  1037     /** Check that given modifiers are legal for given symbol and
  1038      *  return modifiers together with any implicit modifiers for that symbol.
  1039      *  Warning: we can't use flags() here since this method
  1040      *  is called during class enter, when flags() would cause a premature
  1041      *  completion.
  1042      *  @param pos           Position to be used for error reporting.
  1043      *  @param flags         The set of modifiers given in a definition.
  1044      *  @param sym           The defined symbol.
  1045      */
  1046     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1047         long mask;
  1048         long implicit = 0;
  1049         switch (sym.kind) {
  1050         case VAR:
  1051             if (sym.owner.kind != TYP)
  1052                 mask = LocalVarFlags;
  1053             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1054                 mask = implicit = InterfaceVarFlags;
  1055             else
  1056                 mask = VarFlags;
  1057             break;
  1058         case MTH:
  1059             if (sym.name == names.init) {
  1060                 if ((sym.owner.flags_field & ENUM) != 0) {
  1061                     // enum constructors cannot be declared public or
  1062                     // protected and must be implicitly or explicitly
  1063                     // private
  1064                     implicit = PRIVATE;
  1065                     mask = PRIVATE;
  1066                 } else
  1067                     mask = ConstructorFlags;
  1068             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1069                 if ((flags & (DEFAULT | STATIC)) != 0) {
  1070                     mask = InterfaceMethodMask;
  1071                     implicit = PUBLIC;
  1072                     if ((flags & DEFAULT) != 0) {
  1073                         implicit |= ABSTRACT;
  1075                 } else {
  1076                     mask = implicit = InterfaceMethodFlags;
  1079             else {
  1080                 mask = MethodFlags;
  1082             // Imply STRICTFP if owner has STRICTFP set.
  1083             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
  1084                 ((flags) & Flags.DEFAULT) != 0)
  1085                 implicit |= sym.owner.flags_field & STRICTFP;
  1086             break;
  1087         case TYP:
  1088             if (sym.isLocal()) {
  1089                 mask = LocalClassFlags;
  1090                 if (sym.name.isEmpty()) { // Anonymous class
  1091                     // Anonymous classes in static methods are themselves static;
  1092                     // that's why we admit STATIC here.
  1093                     mask |= STATIC;
  1094                     // JLS: Anonymous classes are final.
  1095                     implicit |= FINAL;
  1097                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1098                     (flags & ENUM) != 0)
  1099                     log.error(pos, "enums.must.be.static");
  1100             } else if (sym.owner.kind == TYP) {
  1101                 mask = MemberClassFlags;
  1102                 if (sym.owner.owner.kind == PCK ||
  1103                     (sym.owner.flags_field & STATIC) != 0)
  1104                     mask |= STATIC;
  1105                 else if ((flags & ENUM) != 0)
  1106                     log.error(pos, "enums.must.be.static");
  1107                 // Nested interfaces and enums are always STATIC (Spec ???)
  1108                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1109             } else {
  1110                 mask = ClassFlags;
  1112             // Interfaces are always ABSTRACT
  1113             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1115             if ((flags & ENUM) != 0) {
  1116                 // enums can't be declared abstract or final
  1117                 mask &= ~(ABSTRACT | FINAL);
  1118                 implicit |= implicitEnumFinalFlag(tree);
  1120             // Imply STRICTFP if owner has STRICTFP set.
  1121             implicit |= sym.owner.flags_field & STRICTFP;
  1122             break;
  1123         default:
  1124             throw new AssertionError();
  1126         long illegal = flags & ExtendedStandardFlags & ~mask;
  1127         if (illegal != 0) {
  1128             if ((illegal & INTERFACE) != 0) {
  1129                 log.error(pos, "intf.not.allowed.here");
  1130                 mask |= INTERFACE;
  1132             else {
  1133                 log.error(pos,
  1134                           "mod.not.allowed.here", asFlagSet(illegal));
  1137         else if ((sym.kind == TYP ||
  1138                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1139                   // in the presence of inner classes. Should it be deleted here?
  1140                   checkDisjoint(pos, flags,
  1141                                 ABSTRACT,
  1142                                 PRIVATE | STATIC | DEFAULT))
  1143                  &&
  1144                  checkDisjoint(pos, flags,
  1145                                 STATIC,
  1146                                 DEFAULT)
  1147                  &&
  1148                  checkDisjoint(pos, flags,
  1149                                ABSTRACT | INTERFACE,
  1150                                FINAL | NATIVE | SYNCHRONIZED)
  1151                  &&
  1152                  checkDisjoint(pos, flags,
  1153                                PUBLIC,
  1154                                PRIVATE | PROTECTED)
  1155                  &&
  1156                  checkDisjoint(pos, flags,
  1157                                PRIVATE,
  1158                                PUBLIC | PROTECTED)
  1159                  &&
  1160                  checkDisjoint(pos, flags,
  1161                                FINAL,
  1162                                VOLATILE)
  1163                  &&
  1164                  (sym.kind == TYP ||
  1165                   checkDisjoint(pos, flags,
  1166                                 ABSTRACT | NATIVE,
  1167                                 STRICTFP))) {
  1168             // skip
  1170         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1174     /** Determine if this enum should be implicitly final.
  1176      *  If the enum has no specialized enum contants, it is final.
  1178      *  If the enum does have specialized enum contants, it is
  1179      *  <i>not</i> final.
  1180      */
  1181     private long implicitEnumFinalFlag(JCTree tree) {
  1182         if (!tree.hasTag(CLASSDEF)) return 0;
  1183         class SpecialTreeVisitor extends JCTree.Visitor {
  1184             boolean specialized;
  1185             SpecialTreeVisitor() {
  1186                 this.specialized = false;
  1187             };
  1189             @Override
  1190             public void visitTree(JCTree tree) { /* no-op */ }
  1192             @Override
  1193             public void visitVarDef(JCVariableDecl tree) {
  1194                 if ((tree.mods.flags & ENUM) != 0) {
  1195                     if (tree.init instanceof JCNewClass &&
  1196                         ((JCNewClass) tree.init).def != null) {
  1197                         specialized = true;
  1203         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1204         JCClassDecl cdef = (JCClassDecl) tree;
  1205         for (JCTree defs: cdef.defs) {
  1206             defs.accept(sts);
  1207             if (sts.specialized) return 0;
  1209         return FINAL;
  1212 /* *************************************************************************
  1213  * Type Validation
  1214  **************************************************************************/
  1216     /** Validate a type expression. That is,
  1217      *  check that all type arguments of a parametric type are within
  1218      *  their bounds. This must be done in a second phase after type attribution
  1219      *  since a class might have a subclass as type parameter bound. E.g:
  1221      *  <pre>{@code
  1222      *  class B<A extends C> { ... }
  1223      *  class C extends B<C> { ... }
  1224      *  }</pre>
  1226      *  and we can't make sure that the bound is already attributed because
  1227      *  of possible cycles.
  1229      * Visitor method: Validate a type expression, if it is not null, catching
  1230      *  and reporting any completion failures.
  1231      */
  1232     void validate(JCTree tree, Env<AttrContext> env) {
  1233         validate(tree, env, true);
  1235     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1236         new Validator(env).validateTree(tree, checkRaw, true);
  1239     /** Visitor method: Validate a list of type expressions.
  1240      */
  1241     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1242         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1243             validate(l.head, env);
  1246     /** A visitor class for type validation.
  1247      */
  1248     class Validator extends JCTree.Visitor {
  1250         boolean isOuter;
  1251         Env<AttrContext> env;
  1253         Validator(Env<AttrContext> env) {
  1254             this.env = env;
  1257         @Override
  1258         public void visitTypeArray(JCArrayTypeTree tree) {
  1259             tree.elemtype.accept(this);
  1262         @Override
  1263         public void visitTypeApply(JCTypeApply tree) {
  1264             if (tree.type.hasTag(CLASS)) {
  1265                 List<JCExpression> args = tree.arguments;
  1266                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1268                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1269                 if (incompatibleArg != null) {
  1270                     for (JCTree arg : tree.arguments) {
  1271                         if (arg.type == incompatibleArg) {
  1272                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1274                         forms = forms.tail;
  1278                 forms = tree.type.tsym.type.getTypeArguments();
  1280                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1282                 // For matching pairs of actual argument types `a' and
  1283                 // formal type parameters with declared bound `b' ...
  1284                 while (args.nonEmpty() && forms.nonEmpty()) {
  1285                     validateTree(args.head,
  1286                             !(isOuter && is_java_lang_Class),
  1287                             false);
  1288                     args = args.tail;
  1289                     forms = forms.tail;
  1292                 // Check that this type is either fully parameterized, or
  1293                 // not parameterized at all.
  1294                 if (tree.type.getEnclosingType().isRaw())
  1295                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1296                 if (tree.clazz.hasTag(SELECT))
  1297                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1301         @Override
  1302         public void visitTypeParameter(JCTypeParameter tree) {
  1303             validateTrees(tree.bounds, true, isOuter);
  1304             checkClassBounds(tree.pos(), tree.type);
  1307         @Override
  1308         public void visitWildcard(JCWildcard tree) {
  1309             if (tree.inner != null)
  1310                 validateTree(tree.inner, true, isOuter);
  1313         @Override
  1314         public void visitSelect(JCFieldAccess tree) {
  1315             if (tree.type.hasTag(CLASS)) {
  1316                 visitSelectInternal(tree);
  1318                 // Check that this type is either fully parameterized, or
  1319                 // not parameterized at all.
  1320                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1321                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1325         public void visitSelectInternal(JCFieldAccess tree) {
  1326             if (tree.type.tsym.isStatic() &&
  1327                 tree.selected.type.isParameterized()) {
  1328                 // The enclosing type is not a class, so we are
  1329                 // looking at a static member type.  However, the
  1330                 // qualifying expression is parameterized.
  1331                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1332             } else {
  1333                 // otherwise validate the rest of the expression
  1334                 tree.selected.accept(this);
  1338         @Override
  1339         public void visitAnnotatedType(JCAnnotatedType tree) {
  1340             tree.underlyingType.accept(this);
  1343         /** Default visitor method: do nothing.
  1344          */
  1345         @Override
  1346         public void visitTree(JCTree tree) {
  1349         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1350             try {
  1351                 if (tree != null) {
  1352                     this.isOuter = isOuter;
  1353                     tree.accept(this);
  1354                     if (checkRaw)
  1355                         checkRaw(tree, env);
  1357             } catch (CompletionFailure ex) {
  1358                 completionError(tree.pos(), ex);
  1362         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1363             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1364                 validateTree(l.head, checkRaw, isOuter);
  1368     void checkRaw(JCTree tree, Env<AttrContext> env) {
  1369         if (lint.isEnabled(LintCategory.RAW) &&
  1370             tree.type.hasTag(CLASS) &&
  1371             !TreeInfo.isDiamond(tree) &&
  1372             !withinAnonConstr(env) &&
  1373             tree.type.isRaw()) {
  1374             log.warning(LintCategory.RAW,
  1375                     tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1378     //where
  1379         private boolean withinAnonConstr(Env<AttrContext> env) {
  1380             return env.enclClass.name.isEmpty() &&
  1381                     env.enclMethod != null && env.enclMethod.name == names.init;
  1384 /* *************************************************************************
  1385  * Exception checking
  1386  **************************************************************************/
  1388     /* The following methods treat classes as sets that contain
  1389      * the class itself and all their subclasses
  1390      */
  1392     /** Is given type a subtype of some of the types in given list?
  1393      */
  1394     boolean subset(Type t, List<Type> ts) {
  1395         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1396             if (types.isSubtype(t, l.head)) return true;
  1397         return false;
  1400     /** Is given type a subtype or supertype of
  1401      *  some of the types in given list?
  1402      */
  1403     boolean intersects(Type t, List<Type> ts) {
  1404         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1405             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1406         return false;
  1409     /** Add type set to given type list, unless it is a subclass of some class
  1410      *  in the list.
  1411      */
  1412     List<Type> incl(Type t, List<Type> ts) {
  1413         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1416     /** Remove type set from type set list.
  1417      */
  1418     List<Type> excl(Type t, List<Type> ts) {
  1419         if (ts.isEmpty()) {
  1420             return ts;
  1421         } else {
  1422             List<Type> ts1 = excl(t, ts.tail);
  1423             if (types.isSubtype(ts.head, t)) return ts1;
  1424             else if (ts1 == ts.tail) return ts;
  1425             else return ts1.prepend(ts.head);
  1429     /** Form the union of two type set lists.
  1430      */
  1431     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1432         List<Type> ts = ts1;
  1433         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1434             ts = incl(l.head, ts);
  1435         return ts;
  1438     /** Form the difference of two type lists.
  1439      */
  1440     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1441         List<Type> ts = ts1;
  1442         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1443             ts = excl(l.head, ts);
  1444         return ts;
  1447     /** Form the intersection of two type lists.
  1448      */
  1449     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1450         List<Type> ts = List.nil();
  1451         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1452             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1453         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1454             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1455         return ts;
  1458     /** Is exc an exception symbol that need not be declared?
  1459      */
  1460     boolean isUnchecked(ClassSymbol exc) {
  1461         return
  1462             exc.kind == ERR ||
  1463             exc.isSubClass(syms.errorType.tsym, types) ||
  1464             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1467     /** Is exc an exception type that need not be declared?
  1468      */
  1469     boolean isUnchecked(Type exc) {
  1470         return
  1471             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1472             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1473             exc.hasTag(BOT);
  1476     /** Same, but handling completion failures.
  1477      */
  1478     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1479         try {
  1480             return isUnchecked(exc);
  1481         } catch (CompletionFailure ex) {
  1482             completionError(pos, ex);
  1483             return true;
  1487     /** Is exc handled by given exception list?
  1488      */
  1489     boolean isHandled(Type exc, List<Type> handled) {
  1490         return isUnchecked(exc) || subset(exc, handled);
  1493     /** Return all exceptions in thrown list that are not in handled list.
  1494      *  @param thrown     The list of thrown exceptions.
  1495      *  @param handled    The list of handled exceptions.
  1496      */
  1497     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1498         List<Type> unhandled = List.nil();
  1499         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1500             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1501         return unhandled;
  1504 /* *************************************************************************
  1505  * Overriding/Implementation checking
  1506  **************************************************************************/
  1508     /** The level of access protection given by a flag set,
  1509      *  where PRIVATE is highest and PUBLIC is lowest.
  1510      */
  1511     static int protection(long flags) {
  1512         switch ((short)(flags & AccessFlags)) {
  1513         case PRIVATE: return 3;
  1514         case PROTECTED: return 1;
  1515         default:
  1516         case PUBLIC: return 0;
  1517         case 0: return 2;
  1521     /** A customized "cannot override" error message.
  1522      *  @param m      The overriding method.
  1523      *  @param other  The overridden method.
  1524      *  @return       An internationalized string.
  1525      */
  1526     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1527         String key;
  1528         if ((other.owner.flags() & INTERFACE) == 0)
  1529             key = "cant.override";
  1530         else if ((m.owner.flags() & INTERFACE) == 0)
  1531             key = "cant.implement";
  1532         else
  1533             key = "clashes.with";
  1534         return diags.fragment(key, m, m.location(), other, other.location());
  1537     /** A customized "override" warning message.
  1538      *  @param m      The overriding method.
  1539      *  @param other  The overridden method.
  1540      *  @return       An internationalized string.
  1541      */
  1542     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1543         String key;
  1544         if ((other.owner.flags() & INTERFACE) == 0)
  1545             key = "unchecked.override";
  1546         else if ((m.owner.flags() & INTERFACE) == 0)
  1547             key = "unchecked.implement";
  1548         else
  1549             key = "unchecked.clash.with";
  1550         return diags.fragment(key, m, m.location(), other, other.location());
  1553     /** A customized "override" warning message.
  1554      *  @param m      The overriding method.
  1555      *  @param other  The overridden method.
  1556      *  @return       An internationalized string.
  1557      */
  1558     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1559         String key;
  1560         if ((other.owner.flags() & INTERFACE) == 0)
  1561             key = "varargs.override";
  1562         else  if ((m.owner.flags() & INTERFACE) == 0)
  1563             key = "varargs.implement";
  1564         else
  1565             key = "varargs.clash.with";
  1566         return diags.fragment(key, m, m.location(), other, other.location());
  1569     /** Check that this method conforms with overridden method 'other'.
  1570      *  where `origin' is the class where checking started.
  1571      *  Complications:
  1572      *  (1) Do not check overriding of synthetic methods
  1573      *      (reason: they might be final).
  1574      *      todo: check whether this is still necessary.
  1575      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1576      *      than the method it implements. Augment the proxy methods with the
  1577      *      undeclared exceptions in this case.
  1578      *  (3) When generics are enabled, admit the case where an interface proxy
  1579      *      has a result type
  1580      *      extended by the result type of the method it implements.
  1581      *      Change the proxies result type to the smaller type in this case.
  1583      *  @param tree         The tree from which positions
  1584      *                      are extracted for errors.
  1585      *  @param m            The overriding method.
  1586      *  @param other        The overridden method.
  1587      *  @param origin       The class of which the overriding method
  1588      *                      is a member.
  1589      */
  1590     void checkOverride(JCTree tree,
  1591                        MethodSymbol m,
  1592                        MethodSymbol other,
  1593                        ClassSymbol origin) {
  1594         // Don't check overriding of synthetic methods or by bridge methods.
  1595         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1596             return;
  1599         // Error if static method overrides instance method (JLS 8.4.6.2).
  1600         if ((m.flags() & STATIC) != 0 &&
  1601                    (other.flags() & STATIC) == 0) {
  1602             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1603                       cannotOverride(m, other));
  1604             m.flags_field |= BAD_OVERRIDE;
  1605             return;
  1608         // Error if instance method overrides static or final
  1609         // method (JLS 8.4.6.1).
  1610         if ((other.flags() & FINAL) != 0 ||
  1611                  (m.flags() & STATIC) == 0 &&
  1612                  (other.flags() & STATIC) != 0) {
  1613             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1614                       cannotOverride(m, other),
  1615                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1616             m.flags_field |= BAD_OVERRIDE;
  1617             return;
  1620         if ((m.owner.flags() & ANNOTATION) != 0) {
  1621             // handled in validateAnnotationMethod
  1622             return;
  1625         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1626         if ((origin.flags() & INTERFACE) == 0 &&
  1627                  protection(m.flags()) > protection(other.flags())) {
  1628             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1629                       cannotOverride(m, other),
  1630                       other.flags() == 0 ?
  1631                           "package" :
  1632                           asFlagSet(other.flags() & AccessFlags));
  1633             m.flags_field |= BAD_OVERRIDE;
  1634             return;
  1637         Type mt = types.memberType(origin.type, m);
  1638         Type ot = types.memberType(origin.type, other);
  1639         // Error if overriding result type is different
  1640         // (or, in the case of generics mode, not a subtype) of
  1641         // overridden result type. We have to rename any type parameters
  1642         // before comparing types.
  1643         List<Type> mtvars = mt.getTypeArguments();
  1644         List<Type> otvars = ot.getTypeArguments();
  1645         Type mtres = mt.getReturnType();
  1646         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1648         overrideWarner.clear();
  1649         boolean resultTypesOK =
  1650             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1651         if (!resultTypesOK) {
  1652             if (!allowCovariantReturns &&
  1653                 m.owner != origin &&
  1654                 m.owner.isSubClass(other.owner, types)) {
  1655                 // allow limited interoperability with covariant returns
  1656             } else {
  1657                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1658                           "override.incompatible.ret",
  1659                           cannotOverride(m, other),
  1660                           mtres, otres);
  1661                 m.flags_field |= BAD_OVERRIDE;
  1662                 return;
  1664         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1665             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1666                     "override.unchecked.ret",
  1667                     uncheckedOverrides(m, other),
  1668                     mtres, otres);
  1671         // Error if overriding method throws an exception not reported
  1672         // by overridden method.
  1673         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1674         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1675         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1676         if (unhandledErased.nonEmpty()) {
  1677             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1678                       "override.meth.doesnt.throw",
  1679                       cannotOverride(m, other),
  1680                       unhandledUnerased.head);
  1681             m.flags_field |= BAD_OVERRIDE;
  1682             return;
  1684         else if (unhandledUnerased.nonEmpty()) {
  1685             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1686                           "override.unchecked.thrown",
  1687                          cannotOverride(m, other),
  1688                          unhandledUnerased.head);
  1689             return;
  1692         // Optional warning if varargs don't agree
  1693         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1694             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1695             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1696                         ((m.flags() & Flags.VARARGS) != 0)
  1697                         ? "override.varargs.missing"
  1698                         : "override.varargs.extra",
  1699                         varargsOverrides(m, other));
  1702         // Warn if instance method overrides bridge method (compiler spec ??)
  1703         if ((other.flags() & BRIDGE) != 0) {
  1704             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1705                         uncheckedOverrides(m, other));
  1708         // Warn if a deprecated method overridden by a non-deprecated one.
  1709         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1710             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1713     // where
  1714         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1715             // If the method, m, is defined in an interface, then ignore the issue if the method
  1716             // is only inherited via a supertype and also implemented in the supertype,
  1717             // because in that case, we will rediscover the issue when examining the method
  1718             // in the supertype.
  1719             // If the method, m, is not defined in an interface, then the only time we need to
  1720             // address the issue is when the method is the supertype implemementation: any other
  1721             // case, we will have dealt with when examining the supertype classes
  1722             ClassSymbol mc = m.enclClass();
  1723             Type st = types.supertype(origin.type);
  1724             if (!st.hasTag(CLASS))
  1725                 return true;
  1726             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1728             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1729                 List<Type> intfs = types.interfaces(origin.type);
  1730                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1732             else
  1733                 return (stimpl != m);
  1737     // used to check if there were any unchecked conversions
  1738     Warner overrideWarner = new Warner();
  1740     /** Check that a class does not inherit two concrete methods
  1741      *  with the same signature.
  1742      *  @param pos          Position to be used for error reporting.
  1743      *  @param site         The class type to be checked.
  1744      */
  1745     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1746         Type sup = types.supertype(site);
  1747         if (!sup.hasTag(CLASS)) return;
  1749         for (Type t1 = sup;
  1750              t1.tsym.type.isParameterized();
  1751              t1 = types.supertype(t1)) {
  1752             for (Scope.Entry e1 = t1.tsym.members().elems;
  1753                  e1 != null;
  1754                  e1 = e1.sibling) {
  1755                 Symbol s1 = e1.sym;
  1756                 if (s1.kind != MTH ||
  1757                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1758                     !s1.isInheritedIn(site.tsym, types) ||
  1759                     ((MethodSymbol)s1).implementation(site.tsym,
  1760                                                       types,
  1761                                                       true) != s1)
  1762                     continue;
  1763                 Type st1 = types.memberType(t1, s1);
  1764                 int s1ArgsLength = st1.getParameterTypes().length();
  1765                 if (st1 == s1.type) continue;
  1767                 for (Type t2 = sup;
  1768                      t2.hasTag(CLASS);
  1769                      t2 = types.supertype(t2)) {
  1770                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1771                          e2.scope != null;
  1772                          e2 = e2.next()) {
  1773                         Symbol s2 = e2.sym;
  1774                         if (s2 == s1 ||
  1775                             s2.kind != MTH ||
  1776                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1777                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1778                             !s2.isInheritedIn(site.tsym, types) ||
  1779                             ((MethodSymbol)s2).implementation(site.tsym,
  1780                                                               types,
  1781                                                               true) != s2)
  1782                             continue;
  1783                         Type st2 = types.memberType(t2, s2);
  1784                         if (types.overrideEquivalent(st1, st2))
  1785                             log.error(pos, "concrete.inheritance.conflict",
  1786                                       s1, t1, s2, t2, sup);
  1793     /** Check that classes (or interfaces) do not each define an abstract
  1794      *  method with same name and arguments but incompatible return types.
  1795      *  @param pos          Position to be used for error reporting.
  1796      *  @param t1           The first argument type.
  1797      *  @param t2           The second argument type.
  1798      */
  1799     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1800                                             Type t1,
  1801                                             Type t2) {
  1802         return checkCompatibleAbstracts(pos, t1, t2,
  1803                                         types.makeCompoundType(t1, t2));
  1806     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1807                                             Type t1,
  1808                                             Type t2,
  1809                                             Type site) {
  1810         return firstIncompatibility(pos, t1, t2, site) == null;
  1813     /** Return the first method which is defined with same args
  1814      *  but different return types in two given interfaces, or null if none
  1815      *  exists.
  1816      *  @param t1     The first type.
  1817      *  @param t2     The second type.
  1818      *  @param site   The most derived type.
  1819      *  @returns symbol from t2 that conflicts with one in t1.
  1820      */
  1821     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1822         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1823         closure(t1, interfaces1);
  1824         Map<TypeSymbol,Type> interfaces2;
  1825         if (t1 == t2)
  1826             interfaces2 = interfaces1;
  1827         else
  1828             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1830         for (Type t3 : interfaces1.values()) {
  1831             for (Type t4 : interfaces2.values()) {
  1832                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1833                 if (s != null) return s;
  1836         return null;
  1839     /** Compute all the supertypes of t, indexed by type symbol. */
  1840     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1841         if (!t.hasTag(CLASS)) return;
  1842         if (typeMap.put(t.tsym, t) == null) {
  1843             closure(types.supertype(t), typeMap);
  1844             for (Type i : types.interfaces(t))
  1845                 closure(i, typeMap);
  1849     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1850     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1851         if (!t.hasTag(CLASS)) return;
  1852         if (typesSkip.get(t.tsym) != null) return;
  1853         if (typeMap.put(t.tsym, t) == null) {
  1854             closure(types.supertype(t), typesSkip, typeMap);
  1855             for (Type i : types.interfaces(t))
  1856                 closure(i, typesSkip, typeMap);
  1860     /** Return the first method in t2 that conflicts with a method from t1. */
  1861     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1862         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1863             Symbol s1 = e1.sym;
  1864             Type st1 = null;
  1865             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1866                     (s1.flags() & SYNTHETIC) != 0) continue;
  1867             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1868             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1869             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1870                 Symbol s2 = e2.sym;
  1871                 if (s1 == s2) continue;
  1872                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1873                         (s2.flags() & SYNTHETIC) != 0) continue;
  1874                 if (st1 == null) st1 = types.memberType(t1, s1);
  1875                 Type st2 = types.memberType(t2, s2);
  1876                 if (types.overrideEquivalent(st1, st2)) {
  1877                     List<Type> tvars1 = st1.getTypeArguments();
  1878                     List<Type> tvars2 = st2.getTypeArguments();
  1879                     Type rt1 = st1.getReturnType();
  1880                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1881                     boolean compat =
  1882                         types.isSameType(rt1, rt2) ||
  1883                         !rt1.isPrimitiveOrVoid() &&
  1884                         !rt2.isPrimitiveOrVoid() &&
  1885                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1886                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1887                          checkCommonOverriderIn(s1,s2,site);
  1888                     if (!compat) {
  1889                         log.error(pos, "types.incompatible.diff.ret",
  1890                             t1, t2, s2.name +
  1891                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1892                         return s2;
  1894                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1895                         !checkCommonOverriderIn(s1, s2, site)) {
  1896                     log.error(pos,
  1897                             "name.clash.same.erasure.no.override",
  1898                             s1, s1.location(),
  1899                             s2, s2.location());
  1900                     return s2;
  1904         return null;
  1906     //WHERE
  1907     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1908         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1909         Type st1 = types.memberType(site, s1);
  1910         Type st2 = types.memberType(site, s2);
  1911         closure(site, supertypes);
  1912         for (Type t : supertypes.values()) {
  1913             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1914                 Symbol s3 = e.sym;
  1915                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1916                 Type st3 = types.memberType(site,s3);
  1917                 if (types.overrideEquivalent(st3, st1) &&
  1918                         types.overrideEquivalent(st3, st2) &&
  1919                         types.returnTypeSubstitutable(st3, st1) &&
  1920                         types.returnTypeSubstitutable(st3, st2)) {
  1921                     return true;
  1925         return false;
  1928     /** Check that a given method conforms with any method it overrides.
  1929      *  @param tree         The tree from which positions are extracted
  1930      *                      for errors.
  1931      *  @param m            The overriding method.
  1932      */
  1933     void checkOverride(JCTree tree, MethodSymbol m) {
  1934         ClassSymbol origin = (ClassSymbol)m.owner;
  1935         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1936             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1937                 log.error(tree.pos(), "enum.no.finalize");
  1938                 return;
  1940         for (Type t = origin.type; t.hasTag(CLASS);
  1941              t = types.supertype(t)) {
  1942             if (t != origin.type) {
  1943                 checkOverride(tree, t, origin, m);
  1945             for (Type t2 : types.interfaces(t)) {
  1946                 checkOverride(tree, t2, origin, m);
  1951     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1952         TypeSymbol c = site.tsym;
  1953         Scope.Entry e = c.members().lookup(m.name);
  1954         while (e.scope != null) {
  1955             if (m.overrides(e.sym, origin, types, false)) {
  1956                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1957                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1960             e = e.next();
  1964     private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
  1965         public boolean accepts(Symbol s) {
  1966             return MethodSymbol.implementation_filter.accepts(s) &&
  1967                     (s.flags() & BAD_OVERRIDE) == 0;
  1970     };
  1972     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
  1973             ClassSymbol someClass) {
  1974         /* At present, annotations cannot possibly have a method that is override
  1975          * equivalent with Object.equals(Object) but in any case the condition is
  1976          * fine for completeness.
  1977          */
  1978         if (someClass == (ClassSymbol)syms.objectType.tsym ||
  1979             someClass.isInterface() || someClass.isEnum() ||
  1980             (someClass.flags() & ANNOTATION) != 0 ||
  1981             (someClass.flags() & ABSTRACT) != 0) return;
  1982         //anonymous inner classes implementing interfaces need especial treatment
  1983         if (someClass.isAnonymous()) {
  1984             List<Type> interfaces =  types.interfaces(someClass.type);
  1985             if (interfaces != null && !interfaces.isEmpty() &&
  1986                 interfaces.head.tsym == syms.comparatorType.tsym) return;
  1988         checkClassOverrideEqualsAndHash(pos, someClass);
  1991     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
  1992             ClassSymbol someClass) {
  1993         if (lint.isEnabled(LintCategory.OVERRIDES)) {
  1994             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
  1995                     .tsym.members().lookup(names.equals).sym;
  1996             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
  1997                     .tsym.members().lookup(names.hashCode).sym;
  1998             boolean overridesEquals = types.implementation(equalsAtObject,
  1999                 someClass, false, equalsHasCodeFilter).owner == someClass;
  2000             boolean overridesHashCode = types.implementation(hashCodeAtObject,
  2001                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
  2003             if (overridesEquals && !overridesHashCode) {
  2004                 log.warning(LintCategory.OVERRIDES, pos,
  2005                         "override.equals.but.not.hashcode", someClass);
  2010     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  2011         ClashFilter cf = new ClashFilter(origin.type);
  2012         return (cf.accepts(s1) &&
  2013                 cf.accepts(s2) &&
  2014                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  2018     /** Check that all abstract members of given class have definitions.
  2019      *  @param pos          Position to be used for error reporting.
  2020      *  @param c            The class.
  2021      */
  2022     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  2023         try {
  2024             MethodSymbol undef = firstUndef(c, c);
  2025             if (undef != null) {
  2026                 if ((c.flags() & ENUM) != 0 &&
  2027                     types.supertype(c.type).tsym == syms.enumSym &&
  2028                     (c.flags() & FINAL) == 0) {
  2029                     // add the ABSTRACT flag to an enum
  2030                     c.flags_field |= ABSTRACT;
  2031                 } else {
  2032                     MethodSymbol undef1 =
  2033                         new MethodSymbol(undef.flags(), undef.name,
  2034                                          types.memberType(c.type, undef), undef.owner);
  2035                     log.error(pos, "does.not.override.abstract",
  2036                               c, undef1, undef1.location());
  2039         } catch (CompletionFailure ex) {
  2040             completionError(pos, ex);
  2043 //where
  2044         /** Return first abstract member of class `c' that is not defined
  2045          *  in `impl', null if there is none.
  2046          */
  2047         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  2048             MethodSymbol undef = null;
  2049             // Do not bother to search in classes that are not abstract,
  2050             // since they cannot have abstract members.
  2051             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2052                 Scope s = c.members();
  2053                 for (Scope.Entry e = s.elems;
  2054                      undef == null && e != null;
  2055                      e = e.sibling) {
  2056                     if (e.sym.kind == MTH &&
  2057                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2058                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2059                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2060                         if (implmeth == null || implmeth == absmeth) {
  2061                             //look for default implementations
  2062                             if (allowDefaultMethods) {
  2063                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2064                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2065                                     implmeth = prov;
  2069                         if (implmeth == null || implmeth == absmeth) {
  2070                             undef = absmeth;
  2074                 if (undef == null) {
  2075                     Type st = types.supertype(c.type);
  2076                     if (st.hasTag(CLASS))
  2077                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2079                 for (List<Type> l = types.interfaces(c.type);
  2080                      undef == null && l.nonEmpty();
  2081                      l = l.tail) {
  2082                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2085             return undef;
  2088     void checkNonCyclicDecl(JCClassDecl tree) {
  2089         CycleChecker cc = new CycleChecker();
  2090         cc.scan(tree);
  2091         if (!cc.errorFound && !cc.partialCheck) {
  2092             tree.sym.flags_field |= ACYCLIC;
  2096     class CycleChecker extends TreeScanner {
  2098         List<Symbol> seenClasses = List.nil();
  2099         boolean errorFound = false;
  2100         boolean partialCheck = false;
  2102         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2103             if (sym != null && sym.kind == TYP) {
  2104                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2105                 if (classEnv != null) {
  2106                     DiagnosticSource prevSource = log.currentSource();
  2107                     try {
  2108                         log.useSource(classEnv.toplevel.sourcefile);
  2109                         scan(classEnv.tree);
  2111                     finally {
  2112                         log.useSource(prevSource.getFile());
  2114                 } else if (sym.kind == TYP) {
  2115                     checkClass(pos, sym, List.<JCTree>nil());
  2117             } else {
  2118                 //not completed yet
  2119                 partialCheck = true;
  2123         @Override
  2124         public void visitSelect(JCFieldAccess tree) {
  2125             super.visitSelect(tree);
  2126             checkSymbol(tree.pos(), tree.sym);
  2129         @Override
  2130         public void visitIdent(JCIdent tree) {
  2131             checkSymbol(tree.pos(), tree.sym);
  2134         @Override
  2135         public void visitTypeApply(JCTypeApply tree) {
  2136             scan(tree.clazz);
  2139         @Override
  2140         public void visitTypeArray(JCArrayTypeTree tree) {
  2141             scan(tree.elemtype);
  2144         @Override
  2145         public void visitClassDef(JCClassDecl tree) {
  2146             List<JCTree> supertypes = List.nil();
  2147             if (tree.getExtendsClause() != null) {
  2148                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2150             if (tree.getImplementsClause() != null) {
  2151                 for (JCTree intf : tree.getImplementsClause()) {
  2152                     supertypes = supertypes.prepend(intf);
  2155             checkClass(tree.pos(), tree.sym, supertypes);
  2158         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2159             if ((c.flags_field & ACYCLIC) != 0)
  2160                 return;
  2161             if (seenClasses.contains(c)) {
  2162                 errorFound = true;
  2163                 noteCyclic(pos, (ClassSymbol)c);
  2164             } else if (!c.type.isErroneous()) {
  2165                 try {
  2166                     seenClasses = seenClasses.prepend(c);
  2167                     if (c.type.hasTag(CLASS)) {
  2168                         if (supertypes.nonEmpty()) {
  2169                             scan(supertypes);
  2171                         else {
  2172                             ClassType ct = (ClassType)c.type;
  2173                             if (ct.supertype_field == null ||
  2174                                     ct.interfaces_field == null) {
  2175                                 //not completed yet
  2176                                 partialCheck = true;
  2177                                 return;
  2179                             checkSymbol(pos, ct.supertype_field.tsym);
  2180                             for (Type intf : ct.interfaces_field) {
  2181                                 checkSymbol(pos, intf.tsym);
  2184                         if (c.owner.kind == TYP) {
  2185                             checkSymbol(pos, c.owner);
  2188                 } finally {
  2189                     seenClasses = seenClasses.tail;
  2195     /** Check for cyclic references. Issue an error if the
  2196      *  symbol of the type referred to has a LOCKED flag set.
  2198      *  @param pos      Position to be used for error reporting.
  2199      *  @param t        The type referred to.
  2200      */
  2201     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2202         checkNonCyclicInternal(pos, t);
  2206     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2207         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2210     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2211         final TypeVar tv;
  2212         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2213             return;
  2214         if (seen.contains(t)) {
  2215             tv = (TypeVar)t;
  2216             tv.bound = types.createErrorType(t);
  2217             log.error(pos, "cyclic.inheritance", t);
  2218         } else if (t.hasTag(TYPEVAR)) {
  2219             tv = (TypeVar)t;
  2220             seen = seen.prepend(tv);
  2221             for (Type b : types.getBounds(tv))
  2222                 checkNonCyclic1(pos, b, seen);
  2226     /** Check for cyclic references. Issue an error if the
  2227      *  symbol of the type referred to has a LOCKED flag set.
  2229      *  @param pos      Position to be used for error reporting.
  2230      *  @param t        The type referred to.
  2231      *  @returns        True if the check completed on all attributed classes
  2232      */
  2233     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2234         boolean complete = true; // was the check complete?
  2235         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2236         Symbol c = t.tsym;
  2237         if ((c.flags_field & ACYCLIC) != 0) return true;
  2239         if ((c.flags_field & LOCKED) != 0) {
  2240             noteCyclic(pos, (ClassSymbol)c);
  2241         } else if (!c.type.isErroneous()) {
  2242             try {
  2243                 c.flags_field |= LOCKED;
  2244                 if (c.type.hasTag(CLASS)) {
  2245                     ClassType clazz = (ClassType)c.type;
  2246                     if (clazz.interfaces_field != null)
  2247                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2248                             complete &= checkNonCyclicInternal(pos, l.head);
  2249                     if (clazz.supertype_field != null) {
  2250                         Type st = clazz.supertype_field;
  2251                         if (st != null && st.hasTag(CLASS))
  2252                             complete &= checkNonCyclicInternal(pos, st);
  2254                     if (c.owner.kind == TYP)
  2255                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2257             } finally {
  2258                 c.flags_field &= ~LOCKED;
  2261         if (complete)
  2262             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2263         if (complete) c.flags_field |= ACYCLIC;
  2264         return complete;
  2267     /** Note that we found an inheritance cycle. */
  2268     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2269         log.error(pos, "cyclic.inheritance", c);
  2270         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2271             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2272         Type st = types.supertype(c.type);
  2273         if (st.hasTag(CLASS))
  2274             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2275         c.type = types.createErrorType(c, c.type);
  2276         c.flags_field |= ACYCLIC;
  2279     /**
  2280      * Check that functional interface methods would make sense when seen
  2281      * from the perspective of the implementing class
  2282      */
  2283     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2284         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2285         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2286         c.interfaces_field = List.of(types.removeWildcards(funcInterface));
  2287         c.supertype_field = syms.objectType;
  2288         c.tsym = csym;
  2289         csym.members_field = new Scope(csym);
  2290         Symbol descSym = types.findDescriptorSymbol(funcInterface.tsym);
  2291         Type descType = types.findDescriptorType(funcInterface);
  2292         csym.members_field.enter(new MethodSymbol(PUBLIC, descSym.name, descType, csym));
  2293         csym.completer = null;
  2294         checkImplementations(tree, csym, csym);
  2297     /** Check that all methods which implement some
  2298      *  method conform to the method they implement.
  2299      *  @param tree         The class definition whose members are checked.
  2300      */
  2301     void checkImplementations(JCClassDecl tree) {
  2302         checkImplementations(tree, tree.sym, tree.sym);
  2304     //where
  2305         /** Check that all methods which implement some
  2306          *  method in `ic' conform to the method they implement.
  2307          */
  2308         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2309             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2310                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2311                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2312                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2313                         if (e.sym.kind == MTH &&
  2314                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2315                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2316                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2317                             if (implmeth != null && implmeth != absmeth &&
  2318                                 (implmeth.owner.flags() & INTERFACE) ==
  2319                                 (origin.flags() & INTERFACE)) {
  2320                                 // don't check if implmeth is in a class, yet
  2321                                 // origin is an interface. This case arises only
  2322                                 // if implmeth is declared in Object. The reason is
  2323                                 // that interfaces really don't inherit from
  2324                                 // Object it's just that the compiler represents
  2325                                 // things that way.
  2326                                 checkOverride(tree, implmeth, absmeth, origin);
  2334     /** Check that all abstract methods implemented by a class are
  2335      *  mutually compatible.
  2336      *  @param pos          Position to be used for error reporting.
  2337      *  @param c            The class whose interfaces are checked.
  2338      */
  2339     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2340         List<Type> supertypes = types.interfaces(c);
  2341         Type supertype = types.supertype(c);
  2342         if (supertype.hasTag(CLASS) &&
  2343             (supertype.tsym.flags() & ABSTRACT) != 0)
  2344             supertypes = supertypes.prepend(supertype);
  2345         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2346             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2347                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2348                 return;
  2349             for (List<Type> m = supertypes; m != l; m = m.tail)
  2350                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2351                     return;
  2353         checkCompatibleConcretes(pos, c);
  2356     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2357         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2358             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2359                 // VM allows methods and variables with differing types
  2360                 if (sym.kind == e.sym.kind &&
  2361                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2362                     sym != e.sym &&
  2363                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2364                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2365                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2366                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2367                     return;
  2373     /** Check that all non-override equivalent methods accessible from 'site'
  2374      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2376      *  @param pos  Position to be used for error reporting.
  2377      *  @param site The class whose methods are checked.
  2378      *  @param sym  The method symbol to be checked.
  2379      */
  2380     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2381          ClashFilter cf = new ClashFilter(site);
  2382         //for each method m1 that is overridden (directly or indirectly)
  2383         //by method 'sym' in 'site'...
  2384         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2385             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2386              //...check each method m2 that is a member of 'site'
  2387              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2388                 if (m2 == m1) continue;
  2389                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2390                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2391                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2392                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2393                     sym.flags_field |= CLASH;
  2394                     String key = m1 == sym ?
  2395                             "name.clash.same.erasure.no.override" :
  2396                             "name.clash.same.erasure.no.override.1";
  2397                     log.error(pos,
  2398                             key,
  2399                             sym, sym.location(),
  2400                             m2, m2.location(),
  2401                             m1, m1.location());
  2402                     return;
  2410     /** Check that all static methods accessible from 'site' are
  2411      *  mutually compatible (JLS 8.4.8).
  2413      *  @param pos  Position to be used for error reporting.
  2414      *  @param site The class whose methods are checked.
  2415      *  @param sym  The method symbol to be checked.
  2416      */
  2417     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2418         ClashFilter cf = new ClashFilter(site);
  2419         //for each method m1 that is a member of 'site'...
  2420         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2421             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2422             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2423             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2424                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2425                 log.error(pos,
  2426                         "name.clash.same.erasure.no.hide",
  2427                         sym, sym.location(),
  2428                         s, s.location());
  2429                 return;
  2434      //where
  2435      private class ClashFilter implements Filter<Symbol> {
  2437          Type site;
  2439          ClashFilter(Type site) {
  2440              this.site = site;
  2443          boolean shouldSkip(Symbol s) {
  2444              return (s.flags() & CLASH) != 0 &&
  2445                 s.owner == site.tsym;
  2448          public boolean accepts(Symbol s) {
  2449              return s.kind == MTH &&
  2450                      (s.flags() & SYNTHETIC) == 0 &&
  2451                      !shouldSkip(s) &&
  2452                      s.isInheritedIn(site.tsym, types) &&
  2453                      !s.isConstructor();
  2457     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2458         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2459         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2460             Assert.check(m.kind == MTH);
  2461             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2462             if (prov.size() > 1) {
  2463                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2464                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2465                 for (MethodSymbol provSym : prov) {
  2466                     if ((provSym.flags() & DEFAULT) != 0) {
  2467                         defaults = defaults.append(provSym);
  2468                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2469                         abstracts = abstracts.append(provSym);
  2471                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2472                         //strong semantics - issue an error if two sibling interfaces
  2473                         //have two override-equivalent defaults - or if one is abstract
  2474                         //and the other is default
  2475                         String errKey;
  2476                         Symbol s1 = defaults.first();
  2477                         Symbol s2;
  2478                         if (defaults.size() > 1) {
  2479                             errKey = "types.incompatible.unrelated.defaults";
  2480                             s2 = defaults.toList().tail.head;
  2481                         } else {
  2482                             errKey = "types.incompatible.abstract.default";
  2483                             s2 = abstracts.first();
  2485                         log.error(pos, errKey,
  2486                                 Kinds.kindName(site.tsym), site,
  2487                                 m.name, types.memberType(site, m).getParameterTypes(),
  2488                                 s1.location(), s2.location());
  2489                         break;
  2496     //where
  2497      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2499          Type site;
  2501          DefaultMethodClashFilter(Type site) {
  2502              this.site = site;
  2505          public boolean accepts(Symbol s) {
  2506              return s.kind == MTH &&
  2507                      (s.flags() & DEFAULT) != 0 &&
  2508                      s.isInheritedIn(site.tsym, types) &&
  2509                      !s.isConstructor();
  2513     /** Report a conflict between a user symbol and a synthetic symbol.
  2514      */
  2515     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2516         if (!sym.type.isErroneous()) {
  2517             if (warnOnSyntheticConflicts) {
  2518                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2520             else {
  2521                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2526     /** Check that class c does not implement directly or indirectly
  2527      *  the same parameterized interface with two different argument lists.
  2528      *  @param pos          Position to be used for error reporting.
  2529      *  @param type         The type whose interfaces are checked.
  2530      */
  2531     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2532         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2534 //where
  2535         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2536          *  with their class symbol as key and their type as value. Make
  2537          *  sure no class is entered with two different types.
  2538          */
  2539         void checkClassBounds(DiagnosticPosition pos,
  2540                               Map<TypeSymbol,Type> seensofar,
  2541                               Type type) {
  2542             if (type.isErroneous()) return;
  2543             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2544                 Type it = l.head;
  2545                 Type oldit = seensofar.put(it.tsym, it);
  2546                 if (oldit != null) {
  2547                     List<Type> oldparams = oldit.allparams();
  2548                     List<Type> newparams = it.allparams();
  2549                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2550                         log.error(pos, "cant.inherit.diff.arg",
  2551                                   it.tsym, Type.toString(oldparams),
  2552                                   Type.toString(newparams));
  2554                 checkClassBounds(pos, seensofar, it);
  2556             Type st = types.supertype(type);
  2557             if (st != null) checkClassBounds(pos, seensofar, st);
  2560     /** Enter interface into into set.
  2561      *  If it existed already, issue a "repeated interface" error.
  2562      */
  2563     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2564         if (its.contains(it))
  2565             log.error(pos, "repeated.interface");
  2566         else {
  2567             its.add(it);
  2571 /* *************************************************************************
  2572  * Check annotations
  2573  **************************************************************************/
  2575     /**
  2576      * Recursively validate annotations values
  2577      */
  2578     void validateAnnotationTree(JCTree tree) {
  2579         class AnnotationValidator extends TreeScanner {
  2580             @Override
  2581             public void visitAnnotation(JCAnnotation tree) {
  2582                 if (!tree.type.isErroneous()) {
  2583                     super.visitAnnotation(tree);
  2584                     validateAnnotation(tree);
  2588         tree.accept(new AnnotationValidator());
  2591     /**
  2592      *  {@literal
  2593      *  Annotation types are restricted to primitives, String, an
  2594      *  enum, an annotation, Class, Class<?>, Class<? extends
  2595      *  Anything>, arrays of the preceding.
  2596      *  }
  2597      */
  2598     void validateAnnotationType(JCTree restype) {
  2599         // restype may be null if an error occurred, so don't bother validating it
  2600         if (restype != null) {
  2601             validateAnnotationType(restype.pos(), restype.type);
  2605     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2606         if (type.isPrimitive()) return;
  2607         if (types.isSameType(type, syms.stringType)) return;
  2608         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2609         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2610         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2611         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2612             validateAnnotationType(pos, types.elemtype(type));
  2613             return;
  2615         log.error(pos, "invalid.annotation.member.type");
  2618     /**
  2619      * "It is also a compile-time error if any method declared in an
  2620      * annotation type has a signature that is override-equivalent to
  2621      * that of any public or protected method declared in class Object
  2622      * or in the interface annotation.Annotation."
  2624      * @jls 9.6 Annotation Types
  2625      */
  2626     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2627         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2628             Scope s = sup.tsym.members();
  2629             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2630                 if (e.sym.kind == MTH &&
  2631                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2632                     types.overrideEquivalent(m.type, e.sym.type))
  2633                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2638     /** Check the annotations of a symbol.
  2639      */
  2640     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2641         for (JCAnnotation a : annotations)
  2642             validateAnnotation(a, s);
  2645     /** Check the type annotations.
  2646      */
  2647     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
  2648         for (JCAnnotation a : annotations)
  2649             validateTypeAnnotation(a, isTypeParameter);
  2652     /** Check an annotation of a symbol.
  2653      */
  2654     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2655         validateAnnotationTree(a);
  2657         if (!annotationApplicable(a, s))
  2658             log.error(a.pos(), "annotation.type.not.applicable");
  2660         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2661             if (!isOverrider(s))
  2662                 log.error(a.pos(), "method.does.not.override.superclass");
  2665         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2666             if (s.kind != TYP) {
  2667                 log.error(a.pos(), "bad.functional.intf.anno");
  2668             } else {
  2669                 try {
  2670                     types.findDescriptorSymbol((TypeSymbol)s);
  2671                 } catch (Types.FunctionDescriptorLookupError ex) {
  2672                     log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
  2678     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2679         Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
  2680         validateAnnotationTree(a);
  2682         if (!isTypeAnnotation(a, isTypeParameter))
  2683             log.error(a.pos(), "annotation.type.not.applicable");
  2686     /**
  2687      * Validate the proposed container 'repeatable' on the
  2688      * annotation type symbol 's'. Report errors at position
  2689      * 'pos'.
  2691      * @param s The (annotation)type declaration annotated with a @Repeatable
  2692      * @param repeatable the @Repeatable on 's'
  2693      * @param pos where to report errors
  2694      */
  2695     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2696         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2698         Type t = null;
  2699         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2700         if (!l.isEmpty()) {
  2701             Assert.check(l.head.fst.name == names.value);
  2702             t = ((Attribute.Class)l.head.snd).getValue();
  2705         if (t == null) {
  2706             // errors should already have been reported during Annotate
  2707             return;
  2710         validateValue(t.tsym, s, pos);
  2711         validateRetention(t.tsym, s, pos);
  2712         validateDocumented(t.tsym, s, pos);
  2713         validateInherited(t.tsym, s, pos);
  2714         validateTarget(t.tsym, s, pos);
  2715         validateDefault(t.tsym, s, pos);
  2718     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2719         Scope.Entry e = container.members().lookup(names.value);
  2720         if (e.scope != null && e.sym.kind == MTH) {
  2721             MethodSymbol m = (MethodSymbol) e.sym;
  2722             Type ret = m.getReturnType();
  2723             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2724                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2725                         container, ret, types.makeArrayType(contained.type));
  2727         } else {
  2728             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2732     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2733         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2734         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2736         boolean error = false;
  2737         switch (containedRetention) {
  2738         case RUNTIME:
  2739             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2740                 error = true;
  2742             break;
  2743         case CLASS:
  2744             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2745                 error = true;
  2748         if (error ) {
  2749             log.error(pos, "invalid.repeatable.annotation.retention",
  2750                       container, containerRetention,
  2751                       contained, containedRetention);
  2755     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2756         if (contained.attribute(syms.documentedType.tsym) != null) {
  2757             if (container.attribute(syms.documentedType.tsym) == null) {
  2758                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2763     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2764         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2765             if (container.attribute(syms.inheritedType.tsym) == null) {
  2766                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2771     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2772         // The set of targets the container is applicable to must be a subset
  2773         // (with respect to annotation target semantics) of the set of targets
  2774         // the contained is applicable to. The target sets may be implicit or
  2775         // explicit.
  2777         Set<Name> containerTargets;
  2778         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2779         if (containerTarget == null) {
  2780             containerTargets = getDefaultTargetSet();
  2781         } else {
  2782             containerTargets = new HashSet<Name>();
  2783         for (Attribute app : containerTarget.values) {
  2784             if (!(app instanceof Attribute.Enum)) {
  2785                 continue; // recovery
  2787             Attribute.Enum e = (Attribute.Enum)app;
  2788             containerTargets.add(e.value.name);
  2792         Set<Name> containedTargets;
  2793         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2794         if (containedTarget == null) {
  2795             containedTargets = getDefaultTargetSet();
  2796         } else {
  2797             containedTargets = new HashSet<Name>();
  2798         for (Attribute app : containedTarget.values) {
  2799             if (!(app instanceof Attribute.Enum)) {
  2800                 continue; // recovery
  2802             Attribute.Enum e = (Attribute.Enum)app;
  2803             containedTargets.add(e.value.name);
  2807         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
  2808             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2812     /* get a set of names for the default target */
  2813     private Set<Name> getDefaultTargetSet() {
  2814         if (defaultTargets == null) {
  2815             Set<Name> targets = new HashSet<Name>();
  2816             targets.add(names.ANNOTATION_TYPE);
  2817             targets.add(names.CONSTRUCTOR);
  2818             targets.add(names.FIELD);
  2819             targets.add(names.LOCAL_VARIABLE);
  2820             targets.add(names.METHOD);
  2821             targets.add(names.PACKAGE);
  2822             targets.add(names.PARAMETER);
  2823             targets.add(names.TYPE);
  2825             defaultTargets = java.util.Collections.unmodifiableSet(targets);
  2828         return defaultTargets;
  2830     private Set<Name> defaultTargets;
  2833     /** Checks that s is a subset of t, with respect to ElementType
  2834      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2835      */
  2836     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
  2837         // Check that all elements in s are present in t
  2838         for (Name n2 : s) {
  2839             boolean currentElementOk = false;
  2840             for (Name n1 : t) {
  2841                 if (n1 == n2) {
  2842                     currentElementOk = true;
  2843                     break;
  2844                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2845                     currentElementOk = true;
  2846                     break;
  2849             if (!currentElementOk)
  2850                 return false;
  2852         return true;
  2855     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2856         // validate that all other elements of containing type has defaults
  2857         Scope scope = container.members();
  2858         for(Symbol elm : scope.getElements()) {
  2859             if (elm.name != names.value &&
  2860                 elm.kind == Kinds.MTH &&
  2861                 ((MethodSymbol)elm).defaultValue == null) {
  2862                 log.error(pos,
  2863                           "invalid.repeatable.annotation.elem.nondefault",
  2864                           container,
  2865                           elm);
  2870     /** Is s a method symbol that overrides a method in a superclass? */
  2871     boolean isOverrider(Symbol s) {
  2872         if (s.kind != MTH || s.isStatic())
  2873             return false;
  2874         MethodSymbol m = (MethodSymbol)s;
  2875         TypeSymbol owner = (TypeSymbol)m.owner;
  2876         for (Type sup : types.closure(owner.type)) {
  2877             if (sup == owner.type)
  2878                 continue; // skip "this"
  2879             Scope scope = sup.tsym.members();
  2880             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2881                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2882                     return true;
  2885         return false;
  2888     /** Is the annotation applicable to type annotations? */
  2889     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2890         Attribute.Compound atTarget =
  2891             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2892         if (atTarget == null) {
  2893             // An annotation without @Target is not a type annotation.
  2894             return false;
  2897         Attribute atValue = atTarget.member(names.value);
  2898         if (!(atValue instanceof Attribute.Array)) {
  2899             return false; // error recovery
  2902         Attribute.Array arr = (Attribute.Array) atValue;
  2903         for (Attribute app : arr.values) {
  2904             if (!(app instanceof Attribute.Enum)) {
  2905                 return false; // recovery
  2907             Attribute.Enum e = (Attribute.Enum) app;
  2909             if (e.value.name == names.TYPE_USE)
  2910                 return true;
  2911             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  2912                 return true;
  2914         return false;
  2917     /** Is the annotation applicable to the symbol? */
  2918     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2919         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2920         Name[] targets;
  2922         if (arr == null) {
  2923             targets = defaultTargetMetaInfo(a, s);
  2924         } else {
  2925             // TODO: can we optimize this?
  2926             targets = new Name[arr.values.length];
  2927             for (int i=0; i<arr.values.length; ++i) {
  2928                 Attribute app = arr.values[i];
  2929                 if (!(app instanceof Attribute.Enum)) {
  2930                     return true; // recovery
  2932                 Attribute.Enum e = (Attribute.Enum) app;
  2933                 targets[i] = e.value.name;
  2936         for (Name target : targets) {
  2937             if (target == names.TYPE)
  2938                 { if (s.kind == TYP) return true; }
  2939             else if (target == names.FIELD)
  2940                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2941             else if (target == names.METHOD)
  2942                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2943             else if (target == names.PARAMETER)
  2944                 { if (s.kind == VAR &&
  2945                       s.owner.kind == MTH &&
  2946                       (s.flags() & PARAMETER) != 0)
  2947                     return true;
  2949             else if (target == names.CONSTRUCTOR)
  2950                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2951             else if (target == names.LOCAL_VARIABLE)
  2952                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2953                       (s.flags() & PARAMETER) == 0)
  2954                     return true;
  2956             else if (target == names.ANNOTATION_TYPE)
  2957                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2958                     return true;
  2960             else if (target == names.PACKAGE)
  2961                 { if (s.kind == PCK) return true; }
  2962             else if (target == names.TYPE_USE)
  2963                 { if (s.kind == TYP ||
  2964                       s.kind == VAR ||
  2965                       (s.kind == MTH && !s.isConstructor() &&
  2966                       !s.type.getReturnType().hasTag(VOID)) ||
  2967                       (s.kind == MTH && s.isConstructor()))
  2968                     return true;
  2970             else if (target == names.TYPE_PARAMETER)
  2971                 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
  2972                     return true;
  2974             else
  2975                 return true; // recovery
  2977         return false;
  2981     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2982         Attribute.Compound atTarget =
  2983             s.attribute(syms.annotationTargetType.tsym);
  2984         if (atTarget == null) return null; // ok, is applicable
  2985         Attribute atValue = atTarget.member(names.value);
  2986         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2987         return (Attribute.Array) atValue;
  2990     private final Name[] dfltTargetMeta;
  2991     private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
  2992         return dfltTargetMeta;
  2995     /** Check an annotation value.
  2997      * @param a The annotation tree to check
  2998      * @return true if this annotation tree is valid, otherwise false
  2999      */
  3000     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  3001         boolean res = false;
  3002         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  3003         try {
  3004             res = validateAnnotation(a);
  3005         } finally {
  3006             log.popDiagnosticHandler(diagHandler);
  3008         return res;
  3011     private boolean validateAnnotation(JCAnnotation a) {
  3012         boolean isValid = true;
  3013         // collect an inventory of the annotation elements
  3014         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  3015         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  3016                 e != null;
  3017                 e = e.sibling)
  3018             if (e.sym.kind == MTH && e.sym.name != names.clinit)
  3019                 members.add((MethodSymbol) e.sym);
  3021         // remove the ones that are assigned values
  3022         for (JCTree arg : a.args) {
  3023             if (!arg.hasTag(ASSIGN)) continue; // recovery
  3024             JCAssign assign = (JCAssign) arg;
  3025             Symbol m = TreeInfo.symbol(assign.lhs);
  3026             if (m == null || m.type.isErroneous()) continue;
  3027             if (!members.remove(m)) {
  3028                 isValid = false;
  3029                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  3030                           m.name, a.type);
  3034         // all the remaining ones better have default values
  3035         List<Name> missingDefaults = List.nil();
  3036         for (MethodSymbol m : members) {
  3037             if (m.defaultValue == null && !m.type.isErroneous()) {
  3038                 missingDefaults = missingDefaults.append(m.name);
  3041         missingDefaults = missingDefaults.reverse();
  3042         if (missingDefaults.nonEmpty()) {
  3043             isValid = false;
  3044             String key = (missingDefaults.size() > 1)
  3045                     ? "annotation.missing.default.value.1"
  3046                     : "annotation.missing.default.value";
  3047             log.error(a.pos(), key, a.type, missingDefaults);
  3050         // special case: java.lang.annotation.Target must not have
  3051         // repeated values in its value member
  3052         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  3053             a.args.tail == null)
  3054             return isValid;
  3056         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  3057         JCAssign assign = (JCAssign) a.args.head;
  3058         Symbol m = TreeInfo.symbol(assign.lhs);
  3059         if (m.name != names.value) return false;
  3060         JCTree rhs = assign.rhs;
  3061         if (!rhs.hasTag(NEWARRAY)) return false;
  3062         JCNewArray na = (JCNewArray) rhs;
  3063         Set<Symbol> targets = new HashSet<Symbol>();
  3064         for (JCTree elem : na.elems) {
  3065             if (!targets.add(TreeInfo.symbol(elem))) {
  3066                 isValid = false;
  3067                 log.error(elem.pos(), "repeated.annotation.target");
  3070         return isValid;
  3073     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  3074         if (allowAnnotations &&
  3075             lint.isEnabled(LintCategory.DEP_ANN) &&
  3076             (s.flags() & DEPRECATED) != 0 &&
  3077             !syms.deprecatedType.isErroneous() &&
  3078             s.attribute(syms.deprecatedType.tsym) == null) {
  3079             log.warning(LintCategory.DEP_ANN,
  3080                     pos, "missing.deprecated.annotation");
  3084     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  3085         if ((s.flags() & DEPRECATED) != 0 &&
  3086                 (other.flags() & DEPRECATED) == 0 &&
  3087                 s.outermostClass() != other.outermostClass()) {
  3088             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3089                 @Override
  3090                 public void report() {
  3091                     warnDeprecated(pos, s);
  3093             });
  3097     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  3098         if ((s.flags() & PROPRIETARY) != 0) {
  3099             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3100                 public void report() {
  3101                     if (enableSunApiLintControl)
  3102                       warnSunApi(pos, "sun.proprietary", s);
  3103                     else
  3104                       log.mandatoryWarning(pos, "sun.proprietary", s);
  3106             });
  3110     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
  3111         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
  3112             log.error(pos, "not.in.profile", s, profile);
  3116 /* *************************************************************************
  3117  * Check for recursive annotation elements.
  3118  **************************************************************************/
  3120     /** Check for cycles in the graph of annotation elements.
  3121      */
  3122     void checkNonCyclicElements(JCClassDecl tree) {
  3123         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  3124         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  3125         try {
  3126             tree.sym.flags_field |= LOCKED;
  3127             for (JCTree def : tree.defs) {
  3128                 if (!def.hasTag(METHODDEF)) continue;
  3129                 JCMethodDecl meth = (JCMethodDecl)def;
  3130                 checkAnnotationResType(meth.pos(), meth.restype.type);
  3132         } finally {
  3133             tree.sym.flags_field &= ~LOCKED;
  3134             tree.sym.flags_field |= ACYCLIC_ANN;
  3138     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  3139         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  3140             return;
  3141         if ((tsym.flags_field & LOCKED) != 0) {
  3142             log.error(pos, "cyclic.annotation.element");
  3143             return;
  3145         try {
  3146             tsym.flags_field |= LOCKED;
  3147             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3148                 Symbol s = e.sym;
  3149                 if (s.kind != Kinds.MTH)
  3150                     continue;
  3151                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3153         } finally {
  3154             tsym.flags_field &= ~LOCKED;
  3155             tsym.flags_field |= ACYCLIC_ANN;
  3159     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3160         switch (type.getTag()) {
  3161         case CLASS:
  3162             if ((type.tsym.flags() & ANNOTATION) != 0)
  3163                 checkNonCyclicElementsInternal(pos, type.tsym);
  3164             break;
  3165         case ARRAY:
  3166             checkAnnotationResType(pos, types.elemtype(type));
  3167             break;
  3168         default:
  3169             break; // int etc
  3173 /* *************************************************************************
  3174  * Check for cycles in the constructor call graph.
  3175  **************************************************************************/
  3177     /** Check for cycles in the graph of constructors calling other
  3178      *  constructors.
  3179      */
  3180     void checkCyclicConstructors(JCClassDecl tree) {
  3181         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3183         // enter each constructor this-call into the map
  3184         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3185             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3186             if (app == null) continue;
  3187             JCMethodDecl meth = (JCMethodDecl) l.head;
  3188             if (TreeInfo.name(app.meth) == names._this) {
  3189                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3190             } else {
  3191                 meth.sym.flags_field |= ACYCLIC;
  3195         // Check for cycles in the map
  3196         Symbol[] ctors = new Symbol[0];
  3197         ctors = callMap.keySet().toArray(ctors);
  3198         for (Symbol caller : ctors) {
  3199             checkCyclicConstructor(tree, caller, callMap);
  3203     /** Look in the map to see if the given constructor is part of a
  3204      *  call cycle.
  3205      */
  3206     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3207                                         Map<Symbol,Symbol> callMap) {
  3208         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3209             if ((ctor.flags_field & LOCKED) != 0) {
  3210                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3211                           "recursive.ctor.invocation");
  3212             } else {
  3213                 ctor.flags_field |= LOCKED;
  3214                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3215                 ctor.flags_field &= ~LOCKED;
  3217             ctor.flags_field |= ACYCLIC;
  3221 /* *************************************************************************
  3222  * Miscellaneous
  3223  **************************************************************************/
  3225     /**
  3226      * Return the opcode of the operator but emit an error if it is an
  3227      * error.
  3228      * @param pos        position for error reporting.
  3229      * @param operator   an operator
  3230      * @param tag        a tree tag
  3231      * @param left       type of left hand side
  3232      * @param right      type of right hand side
  3233      */
  3234     int checkOperator(DiagnosticPosition pos,
  3235                        OperatorSymbol operator,
  3236                        JCTree.Tag tag,
  3237                        Type left,
  3238                        Type right) {
  3239         if (operator.opcode == ByteCodes.error) {
  3240             log.error(pos,
  3241                       "operator.cant.be.applied.1",
  3242                       treeinfo.operatorName(tag),
  3243                       left, right);
  3245         return operator.opcode;
  3249     /**
  3250      *  Check for division by integer constant zero
  3251      *  @param pos           Position for error reporting.
  3252      *  @param operator      The operator for the expression
  3253      *  @param operand       The right hand operand for the expression
  3254      */
  3255     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3256         if (operand.constValue() != null
  3257             && lint.isEnabled(LintCategory.DIVZERO)
  3258             && operand.getTag().isSubRangeOf(LONG)
  3259             && ((Number) (operand.constValue())).longValue() == 0) {
  3260             int opc = ((OperatorSymbol)operator).opcode;
  3261             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3262                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3263                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3268     /**
  3269      * Check for empty statements after if
  3270      */
  3271     void checkEmptyIf(JCIf tree) {
  3272         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3273                 lint.isEnabled(LintCategory.EMPTY))
  3274             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3277     /** Check that symbol is unique in given scope.
  3278      *  @param pos           Position for error reporting.
  3279      *  @param sym           The symbol.
  3280      *  @param s             The scope.
  3281      */
  3282     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3283         if (sym.type.isErroneous())
  3284             return true;
  3285         if (sym.owner.name == names.any) return false;
  3286         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3287             if (sym != e.sym &&
  3288                     (e.sym.flags() & CLASH) == 0 &&
  3289                     sym.kind == e.sym.kind &&
  3290                     sym.name != names.error &&
  3291                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3292                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3293                     varargsDuplicateError(pos, sym, e.sym);
  3294                     return true;
  3295                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3296                     duplicateErasureError(pos, sym, e.sym);
  3297                     sym.flags_field |= CLASH;
  3298                     return true;
  3299                 } else {
  3300                     duplicateError(pos, e.sym);
  3301                     return false;
  3305         return true;
  3308     /** Report duplicate declaration error.
  3309      */
  3310     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3311         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3312             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3316     /** Check that single-type import is not already imported or top-level defined,
  3317      *  but make an exception for two single-type imports which denote the same type.
  3318      *  @param pos           Position for error reporting.
  3319      *  @param sym           The symbol.
  3320      *  @param s             The scope
  3321      */
  3322     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3323         return checkUniqueImport(pos, sym, s, false);
  3326     /** Check that static single-type import is not already imported or top-level defined,
  3327      *  but make an exception for two single-type imports which denote the same type.
  3328      *  @param pos           Position for error reporting.
  3329      *  @param sym           The symbol.
  3330      *  @param s             The scope
  3331      */
  3332     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3333         return checkUniqueImport(pos, sym, s, true);
  3336     /** Check that single-type import is not already imported or top-level defined,
  3337      *  but make an exception for two single-type imports which denote the same type.
  3338      *  @param pos           Position for error reporting.
  3339      *  @param sym           The symbol.
  3340      *  @param s             The scope.
  3341      *  @param staticImport  Whether or not this was a static import
  3342      */
  3343     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3344         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3345             // is encountered class entered via a class declaration?
  3346             boolean isClassDecl = e.scope == s;
  3347             if ((isClassDecl || sym != e.sym) &&
  3348                 sym.kind == e.sym.kind &&
  3349                 sym.name != names.error) {
  3350                 if (!e.sym.type.isErroneous()) {
  3351                     String what = e.sym.toString();
  3352                     if (!isClassDecl) {
  3353                         if (staticImport)
  3354                             log.error(pos, "already.defined.static.single.import", what);
  3355                         else
  3356                             log.error(pos, "already.defined.single.import", what);
  3358                     else if (sym != e.sym)
  3359                         log.error(pos, "already.defined.this.unit", what);
  3361                 return false;
  3364         return true;
  3367     /** Check that a qualified name is in canonical form (for import decls).
  3368      */
  3369     public void checkCanonical(JCTree tree) {
  3370         if (!isCanonical(tree))
  3371             log.error(tree.pos(), "import.requires.canonical",
  3372                       TreeInfo.symbol(tree));
  3374         // where
  3375         private boolean isCanonical(JCTree tree) {
  3376             while (tree.hasTag(SELECT)) {
  3377                 JCFieldAccess s = (JCFieldAccess) tree;
  3378                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3379                     return false;
  3380                 tree = s.selected;
  3382             return true;
  3385     /** Check that an auxiliary class is not accessed from any other file than its own.
  3386      */
  3387     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3388         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3389             (c.flags() & AUXILIARY) != 0 &&
  3390             rs.isAccessible(env, c) &&
  3391             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3393             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3394                         c, c.sourcefile);
  3398     private class ConversionWarner extends Warner {
  3399         final String uncheckedKey;
  3400         final Type found;
  3401         final Type expected;
  3402         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3403             super(pos);
  3404             this.uncheckedKey = uncheckedKey;
  3405             this.found = found;
  3406             this.expected = expected;
  3409         @Override
  3410         public void warn(LintCategory lint) {
  3411             boolean warned = this.warned;
  3412             super.warn(lint);
  3413             if (warned) return; // suppress redundant diagnostics
  3414             switch (lint) {
  3415                 case UNCHECKED:
  3416                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3417                     break;
  3418                 case VARARGS:
  3419                     if (method != null &&
  3420                             method.attribute(syms.trustMeType.tsym) != null &&
  3421                             isTrustMeAllowedOnMethod(method) &&
  3422                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3423                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3425                     break;
  3426                 default:
  3427                     throw new AssertionError("Unexpected lint: " + lint);
  3432     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3433         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3436     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3437         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial