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

Tue, 26 Feb 2013 09:04:19 +0000

author
vromero
date
Tue, 26 Feb 2013 09:04:19 +0000
changeset 1607
bd49e0304281
parent 1603
6118072811e5
child 1613
d2a98dde7ecc
permissions
-rw-r--r--

8008436: javac should not issue a warning for overriding equals without hasCode if hashCode has been overriden by a superclass
Reviewed-by: jjg, mcimadamore

     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     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   222         DeferredLintHandler prev = deferredLintHandler;
   223         deferredLintHandler = newDeferredLintHandler;
   224         return prev;
   225     }
   227     MethodSymbol setMethod(MethodSymbol newMethod) {
   228         MethodSymbol prev = method;
   229         method = newMethod;
   230         return prev;
   231     }
   233     /** Warn about deprecated symbol.
   234      *  @param pos        Position to be used for error reporting.
   235      *  @param sym        The deprecated symbol.
   236      */
   237     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   238         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   239             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   240     }
   242     /** Warn about unchecked operation.
   243      *  @param pos        Position to be used for error reporting.
   244      *  @param msg        A string describing the problem.
   245      */
   246     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   247         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   248             uncheckedHandler.report(pos, msg, args);
   249     }
   251     /** Warn about unsafe vararg method decl.
   252      *  @param pos        Position to be used for error reporting.
   253      */
   254     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   255         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   256             log.warning(LintCategory.VARARGS, pos, key, args);
   257     }
   259     /** Warn about using proprietary API.
   260      *  @param pos        Position to be used for error reporting.
   261      *  @param msg        A string describing the problem.
   262      */
   263     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   264         if (!lint.isSuppressed(LintCategory.SUNAPI))
   265             sunApiHandler.report(pos, msg, args);
   266     }
   268     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   269         if (lint.isEnabled(LintCategory.STATIC))
   270             log.warning(LintCategory.STATIC, pos, msg, args);
   271     }
   273     /**
   274      * Report any deferred diagnostics.
   275      */
   276     public void reportDeferredDiagnostics() {
   277         deprecationHandler.reportDeferredDiagnostic();
   278         uncheckedHandler.reportDeferredDiagnostic();
   279         sunApiHandler.reportDeferredDiagnostic();
   280     }
   283     /** Report a failure to complete a class.
   284      *  @param pos        Position to be used for error reporting.
   285      *  @param ex         The failure to report.
   286      */
   287     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   288         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   289         if (ex instanceof ClassReader.BadClassFile
   290                 && !suppressAbortOnBadClassFile) throw new Abort();
   291         else return syms.errType;
   292     }
   294     /** Report an error that wrong type tag was found.
   295      *  @param pos        Position to be used for error reporting.
   296      *  @param required   An internationalized string describing the type tag
   297      *                    required.
   298      *  @param found      The type that was found.
   299      */
   300     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   301         // this error used to be raised by the parser,
   302         // but has been delayed to this point:
   303         if (found instanceof Type && ((Type)found).hasTag(VOID)) {
   304             log.error(pos, "illegal.start.of.type");
   305             return syms.errType;
   306         }
   307         log.error(pos, "type.found.req", found, required);
   308         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   309     }
   311     /** Report an error that symbol cannot be referenced before super
   312      *  has been called.
   313      *  @param pos        Position to be used for error reporting.
   314      *  @param sym        The referenced symbol.
   315      */
   316     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   317         log.error(pos, "cant.ref.before.ctor.called", sym);
   318     }
   320     /** Report duplicate declaration error.
   321      */
   322     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   323         if (!sym.type.isErroneous()) {
   324             Symbol location = sym.location();
   325             if (location.kind == MTH &&
   326                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   327                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   328                         kindName(sym.location()), kindName(sym.location().enclClass()),
   329                         sym.location().enclClass());
   330             } else {
   331                 log.error(pos, "already.defined", kindName(sym), sym,
   332                         kindName(sym.location()), sym.location());
   333             }
   334         }
   335     }
   337     /** Report array/varargs duplicate declaration
   338      */
   339     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   340         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   341             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   342         }
   343     }
   345 /* ************************************************************************
   346  * duplicate declaration checking
   347  *************************************************************************/
   349     /** Check that variable does not hide variable with same name in
   350      *  immediately enclosing local scope.
   351      *  @param pos           Position for error reporting.
   352      *  @param v             The symbol.
   353      *  @param s             The scope.
   354      */
   355     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   356         if (s.next != null) {
   357             for (Scope.Entry e = s.next.lookup(v.name);
   358                  e.scope != null && e.sym.owner == v.owner;
   359                  e = e.next()) {
   360                 if (e.sym.kind == VAR &&
   361                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   362                     v.name != names.error) {
   363                     duplicateError(pos, e.sym);
   364                     return;
   365                 }
   366             }
   367         }
   368     }
   370     /** Check that a class or interface does not hide a class or
   371      *  interface with same name in immediately enclosing local scope.
   372      *  @param pos           Position for error reporting.
   373      *  @param c             The symbol.
   374      *  @param s             The scope.
   375      */
   376     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   377         if (s.next != null) {
   378             for (Scope.Entry e = s.next.lookup(c.name);
   379                  e.scope != null && e.sym.owner == c.owner;
   380                  e = e.next()) {
   381                 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
   382                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   383                     c.name != names.error) {
   384                     duplicateError(pos, e.sym);
   385                     return;
   386                 }
   387             }
   388         }
   389     }
   391     /** Check that class does not have the same name as one of
   392      *  its enclosing classes, or as a class defined in its enclosing scope.
   393      *  return true if class is unique in its enclosing scope.
   394      *  @param pos           Position for error reporting.
   395      *  @param name          The class name.
   396      *  @param s             The enclosing scope.
   397      */
   398     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   399         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   400             if (e.sym.kind == TYP && e.sym.name != names.error) {
   401                 duplicateError(pos, e.sym);
   402                 return false;
   403             }
   404         }
   405         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   406             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   407                 duplicateError(pos, sym);
   408                 return true;
   409             }
   410         }
   411         return true;
   412     }
   414 /* *************************************************************************
   415  * Class name generation
   416  **************************************************************************/
   418     /** Return name of local class.
   419      *  This is of the form   {@code <enclClass> $ n <classname> }
   420      *  where
   421      *    enclClass is the flat name of the enclosing class,
   422      *    classname is the simple name of the local class
   423      */
   424     Name localClassName(ClassSymbol c) {
   425         for (int i=1; ; i++) {
   426             Name flatname = names.
   427                 fromString("" + c.owner.enclClass().flatname +
   428                            syntheticNameChar + i +
   429                            c.name);
   430             if (compiled.get(flatname) == null) return flatname;
   431         }
   432     }
   434 /* *************************************************************************
   435  * Type Checking
   436  **************************************************************************/
   438     /**
   439      * A check context is an object that can be used to perform compatibility
   440      * checks - depending on the check context, meaning of 'compatibility' might
   441      * vary significantly.
   442      */
   443     public interface CheckContext {
   444         /**
   445          * Is type 'found' compatible with type 'req' in given context
   446          */
   447         boolean compatible(Type found, Type req, Warner warn);
   448         /**
   449          * Report a check error
   450          */
   451         void report(DiagnosticPosition pos, JCDiagnostic details);
   452         /**
   453          * Obtain a warner for this check context
   454          */
   455         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   457         public Infer.InferenceContext inferenceContext();
   459         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   460     }
   462     /**
   463      * This class represent a check context that is nested within another check
   464      * context - useful to check sub-expressions. The default behavior simply
   465      * redirects all method calls to the enclosing check context leveraging
   466      * the forwarding pattern.
   467      */
   468     static class NestedCheckContext implements CheckContext {
   469         CheckContext enclosingContext;
   471         NestedCheckContext(CheckContext enclosingContext) {
   472             this.enclosingContext = enclosingContext;
   473         }
   475         public boolean compatible(Type found, Type req, Warner warn) {
   476             return enclosingContext.compatible(found, req, warn);
   477         }
   479         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   480             enclosingContext.report(pos, details);
   481         }
   483         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   484             return enclosingContext.checkWarner(pos, found, req);
   485         }
   487         public Infer.InferenceContext inferenceContext() {
   488             return enclosingContext.inferenceContext();
   489         }
   491         public DeferredAttrContext deferredAttrContext() {
   492             return enclosingContext.deferredAttrContext();
   493         }
   494     }
   496     /**
   497      * Check context to be used when evaluating assignment/return statements
   498      */
   499     CheckContext basicHandler = new CheckContext() {
   500         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   501             log.error(pos, "prob.found.req", details);
   502         }
   503         public boolean compatible(Type found, Type req, Warner warn) {
   504             return types.isAssignable(found, req, warn);
   505         }
   507         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   508             return convertWarner(pos, found, req);
   509         }
   511         public InferenceContext inferenceContext() {
   512             return infer.emptyContext;
   513         }
   515         public DeferredAttrContext deferredAttrContext() {
   516             return deferredAttr.emptyDeferredAttrContext;
   517         }
   518     };
   520     /** Check that a given type is assignable to a given proto-type.
   521      *  If it is, return the type, otherwise return errType.
   522      *  @param pos        Position to be used for error reporting.
   523      *  @param found      The type that was found.
   524      *  @param req        The type that was required.
   525      */
   526     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   527         return checkType(pos, found, req, basicHandler);
   528     }
   530     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   531         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   532         if (inferenceContext.free(req)) {
   533             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   534                 @Override
   535                 public void typesInferred(InferenceContext inferenceContext) {
   536                     checkType(pos, found, inferenceContext.asInstType(req), checkContext);
   537                 }
   538             });
   539         }
   540         if (req.hasTag(ERROR))
   541             return req;
   542         if (req.hasTag(NONE))
   543             return found;
   544         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   545             return found;
   546         } else {
   547             if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
   548                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   549                 return types.createErrorType(found);
   550             }
   551             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   552             return types.createErrorType(found);
   553         }
   554     }
   556     /** Check that a given type can be cast to a given target type.
   557      *  Return the result of the cast.
   558      *  @param pos        Position to be used for error reporting.
   559      *  @param found      The type that is being cast.
   560      *  @param req        The target type of the cast.
   561      */
   562     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   563         return checkCastable(pos, found, req, basicHandler);
   564     }
   565     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   566         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   567             return req;
   568         } else {
   569             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   570             return types.createErrorType(found);
   571         }
   572     }
   574     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   575      * The problem should only be reported for non-292 cast
   576      */
   577     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   578         if (!tree.type.isErroneous() &&
   579                 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   580                 && types.isSameType(tree.expr.type, tree.clazz.type)
   581                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
   582                 && !is292targetTypeCast(tree)) {
   583             log.warning(Lint.LintCategory.CAST,
   584                     tree.pos(), "redundant.cast", tree.expr.type);
   585         }
   586     }
   587     //where
   588         private boolean is292targetTypeCast(JCTypeCast tree) {
   589             boolean is292targetTypeCast = false;
   590             JCExpression expr = TreeInfo.skipParens(tree.expr);
   591             if (expr.hasTag(APPLY)) {
   592                 JCMethodInvocation apply = (JCMethodInvocation)expr;
   593                 Symbol sym = TreeInfo.symbol(apply.meth);
   594                 is292targetTypeCast = sym != null &&
   595                     sym.kind == MTH &&
   596                     (sym.flags() & HYPOTHETICAL) != 0;
   597             }
   598             return is292targetTypeCast;
   599         }
   601         private static final boolean ignoreAnnotatedCasts = true;
   603     /** Check that a type is within some bounds.
   604      *
   605      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
   606      *  type argument.
   607      *  @param a             The type that should be bounded by bs.
   608      *  @param bound         The bound.
   609      */
   610     private boolean checkExtends(Type a, Type bound) {
   611          if (a.isUnbound()) {
   612              return true;
   613          } else if (!a.hasTag(WILDCARD)) {
   614              a = types.upperBound(a);
   615              return types.isSubtype(a, bound);
   616          } else if (a.isExtendsBound()) {
   617              return types.isCastable(bound, types.upperBound(a), types.noWarnings);
   618          } else if (a.isSuperBound()) {
   619              return !types.notSoftSubtype(types.lowerBound(a), bound);
   620          }
   621          return true;
   622      }
   624     /** Check that type is different from 'void'.
   625      *  @param pos           Position to be used for error reporting.
   626      *  @param t             The type to be checked.
   627      */
   628     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   629         if (t.hasTag(VOID)) {
   630             log.error(pos, "void.not.allowed.here");
   631             return types.createErrorType(t);
   632         } else {
   633             return t;
   634         }
   635     }
   637     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
   638         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
   639             return typeTagError(pos,
   640                                 diags.fragment("type.req.class.array"),
   641                                 asTypeParam(t));
   642         } else {
   643             return t;
   644         }
   645     }
   647     /** Check that type is a class or interface type.
   648      *  @param pos           Position to be used for error reporting.
   649      *  @param t             The type to be checked.
   650      */
   651     Type checkClassType(DiagnosticPosition pos, Type t) {
   652         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
   653             return typeTagError(pos,
   654                                 diags.fragment("type.req.class"),
   655                                 asTypeParam(t));
   656         } else {
   657             return t;
   658         }
   659     }
   660     //where
   661         private Object asTypeParam(Type t) {
   662             return (t.hasTag(TYPEVAR))
   663                                     ? diags.fragment("type.parameter", t)
   664                                     : t;
   665         }
   667     /** Check that type is a valid qualifier for a constructor reference expression
   668      */
   669     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
   670         t = checkClassOrArrayType(pos, t);
   671         if (t.hasTag(CLASS)) {
   672             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
   673                 log.error(pos, "abstract.cant.be.instantiated");
   674                 t = types.createErrorType(t);
   675             } else if ((t.tsym.flags() & ENUM) != 0) {
   676                 log.error(pos, "enum.cant.be.instantiated");
   677                 t = types.createErrorType(t);
   678             }
   679         }
   680         return t;
   681     }
   683     /** Check that type is a class or interface type.
   684      *  @param pos           Position to be used for error reporting.
   685      *  @param t             The type to be checked.
   686      *  @param noBounds    True if type bounds are illegal here.
   687      */
   688     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   689         t = checkClassType(pos, t);
   690         if (noBounds && t.isParameterized()) {
   691             List<Type> args = t.getTypeArguments();
   692             while (args.nonEmpty()) {
   693                 if (args.head.hasTag(WILDCARD))
   694                     return typeTagError(pos,
   695                                         diags.fragment("type.req.exact"),
   696                                         args.head);
   697                 args = args.tail;
   698             }
   699         }
   700         return t;
   701     }
   703     /** Check that type is a reifiable class, interface or array type.
   704      *  @param pos           Position to be used for error reporting.
   705      *  @param t             The type to be checked.
   706      */
   707     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   708         t = checkClassOrArrayType(pos, t);
   709         if (!t.isErroneous() && !types.isReifiable(t)) {
   710             log.error(pos, "illegal.generic.type.for.instof");
   711             return types.createErrorType(t);
   712         } else {
   713             return t;
   714         }
   715     }
   717     /** Check that type is a reference type, i.e. a class, interface or array type
   718      *  or a type variable.
   719      *  @param pos           Position to be used for error reporting.
   720      *  @param t             The type to be checked.
   721      */
   722     Type checkRefType(DiagnosticPosition pos, Type t) {
   723         if (t.isReference())
   724             return t;
   725         else
   726             return typeTagError(pos,
   727                                 diags.fragment("type.req.ref"),
   728                                 t);
   729     }
   731     /** Check that each type is a reference type, i.e. a class, interface or array type
   732      *  or a type variable.
   733      *  @param trees         Original trees, used for error reporting.
   734      *  @param types         The types to be checked.
   735      */
   736     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   737         List<JCExpression> tl = trees;
   738         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   739             l.head = checkRefType(tl.head.pos(), l.head);
   740             tl = tl.tail;
   741         }
   742         return types;
   743     }
   745     /** Check that type is a null or reference type.
   746      *  @param pos           Position to be used for error reporting.
   747      *  @param t             The type to be checked.
   748      */
   749     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   750         if (t.isNullOrReference())
   751             return t;
   752         else
   753             return typeTagError(pos,
   754                                 diags.fragment("type.req.ref"),
   755                                 t);
   756     }
   758     /** Check that flag set does not contain elements of two conflicting sets. s
   759      *  Return true if it doesn't.
   760      *  @param pos           Position to be used for error reporting.
   761      *  @param flags         The set of flags to be checked.
   762      *  @param set1          Conflicting flags set #1.
   763      *  @param set2          Conflicting flags set #2.
   764      */
   765     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   766         if ((flags & set1) != 0 && (flags & set2) != 0) {
   767             log.error(pos,
   768                       "illegal.combination.of.modifiers",
   769                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   770                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   771             return false;
   772         } else
   773             return true;
   774     }
   776     /** Check that usage of diamond operator is correct (i.e. diamond should not
   777      * be used with non-generic classes or in anonymous class creation expressions)
   778      */
   779     Type checkDiamond(JCNewClass tree, Type t) {
   780         if (!TreeInfo.isDiamond(tree) ||
   781                 t.isErroneous()) {
   782             return checkClassType(tree.clazz.pos(), t, true);
   783         } else if (tree.def != null) {
   784             log.error(tree.clazz.pos(),
   785                     "cant.apply.diamond.1",
   786                     t, diags.fragment("diamond.and.anon.class", t));
   787             return types.createErrorType(t);
   788         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   789             log.error(tree.clazz.pos(),
   790                 "cant.apply.diamond.1",
   791                 t, diags.fragment("diamond.non.generic", t));
   792             return types.createErrorType(t);
   793         } else if (tree.typeargs != null &&
   794                 tree.typeargs.nonEmpty()) {
   795             log.error(tree.clazz.pos(),
   796                 "cant.apply.diamond.1",
   797                 t, diags.fragment("diamond.and.explicit.params", t));
   798             return types.createErrorType(t);
   799         } else {
   800             return t;
   801         }
   802     }
   804     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   805         MethodSymbol m = tree.sym;
   806         if (!allowSimplifiedVarargs) return;
   807         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   808         Type varargElemType = null;
   809         if (m.isVarArgs()) {
   810             varargElemType = types.elemtype(tree.params.last().type);
   811         }
   812         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   813             if (varargElemType != null) {
   814                 log.error(tree,
   815                         "varargs.invalid.trustme.anno",
   816                         syms.trustMeType.tsym,
   817                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   818             } else {
   819                 log.error(tree,
   820                             "varargs.invalid.trustme.anno",
   821                             syms.trustMeType.tsym,
   822                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   823             }
   824         } else if (hasTrustMeAnno && varargElemType != null &&
   825                             types.isReifiable(varargElemType)) {
   826             warnUnsafeVararg(tree,
   827                             "varargs.redundant.trustme.anno",
   828                             syms.trustMeType.tsym,
   829                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   830         }
   831         else if (!hasTrustMeAnno && varargElemType != null &&
   832                 !types.isReifiable(varargElemType)) {
   833             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   834         }
   835     }
   836     //where
   837         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   838             return (s.flags() & VARARGS) != 0 &&
   839                 (s.isConstructor() ||
   840                     (s.flags() & (STATIC | FINAL)) != 0);
   841         }
   843     Type checkMethod(Type owntype,
   844                             Symbol sym,
   845                             Env<AttrContext> env,
   846                             final List<JCExpression> argtrees,
   847                             List<Type> argtypes,
   848                             boolean useVarargs,
   849                             boolean unchecked) {
   850         // System.out.println("call   : " + env.tree);
   851         // System.out.println("method : " + owntype);
   852         // System.out.println("actuals: " + argtypes);
   853         List<Type> formals = owntype.getParameterTypes();
   854         Type last = useVarargs ? formals.last() : null;
   855         if (sym.name == names.init &&
   856                 sym.owner == syms.enumSym)
   857                 formals = formals.tail.tail;
   858         List<JCExpression> args = argtrees;
   859         DeferredAttr.DeferredTypeMap checkDeferredMap =
   860                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   861         if (args != null) {
   862             //this is null when type-checking a method reference
   863             while (formals.head != last) {
   864                 JCTree arg = args.head;
   865                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   866                 assertConvertible(arg, arg.type, formals.head, warn);
   867                 args = args.tail;
   868                 formals = formals.tail;
   869             }
   870             if (useVarargs) {
   871                 Type varArg = types.elemtype(last);
   872                 while (args.tail != null) {
   873                     JCTree arg = args.head;
   874                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   875                     assertConvertible(arg, arg.type, varArg, warn);
   876                     args = args.tail;
   877                 }
   878             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   879                 // non-varargs call to varargs method
   880                 Type varParam = owntype.getParameterTypes().last();
   881                 Type lastArg = checkDeferredMap.apply(argtypes.last());
   882                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   883                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   884                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   885                             types.elemtype(varParam), varParam);
   886             }
   887         }
   888         if (unchecked) {
   889             warnUnchecked(env.tree.pos(),
   890                     "unchecked.meth.invocation.applied",
   891                     kindName(sym),
   892                     sym.name,
   893                     rs.methodArguments(sym.type.getParameterTypes()),
   894                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   895                     kindName(sym.location()),
   896                     sym.location());
   897            owntype = new MethodType(owntype.getParameterTypes(),
   898                    types.erasure(owntype.getReturnType()),
   899                    types.erasure(owntype.getThrownTypes()),
   900                    syms.methodClass);
   901         }
   902         if (useVarargs) {
   903             Type argtype = owntype.getParameterTypes().last();
   904             if (!types.isReifiable(argtype) &&
   905                     (!allowSimplifiedVarargs ||
   906                     sym.attribute(syms.trustMeType.tsym) == null ||
   907                     !isTrustMeAllowedOnMethod(sym))) {
   908                 warnUnchecked(env.tree.pos(),
   909                                   "unchecked.generic.array.creation",
   910                                   argtype);
   911             }
   912             if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
   913                 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
   914             }
   915          }
   916          PolyKind pkind = (sym.type.hasTag(FORALL) &&
   917                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
   918                  PolyKind.POLY : PolyKind.STANDALONE;
   919          TreeInfo.setPolyKind(env.tree, pkind);
   920          return owntype;
   921     }
   922     //where
   923         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   924             if (types.isConvertible(actual, formal, warn))
   925                 return;
   927             if (formal.isCompound()
   928                 && types.isSubtype(actual, types.supertype(formal))
   929                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   930                 return;
   931         }
   933     /**
   934      * Check that type 't' is a valid instantiation of a generic class
   935      * (see JLS 4.5)
   936      *
   937      * @param t class type to be checked
   938      * @return true if 't' is well-formed
   939      */
   940     public boolean checkValidGenericType(Type t) {
   941         return firstIncompatibleTypeArg(t) == null;
   942     }
   943     //WHERE
   944         private Type firstIncompatibleTypeArg(Type type) {
   945             List<Type> formals = type.tsym.type.allparams();
   946             List<Type> actuals = type.allparams();
   947             List<Type> args = type.getTypeArguments();
   948             List<Type> forms = type.tsym.type.getTypeArguments();
   949             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   951             // For matching pairs of actual argument types `a' and
   952             // formal type parameters with declared bound `b' ...
   953             while (args.nonEmpty() && forms.nonEmpty()) {
   954                 // exact type arguments needs to know their
   955                 // bounds (for upper and lower bound
   956                 // calculations).  So we create new bounds where
   957                 // type-parameters are replaced with actuals argument types.
   958                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   959                 args = args.tail;
   960                 forms = forms.tail;
   961             }
   963             args = type.getTypeArguments();
   964             List<Type> tvars_cap = types.substBounds(formals,
   965                                       formals,
   966                                       types.capture(type).allparams());
   967             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   968                 // Let the actual arguments know their bound
   969                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   970                 args = args.tail;
   971                 tvars_cap = tvars_cap.tail;
   972             }
   974             args = type.getTypeArguments();
   975             List<Type> bounds = bounds_buf.toList();
   977             while (args.nonEmpty() && bounds.nonEmpty()) {
   978                 Type actual = args.head;
   979                 if (!isTypeArgErroneous(actual) &&
   980                         !bounds.head.isErroneous() &&
   981                         !checkExtends(actual, bounds.head)) {
   982                     return args.head;
   983                 }
   984                 args = args.tail;
   985                 bounds = bounds.tail;
   986             }
   988             args = type.getTypeArguments();
   989             bounds = bounds_buf.toList();
   991             for (Type arg : types.capture(type).getTypeArguments()) {
   992                 if (arg.hasTag(TYPEVAR) &&
   993                         arg.getUpperBound().isErroneous() &&
   994                         !bounds.head.isErroneous() &&
   995                         !isTypeArgErroneous(args.head)) {
   996                     return args.head;
   997                 }
   998                 bounds = bounds.tail;
   999                 args = args.tail;
  1002             return null;
  1004         //where
  1005         boolean isTypeArgErroneous(Type t) {
  1006             return isTypeArgErroneous.visit(t);
  1009         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1010             public Boolean visitType(Type t, Void s) {
  1011                 return t.isErroneous();
  1013             @Override
  1014             public Boolean visitTypeVar(TypeVar t, Void s) {
  1015                 return visit(t.getUpperBound());
  1017             @Override
  1018             public Boolean visitCapturedType(CapturedType t, Void s) {
  1019                 return visit(t.getUpperBound()) ||
  1020                         visit(t.getLowerBound());
  1022             @Override
  1023             public Boolean visitWildcardType(WildcardType t, Void s) {
  1024                 return visit(t.type);
  1026         };
  1028     /** Check that given modifiers are legal for given symbol and
  1029      *  return modifiers together with any implicit modifiers for that symbol.
  1030      *  Warning: we can't use flags() here since this method
  1031      *  is called during class enter, when flags() would cause a premature
  1032      *  completion.
  1033      *  @param pos           Position to be used for error reporting.
  1034      *  @param flags         The set of modifiers given in a definition.
  1035      *  @param sym           The defined symbol.
  1036      */
  1037     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1038         long mask;
  1039         long implicit = 0;
  1040         switch (sym.kind) {
  1041         case VAR:
  1042             if (sym.owner.kind != TYP)
  1043                 mask = LocalVarFlags;
  1044             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1045                 mask = implicit = InterfaceVarFlags;
  1046             else
  1047                 mask = VarFlags;
  1048             break;
  1049         case MTH:
  1050             if (sym.name == names.init) {
  1051                 if ((sym.owner.flags_field & ENUM) != 0) {
  1052                     // enum constructors cannot be declared public or
  1053                     // protected and must be implicitly or explicitly
  1054                     // private
  1055                     implicit = PRIVATE;
  1056                     mask = PRIVATE;
  1057                 } else
  1058                     mask = ConstructorFlags;
  1059             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1060                 if ((flags & (DEFAULT | STATIC)) != 0) {
  1061                     mask = InterfaceMethodMask;
  1062                     implicit = PUBLIC;
  1063                     if ((flags & DEFAULT) != 0) {
  1064                         implicit |= ABSTRACT;
  1066                 } else {
  1067                     mask = implicit = InterfaceMethodFlags;
  1070             else {
  1071                 mask = MethodFlags;
  1073             // Imply STRICTFP if owner has STRICTFP set.
  1074             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1075                 implicit |= sym.owner.flags_field & STRICTFP;
  1076             break;
  1077         case TYP:
  1078             if (sym.isLocal()) {
  1079                 mask = LocalClassFlags;
  1080                 if (sym.name.isEmpty()) { // Anonymous class
  1081                     // Anonymous classes in static methods are themselves static;
  1082                     // that's why we admit STATIC here.
  1083                     mask |= STATIC;
  1084                     // JLS: Anonymous classes are final.
  1085                     implicit |= FINAL;
  1087                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1088                     (flags & ENUM) != 0)
  1089                     log.error(pos, "enums.must.be.static");
  1090             } else if (sym.owner.kind == TYP) {
  1091                 mask = MemberClassFlags;
  1092                 if (sym.owner.owner.kind == PCK ||
  1093                     (sym.owner.flags_field & STATIC) != 0)
  1094                     mask |= STATIC;
  1095                 else if ((flags & ENUM) != 0)
  1096                     log.error(pos, "enums.must.be.static");
  1097                 // Nested interfaces and enums are always STATIC (Spec ???)
  1098                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1099             } else {
  1100                 mask = ClassFlags;
  1102             // Interfaces are always ABSTRACT
  1103             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1105             if ((flags & ENUM) != 0) {
  1106                 // enums can't be declared abstract or final
  1107                 mask &= ~(ABSTRACT | FINAL);
  1108                 implicit |= implicitEnumFinalFlag(tree);
  1110             // Imply STRICTFP if owner has STRICTFP set.
  1111             implicit |= sym.owner.flags_field & STRICTFP;
  1112             break;
  1113         default:
  1114             throw new AssertionError();
  1116         long illegal = flags & ExtendedStandardFlags & ~mask;
  1117         if (illegal != 0) {
  1118             if ((illegal & INTERFACE) != 0) {
  1119                 log.error(pos, "intf.not.allowed.here");
  1120                 mask |= INTERFACE;
  1122             else {
  1123                 log.error(pos,
  1124                           "mod.not.allowed.here", asFlagSet(illegal));
  1127         else if ((sym.kind == TYP ||
  1128                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1129                   // in the presence of inner classes. Should it be deleted here?
  1130                   checkDisjoint(pos, flags,
  1131                                 ABSTRACT,
  1132                                 PRIVATE | STATIC | DEFAULT))
  1133                  &&
  1134                  checkDisjoint(pos, flags,
  1135                                 STATIC,
  1136                                 DEFAULT)
  1137                  &&
  1138                  checkDisjoint(pos, flags,
  1139                                ABSTRACT | INTERFACE,
  1140                                FINAL | NATIVE | SYNCHRONIZED)
  1141                  &&
  1142                  checkDisjoint(pos, flags,
  1143                                PUBLIC,
  1144                                PRIVATE | PROTECTED)
  1145                  &&
  1146                  checkDisjoint(pos, flags,
  1147                                PRIVATE,
  1148                                PUBLIC | PROTECTED)
  1149                  &&
  1150                  checkDisjoint(pos, flags,
  1151                                FINAL,
  1152                                VOLATILE)
  1153                  &&
  1154                  (sym.kind == TYP ||
  1155                   checkDisjoint(pos, flags,
  1156                                 ABSTRACT | NATIVE,
  1157                                 STRICTFP))) {
  1158             // skip
  1160         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1164     /** Determine if this enum should be implicitly final.
  1166      *  If the enum has no specialized enum contants, it is final.
  1168      *  If the enum does have specialized enum contants, it is
  1169      *  <i>not</i> final.
  1170      */
  1171     private long implicitEnumFinalFlag(JCTree tree) {
  1172         if (!tree.hasTag(CLASSDEF)) return 0;
  1173         class SpecialTreeVisitor extends JCTree.Visitor {
  1174             boolean specialized;
  1175             SpecialTreeVisitor() {
  1176                 this.specialized = false;
  1177             };
  1179             @Override
  1180             public void visitTree(JCTree tree) { /* no-op */ }
  1182             @Override
  1183             public void visitVarDef(JCVariableDecl tree) {
  1184                 if ((tree.mods.flags & ENUM) != 0) {
  1185                     if (tree.init instanceof JCNewClass &&
  1186                         ((JCNewClass) tree.init).def != null) {
  1187                         specialized = true;
  1193         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1194         JCClassDecl cdef = (JCClassDecl) tree;
  1195         for (JCTree defs: cdef.defs) {
  1196             defs.accept(sts);
  1197             if (sts.specialized) return 0;
  1199         return FINAL;
  1202 /* *************************************************************************
  1203  * Type Validation
  1204  **************************************************************************/
  1206     /** Validate a type expression. That is,
  1207      *  check that all type arguments of a parametric type are within
  1208      *  their bounds. This must be done in a second phase after type attributon
  1209      *  since a class might have a subclass as type parameter bound. E.g:
  1211      *  <pre>{@code
  1212      *  class B<A extends C> { ... }
  1213      *  class C extends B<C> { ... }
  1214      *  }</pre>
  1216      *  and we can't make sure that the bound is already attributed because
  1217      *  of possible cycles.
  1219      * Visitor method: Validate a type expression, if it is not null, catching
  1220      *  and reporting any completion failures.
  1221      */
  1222     void validate(JCTree tree, Env<AttrContext> env) {
  1223         validate(tree, env, true);
  1225     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1226         new Validator(env).validateTree(tree, checkRaw, true);
  1229     /** Visitor method: Validate a list of type expressions.
  1230      */
  1231     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1232         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1233             validate(l.head, env);
  1236     /** A visitor class for type validation.
  1237      */
  1238     class Validator extends JCTree.Visitor {
  1240         boolean isOuter;
  1241         Env<AttrContext> env;
  1243         Validator(Env<AttrContext> env) {
  1244             this.env = env;
  1247         @Override
  1248         public void visitTypeArray(JCArrayTypeTree tree) {
  1249             tree.elemtype.accept(this);
  1252         @Override
  1253         public void visitTypeApply(JCTypeApply tree) {
  1254             if (tree.type.hasTag(CLASS)) {
  1255                 List<JCExpression> args = tree.arguments;
  1256                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1258                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1259                 if (incompatibleArg != null) {
  1260                     for (JCTree arg : tree.arguments) {
  1261                         if (arg.type == incompatibleArg) {
  1262                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1264                         forms = forms.tail;
  1268                 forms = tree.type.tsym.type.getTypeArguments();
  1270                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1272                 // For matching pairs of actual argument types `a' and
  1273                 // formal type parameters with declared bound `b' ...
  1274                 while (args.nonEmpty() && forms.nonEmpty()) {
  1275                     validateTree(args.head,
  1276                             !(isOuter && is_java_lang_Class),
  1277                             false);
  1278                     args = args.tail;
  1279                     forms = forms.tail;
  1282                 // Check that this type is either fully parameterized, or
  1283                 // not parameterized at all.
  1284                 if (tree.type.getEnclosingType().isRaw())
  1285                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1286                 if (tree.clazz.hasTag(SELECT))
  1287                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1291         @Override
  1292         public void visitTypeParameter(JCTypeParameter tree) {
  1293             validateTrees(tree.bounds, true, isOuter);
  1294             checkClassBounds(tree.pos(), tree.type);
  1297         @Override
  1298         public void visitWildcard(JCWildcard tree) {
  1299             if (tree.inner != null)
  1300                 validateTree(tree.inner, true, isOuter);
  1303         @Override
  1304         public void visitSelect(JCFieldAccess tree) {
  1305             if (tree.type.hasTag(CLASS)) {
  1306                 visitSelectInternal(tree);
  1308                 // Check that this type is either fully parameterized, or
  1309                 // not parameterized at all.
  1310                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1311                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1315         public void visitSelectInternal(JCFieldAccess tree) {
  1316             if (tree.type.tsym.isStatic() &&
  1317                 tree.selected.type.isParameterized()) {
  1318                 // The enclosing type is not a class, so we are
  1319                 // looking at a static member type.  However, the
  1320                 // qualifying expression is parameterized.
  1321                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1322             } else {
  1323                 // otherwise validate the rest of the expression
  1324                 tree.selected.accept(this);
  1328         @Override
  1329         public void visitAnnotatedType(JCAnnotatedType tree) {
  1330             tree.underlyingType.accept(this);
  1333         /** Default visitor method: do nothing.
  1334          */
  1335         @Override
  1336         public void visitTree(JCTree tree) {
  1339         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1340             try {
  1341                 if (tree != null) {
  1342                     this.isOuter = isOuter;
  1343                     tree.accept(this);
  1344                     if (checkRaw)
  1345                         checkRaw(tree, env);
  1347             } catch (CompletionFailure ex) {
  1348                 completionError(tree.pos(), ex);
  1352         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1353             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1354                 validateTree(l.head, checkRaw, isOuter);
  1357         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1358             if (lint.isEnabled(LintCategory.RAW) &&
  1359                 tree.type.hasTag(CLASS) &&
  1360                 !TreeInfo.isDiamond(tree) &&
  1361                 !withinAnonConstr(env) &&
  1362                 tree.type.isRaw()) {
  1363                 log.warning(LintCategory.RAW,
  1364                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1368         boolean withinAnonConstr(Env<AttrContext> env) {
  1369             return env.enclClass.name.isEmpty() &&
  1370                     env.enclMethod != null && env.enclMethod.name == names.init;
  1374 /* *************************************************************************
  1375  * Exception checking
  1376  **************************************************************************/
  1378     /* The following methods treat classes as sets that contain
  1379      * the class itself and all their subclasses
  1380      */
  1382     /** Is given type a subtype of some of the types in given list?
  1383      */
  1384     boolean subset(Type t, List<Type> ts) {
  1385         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1386             if (types.isSubtype(t, l.head)) return true;
  1387         return false;
  1390     /** Is given type a subtype or supertype of
  1391      *  some of the types in given list?
  1392      */
  1393     boolean intersects(Type t, List<Type> ts) {
  1394         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1395             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1396         return false;
  1399     /** Add type set to given type list, unless it is a subclass of some class
  1400      *  in the list.
  1401      */
  1402     List<Type> incl(Type t, List<Type> ts) {
  1403         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1406     /** Remove type set from type set list.
  1407      */
  1408     List<Type> excl(Type t, List<Type> ts) {
  1409         if (ts.isEmpty()) {
  1410             return ts;
  1411         } else {
  1412             List<Type> ts1 = excl(t, ts.tail);
  1413             if (types.isSubtype(ts.head, t)) return ts1;
  1414             else if (ts1 == ts.tail) return ts;
  1415             else return ts1.prepend(ts.head);
  1419     /** Form the union of two type set lists.
  1420      */
  1421     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1422         List<Type> ts = ts1;
  1423         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1424             ts = incl(l.head, ts);
  1425         return ts;
  1428     /** Form the difference of two type lists.
  1429      */
  1430     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1431         List<Type> ts = ts1;
  1432         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1433             ts = excl(l.head, ts);
  1434         return ts;
  1437     /** Form the intersection of two type lists.
  1438      */
  1439     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1440         List<Type> ts = List.nil();
  1441         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1442             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1443         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1444             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1445         return ts;
  1448     /** Is exc an exception symbol that need not be declared?
  1449      */
  1450     boolean isUnchecked(ClassSymbol exc) {
  1451         return
  1452             exc.kind == ERR ||
  1453             exc.isSubClass(syms.errorType.tsym, types) ||
  1454             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1457     /** Is exc an exception type that need not be declared?
  1458      */
  1459     boolean isUnchecked(Type exc) {
  1460         return
  1461             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1462             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1463             exc.hasTag(BOT);
  1466     /** Same, but handling completion failures.
  1467      */
  1468     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1469         try {
  1470             return isUnchecked(exc);
  1471         } catch (CompletionFailure ex) {
  1472             completionError(pos, ex);
  1473             return true;
  1477     /** Is exc handled by given exception list?
  1478      */
  1479     boolean isHandled(Type exc, List<Type> handled) {
  1480         return isUnchecked(exc) || subset(exc, handled);
  1483     /** Return all exceptions in thrown list that are not in handled list.
  1484      *  @param thrown     The list of thrown exceptions.
  1485      *  @param handled    The list of handled exceptions.
  1486      */
  1487     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1488         List<Type> unhandled = List.nil();
  1489         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1490             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1491         return unhandled;
  1494 /* *************************************************************************
  1495  * Overriding/Implementation checking
  1496  **************************************************************************/
  1498     /** The level of access protection given by a flag set,
  1499      *  where PRIVATE is highest and PUBLIC is lowest.
  1500      */
  1501     static int protection(long flags) {
  1502         switch ((short)(flags & AccessFlags)) {
  1503         case PRIVATE: return 3;
  1504         case PROTECTED: return 1;
  1505         default:
  1506         case PUBLIC: return 0;
  1507         case 0: return 2;
  1511     /** A customized "cannot override" error message.
  1512      *  @param m      The overriding method.
  1513      *  @param other  The overridden method.
  1514      *  @return       An internationalized string.
  1515      */
  1516     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1517         String key;
  1518         if ((other.owner.flags() & INTERFACE) == 0)
  1519             key = "cant.override";
  1520         else if ((m.owner.flags() & INTERFACE) == 0)
  1521             key = "cant.implement";
  1522         else
  1523             key = "clashes.with";
  1524         return diags.fragment(key, m, m.location(), other, other.location());
  1527     /** A customized "override" warning message.
  1528      *  @param m      The overriding method.
  1529      *  @param other  The overridden method.
  1530      *  @return       An internationalized string.
  1531      */
  1532     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1533         String key;
  1534         if ((other.owner.flags() & INTERFACE) == 0)
  1535             key = "unchecked.override";
  1536         else if ((m.owner.flags() & INTERFACE) == 0)
  1537             key = "unchecked.implement";
  1538         else
  1539             key = "unchecked.clash.with";
  1540         return diags.fragment(key, m, m.location(), other, other.location());
  1543     /** A customized "override" warning message.
  1544      *  @param m      The overriding method.
  1545      *  @param other  The overridden method.
  1546      *  @return       An internationalized string.
  1547      */
  1548     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1549         String key;
  1550         if ((other.owner.flags() & INTERFACE) == 0)
  1551             key = "varargs.override";
  1552         else  if ((m.owner.flags() & INTERFACE) == 0)
  1553             key = "varargs.implement";
  1554         else
  1555             key = "varargs.clash.with";
  1556         return diags.fragment(key, m, m.location(), other, other.location());
  1559     /** Check that this method conforms with overridden method 'other'.
  1560      *  where `origin' is the class where checking started.
  1561      *  Complications:
  1562      *  (1) Do not check overriding of synthetic methods
  1563      *      (reason: they might be final).
  1564      *      todo: check whether this is still necessary.
  1565      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1566      *      than the method it implements. Augment the proxy methods with the
  1567      *      undeclared exceptions in this case.
  1568      *  (3) When generics are enabled, admit the case where an interface proxy
  1569      *      has a result type
  1570      *      extended by the result type of the method it implements.
  1571      *      Change the proxies result type to the smaller type in this case.
  1573      *  @param tree         The tree from which positions
  1574      *                      are extracted for errors.
  1575      *  @param m            The overriding method.
  1576      *  @param other        The overridden method.
  1577      *  @param origin       The class of which the overriding method
  1578      *                      is a member.
  1579      */
  1580     void checkOverride(JCTree tree,
  1581                        MethodSymbol m,
  1582                        MethodSymbol other,
  1583                        ClassSymbol origin) {
  1584         // Don't check overriding of synthetic methods or by bridge methods.
  1585         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1586             return;
  1589         // Error if static method overrides instance method (JLS 8.4.6.2).
  1590         if ((m.flags() & STATIC) != 0 &&
  1591                    (other.flags() & STATIC) == 0) {
  1592             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1593                       cannotOverride(m, other));
  1594             m.flags_field |= BAD_OVERRIDE;
  1595             return;
  1598         // Error if instance method overrides static or final
  1599         // method (JLS 8.4.6.1).
  1600         if ((other.flags() & FINAL) != 0 ||
  1601                  (m.flags() & STATIC) == 0 &&
  1602                  (other.flags() & STATIC) != 0) {
  1603             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1604                       cannotOverride(m, other),
  1605                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1606             m.flags_field |= BAD_OVERRIDE;
  1607             return;
  1610         if ((m.owner.flags() & ANNOTATION) != 0) {
  1611             // handled in validateAnnotationMethod
  1612             return;
  1615         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1616         if ((origin.flags() & INTERFACE) == 0 &&
  1617                  protection(m.flags()) > protection(other.flags())) {
  1618             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1619                       cannotOverride(m, other),
  1620                       other.flags() == 0 ?
  1621                           Flag.PACKAGE :
  1622                           asFlagSet(other.flags() & AccessFlags));
  1623             m.flags_field |= BAD_OVERRIDE;
  1624             return;
  1627         Type mt = types.memberType(origin.type, m);
  1628         Type ot = types.memberType(origin.type, other);
  1629         // Error if overriding result type is different
  1630         // (or, in the case of generics mode, not a subtype) of
  1631         // overridden result type. We have to rename any type parameters
  1632         // before comparing types.
  1633         List<Type> mtvars = mt.getTypeArguments();
  1634         List<Type> otvars = ot.getTypeArguments();
  1635         Type mtres = mt.getReturnType();
  1636         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1638         overrideWarner.clear();
  1639         boolean resultTypesOK =
  1640             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1641         if (!resultTypesOK) {
  1642             if (!allowCovariantReturns &&
  1643                 m.owner != origin &&
  1644                 m.owner.isSubClass(other.owner, types)) {
  1645                 // allow limited interoperability with covariant returns
  1646             } else {
  1647                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1648                           "override.incompatible.ret",
  1649                           cannotOverride(m, other),
  1650                           mtres, otres);
  1651                 m.flags_field |= BAD_OVERRIDE;
  1652                 return;
  1654         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1655             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1656                     "override.unchecked.ret",
  1657                     uncheckedOverrides(m, other),
  1658                     mtres, otres);
  1661         // Error if overriding method throws an exception not reported
  1662         // by overridden method.
  1663         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1664         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1665         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1666         if (unhandledErased.nonEmpty()) {
  1667             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1668                       "override.meth.doesnt.throw",
  1669                       cannotOverride(m, other),
  1670                       unhandledUnerased.head);
  1671             m.flags_field |= BAD_OVERRIDE;
  1672             return;
  1674         else if (unhandledUnerased.nonEmpty()) {
  1675             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1676                           "override.unchecked.thrown",
  1677                          cannotOverride(m, other),
  1678                          unhandledUnerased.head);
  1679             return;
  1682         // Optional warning if varargs don't agree
  1683         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1684             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1685             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1686                         ((m.flags() & Flags.VARARGS) != 0)
  1687                         ? "override.varargs.missing"
  1688                         : "override.varargs.extra",
  1689                         varargsOverrides(m, other));
  1692         // Warn if instance method overrides bridge method (compiler spec ??)
  1693         if ((other.flags() & BRIDGE) != 0) {
  1694             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1695                         uncheckedOverrides(m, other));
  1698         // Warn if a deprecated method overridden by a non-deprecated one.
  1699         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1700             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1703     // where
  1704         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1705             // If the method, m, is defined in an interface, then ignore the issue if the method
  1706             // is only inherited via a supertype and also implemented in the supertype,
  1707             // because in that case, we will rediscover the issue when examining the method
  1708             // in the supertype.
  1709             // If the method, m, is not defined in an interface, then the only time we need to
  1710             // address the issue is when the method is the supertype implemementation: any other
  1711             // case, we will have dealt with when examining the supertype classes
  1712             ClassSymbol mc = m.enclClass();
  1713             Type st = types.supertype(origin.type);
  1714             if (!st.hasTag(CLASS))
  1715                 return true;
  1716             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1718             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1719                 List<Type> intfs = types.interfaces(origin.type);
  1720                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1722             else
  1723                 return (stimpl != m);
  1727     // used to check if there were any unchecked conversions
  1728     Warner overrideWarner = new Warner();
  1730     /** Check that a class does not inherit two concrete methods
  1731      *  with the same signature.
  1732      *  @param pos          Position to be used for error reporting.
  1733      *  @param site         The class type to be checked.
  1734      */
  1735     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1736         Type sup = types.supertype(site);
  1737         if (!sup.hasTag(CLASS)) return;
  1739         for (Type t1 = sup;
  1740              t1.tsym.type.isParameterized();
  1741              t1 = types.supertype(t1)) {
  1742             for (Scope.Entry e1 = t1.tsym.members().elems;
  1743                  e1 != null;
  1744                  e1 = e1.sibling) {
  1745                 Symbol s1 = e1.sym;
  1746                 if (s1.kind != MTH ||
  1747                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1748                     !s1.isInheritedIn(site.tsym, types) ||
  1749                     ((MethodSymbol)s1).implementation(site.tsym,
  1750                                                       types,
  1751                                                       true) != s1)
  1752                     continue;
  1753                 Type st1 = types.memberType(t1, s1);
  1754                 int s1ArgsLength = st1.getParameterTypes().length();
  1755                 if (st1 == s1.type) continue;
  1757                 for (Type t2 = sup;
  1758                      t2.hasTag(CLASS);
  1759                      t2 = types.supertype(t2)) {
  1760                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1761                          e2.scope != null;
  1762                          e2 = e2.next()) {
  1763                         Symbol s2 = e2.sym;
  1764                         if (s2 == s1 ||
  1765                             s2.kind != MTH ||
  1766                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1767                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1768                             !s2.isInheritedIn(site.tsym, types) ||
  1769                             ((MethodSymbol)s2).implementation(site.tsym,
  1770                                                               types,
  1771                                                               true) != s2)
  1772                             continue;
  1773                         Type st2 = types.memberType(t2, s2);
  1774                         if (types.overrideEquivalent(st1, st2))
  1775                             log.error(pos, "concrete.inheritance.conflict",
  1776                                       s1, t1, s2, t2, sup);
  1783     /** Check that classes (or interfaces) do not each define an abstract
  1784      *  method with same name and arguments but incompatible return types.
  1785      *  @param pos          Position to be used for error reporting.
  1786      *  @param t1           The first argument type.
  1787      *  @param t2           The second argument type.
  1788      */
  1789     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1790                                             Type t1,
  1791                                             Type t2) {
  1792         return checkCompatibleAbstracts(pos, t1, t2,
  1793                                         types.makeCompoundType(t1, t2));
  1796     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1797                                             Type t1,
  1798                                             Type t2,
  1799                                             Type site) {
  1800         return firstIncompatibility(pos, t1, t2, site) == null;
  1803     /** Return the first method which is defined with same args
  1804      *  but different return types in two given interfaces, or null if none
  1805      *  exists.
  1806      *  @param t1     The first type.
  1807      *  @param t2     The second type.
  1808      *  @param site   The most derived type.
  1809      *  @returns symbol from t2 that conflicts with one in t1.
  1810      */
  1811     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1812         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1813         closure(t1, interfaces1);
  1814         Map<TypeSymbol,Type> interfaces2;
  1815         if (t1 == t2)
  1816             interfaces2 = interfaces1;
  1817         else
  1818             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1820         for (Type t3 : interfaces1.values()) {
  1821             for (Type t4 : interfaces2.values()) {
  1822                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1823                 if (s != null) return s;
  1826         return null;
  1829     /** Compute all the supertypes of t, indexed by type symbol. */
  1830     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1831         if (!t.hasTag(CLASS)) return;
  1832         if (typeMap.put(t.tsym, t) == null) {
  1833             closure(types.supertype(t), typeMap);
  1834             for (Type i : types.interfaces(t))
  1835                 closure(i, typeMap);
  1839     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1840     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1841         if (!t.hasTag(CLASS)) return;
  1842         if (typesSkip.get(t.tsym) != null) return;
  1843         if (typeMap.put(t.tsym, t) == null) {
  1844             closure(types.supertype(t), typesSkip, typeMap);
  1845             for (Type i : types.interfaces(t))
  1846                 closure(i, typesSkip, typeMap);
  1850     /** Return the first method in t2 that conflicts with a method from t1. */
  1851     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1852         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1853             Symbol s1 = e1.sym;
  1854             Type st1 = null;
  1855             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1856                     (s1.flags() & SYNTHETIC) != 0) continue;
  1857             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1858             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1859             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1860                 Symbol s2 = e2.sym;
  1861                 if (s1 == s2) continue;
  1862                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1863                         (s2.flags() & SYNTHETIC) != 0) continue;
  1864                 if (st1 == null) st1 = types.memberType(t1, s1);
  1865                 Type st2 = types.memberType(t2, s2);
  1866                 if (types.overrideEquivalent(st1, st2)) {
  1867                     List<Type> tvars1 = st1.getTypeArguments();
  1868                     List<Type> tvars2 = st2.getTypeArguments();
  1869                     Type rt1 = st1.getReturnType();
  1870                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1871                     boolean compat =
  1872                         types.isSameType(rt1, rt2) ||
  1873                         !rt1.isPrimitiveOrVoid() &&
  1874                         !rt2.isPrimitiveOrVoid() &&
  1875                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1876                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1877                          checkCommonOverriderIn(s1,s2,site);
  1878                     if (!compat) {
  1879                         log.error(pos, "types.incompatible.diff.ret",
  1880                             t1, t2, s2.name +
  1881                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1882                         return s2;
  1884                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1885                         !checkCommonOverriderIn(s1, s2, site)) {
  1886                     log.error(pos,
  1887                             "name.clash.same.erasure.no.override",
  1888                             s1, s1.location(),
  1889                             s2, s2.location());
  1890                     return s2;
  1894         return null;
  1896     //WHERE
  1897     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1898         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1899         Type st1 = types.memberType(site, s1);
  1900         Type st2 = types.memberType(site, s2);
  1901         closure(site, supertypes);
  1902         for (Type t : supertypes.values()) {
  1903             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1904                 Symbol s3 = e.sym;
  1905                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1906                 Type st3 = types.memberType(site,s3);
  1907                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1908                     if (s3.owner == site.tsym) {
  1909                         return true;
  1911                     List<Type> tvars1 = st1.getTypeArguments();
  1912                     List<Type> tvars2 = st2.getTypeArguments();
  1913                     List<Type> tvars3 = st3.getTypeArguments();
  1914                     Type rt1 = st1.getReturnType();
  1915                     Type rt2 = st2.getReturnType();
  1916                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1917                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1918                     boolean compat =
  1919                         !rt13.isPrimitiveOrVoid() &&
  1920                         !rt23.isPrimitiveOrVoid() &&
  1921                         (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
  1922                          types.covariantReturnType(rt23, rt2, types.noWarnings));
  1923                     if (compat)
  1924                         return true;
  1928         return false;
  1931     /** Check that a given method conforms with any method it overrides.
  1932      *  @param tree         The tree from which positions are extracted
  1933      *                      for errors.
  1934      *  @param m            The overriding method.
  1935      */
  1936     void checkOverride(JCTree tree, MethodSymbol m) {
  1937         ClassSymbol origin = (ClassSymbol)m.owner;
  1938         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1939             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1940                 log.error(tree.pos(), "enum.no.finalize");
  1941                 return;
  1943         for (Type t = origin.type; t.hasTag(CLASS);
  1944              t = types.supertype(t)) {
  1945             if (t != origin.type) {
  1946                 checkOverride(tree, t, origin, m);
  1948             for (Type t2 : types.interfaces(t)) {
  1949                 checkOverride(tree, t2, origin, m);
  1954     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1955         TypeSymbol c = site.tsym;
  1956         Scope.Entry e = c.members().lookup(m.name);
  1957         while (e.scope != null) {
  1958             if (m.overrides(e.sym, origin, types, false)) {
  1959                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1960                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1963             e = e.next();
  1967     private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
  1968         public boolean accepts(Symbol s) {
  1969             return MethodSymbol.implementation_filter.accepts(s) &&
  1970                     (s.flags() & BAD_OVERRIDE) == 0;
  1973     };
  1975     public void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
  1976             ClassSymbol someClass) {
  1977         if (lint.isEnabled(LintCategory.OVERRIDES)) {
  1978             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
  1979                     .tsym.members().lookup(names.equals).sym;
  1980             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
  1981                     .tsym.members().lookup(names.hashCode).sym;
  1983             boolean overridesEquals = types.implementation(equalsAtObject,
  1984                 someClass, false, equalsHasCodeFilter).owner == someClass;
  1985             boolean overridesHashCode = types.implementation(hashCodeAtObject,
  1986                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
  1988             if (overridesEquals && !overridesHashCode) {
  1989                 log.warning(LintCategory.OVERRIDES, pos,
  1990                         "override.equals.but.not.hashcode", someClass.fullname);
  1995     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1996         ClashFilter cf = new ClashFilter(origin.type);
  1997         return (cf.accepts(s1) &&
  1998                 cf.accepts(s2) &&
  1999                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  2003     /** Check that all abstract members of given class have definitions.
  2004      *  @param pos          Position to be used for error reporting.
  2005      *  @param c            The class.
  2006      */
  2007     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  2008         try {
  2009             MethodSymbol undef = firstUndef(c, c);
  2010             if (undef != null) {
  2011                 if ((c.flags() & ENUM) != 0 &&
  2012                     types.supertype(c.type).tsym == syms.enumSym &&
  2013                     (c.flags() & FINAL) == 0) {
  2014                     // add the ABSTRACT flag to an enum
  2015                     c.flags_field |= ABSTRACT;
  2016                 } else {
  2017                     MethodSymbol undef1 =
  2018                         new MethodSymbol(undef.flags(), undef.name,
  2019                                          types.memberType(c.type, undef), undef.owner);
  2020                     log.error(pos, "does.not.override.abstract",
  2021                               c, undef1, undef1.location());
  2024         } catch (CompletionFailure ex) {
  2025             completionError(pos, ex);
  2028 //where
  2029         /** Return first abstract member of class `c' that is not defined
  2030          *  in `impl', null if there is none.
  2031          */
  2032         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  2033             MethodSymbol undef = null;
  2034             // Do not bother to search in classes that are not abstract,
  2035             // since they cannot have abstract members.
  2036             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2037                 Scope s = c.members();
  2038                 for (Scope.Entry e = s.elems;
  2039                      undef == null && e != null;
  2040                      e = e.sibling) {
  2041                     if (e.sym.kind == MTH &&
  2042                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2043                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2044                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2045                         if (implmeth == null || implmeth == absmeth) {
  2046                             //look for default implementations
  2047                             if (allowDefaultMethods) {
  2048                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2049                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2050                                     implmeth = prov;
  2054                         if (implmeth == null || implmeth == absmeth) {
  2055                             undef = absmeth;
  2059                 if (undef == null) {
  2060                     Type st = types.supertype(c.type);
  2061                     if (st.hasTag(CLASS))
  2062                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2064                 for (List<Type> l = types.interfaces(c.type);
  2065                      undef == null && l.nonEmpty();
  2066                      l = l.tail) {
  2067                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2070             return undef;
  2073     void checkNonCyclicDecl(JCClassDecl tree) {
  2074         CycleChecker cc = new CycleChecker();
  2075         cc.scan(tree);
  2076         if (!cc.errorFound && !cc.partialCheck) {
  2077             tree.sym.flags_field |= ACYCLIC;
  2081     class CycleChecker extends TreeScanner {
  2083         List<Symbol> seenClasses = List.nil();
  2084         boolean errorFound = false;
  2085         boolean partialCheck = false;
  2087         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2088             if (sym != null && sym.kind == TYP) {
  2089                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2090                 if (classEnv != null) {
  2091                     DiagnosticSource prevSource = log.currentSource();
  2092                     try {
  2093                         log.useSource(classEnv.toplevel.sourcefile);
  2094                         scan(classEnv.tree);
  2096                     finally {
  2097                         log.useSource(prevSource.getFile());
  2099                 } else if (sym.kind == TYP) {
  2100                     checkClass(pos, sym, List.<JCTree>nil());
  2102             } else {
  2103                 //not completed yet
  2104                 partialCheck = true;
  2108         @Override
  2109         public void visitSelect(JCFieldAccess tree) {
  2110             super.visitSelect(tree);
  2111             checkSymbol(tree.pos(), tree.sym);
  2114         @Override
  2115         public void visitIdent(JCIdent tree) {
  2116             checkSymbol(tree.pos(), tree.sym);
  2119         @Override
  2120         public void visitTypeApply(JCTypeApply tree) {
  2121             scan(tree.clazz);
  2124         @Override
  2125         public void visitTypeArray(JCArrayTypeTree tree) {
  2126             scan(tree.elemtype);
  2129         @Override
  2130         public void visitClassDef(JCClassDecl tree) {
  2131             List<JCTree> supertypes = List.nil();
  2132             if (tree.getExtendsClause() != null) {
  2133                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2135             if (tree.getImplementsClause() != null) {
  2136                 for (JCTree intf : tree.getImplementsClause()) {
  2137                     supertypes = supertypes.prepend(intf);
  2140             checkClass(tree.pos(), tree.sym, supertypes);
  2143         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2144             if ((c.flags_field & ACYCLIC) != 0)
  2145                 return;
  2146             if (seenClasses.contains(c)) {
  2147                 errorFound = true;
  2148                 noteCyclic(pos, (ClassSymbol)c);
  2149             } else if (!c.type.isErroneous()) {
  2150                 try {
  2151                     seenClasses = seenClasses.prepend(c);
  2152                     if (c.type.hasTag(CLASS)) {
  2153                         if (supertypes.nonEmpty()) {
  2154                             scan(supertypes);
  2156                         else {
  2157                             ClassType ct = (ClassType)c.type;
  2158                             if (ct.supertype_field == null ||
  2159                                     ct.interfaces_field == null) {
  2160                                 //not completed yet
  2161                                 partialCheck = true;
  2162                                 return;
  2164                             checkSymbol(pos, ct.supertype_field.tsym);
  2165                             for (Type intf : ct.interfaces_field) {
  2166                                 checkSymbol(pos, intf.tsym);
  2169                         if (c.owner.kind == TYP) {
  2170                             checkSymbol(pos, c.owner);
  2173                 } finally {
  2174                     seenClasses = seenClasses.tail;
  2180     /** Check for cyclic references. Issue an error if the
  2181      *  symbol of the type referred to has a LOCKED flag set.
  2183      *  @param pos      Position to be used for error reporting.
  2184      *  @param t        The type referred to.
  2185      */
  2186     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2187         checkNonCyclicInternal(pos, t);
  2191     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2192         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2195     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2196         final TypeVar tv;
  2197         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2198             return;
  2199         if (seen.contains(t)) {
  2200             tv = (TypeVar)t;
  2201             tv.bound = types.createErrorType(t);
  2202             log.error(pos, "cyclic.inheritance", t);
  2203         } else if (t.hasTag(TYPEVAR)) {
  2204             tv = (TypeVar)t;
  2205             seen = seen.prepend(tv);
  2206             for (Type b : types.getBounds(tv))
  2207                 checkNonCyclic1(pos, b, seen);
  2211     /** Check for cyclic references. Issue an error if the
  2212      *  symbol of the type referred to has a LOCKED flag set.
  2214      *  @param pos      Position to be used for error reporting.
  2215      *  @param t        The type referred to.
  2216      *  @returns        True if the check completed on all attributed classes
  2217      */
  2218     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2219         boolean complete = true; // was the check complete?
  2220         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2221         Symbol c = t.tsym;
  2222         if ((c.flags_field & ACYCLIC) != 0) return true;
  2224         if ((c.flags_field & LOCKED) != 0) {
  2225             noteCyclic(pos, (ClassSymbol)c);
  2226         } else if (!c.type.isErroneous()) {
  2227             try {
  2228                 c.flags_field |= LOCKED;
  2229                 if (c.type.hasTag(CLASS)) {
  2230                     ClassType clazz = (ClassType)c.type;
  2231                     if (clazz.interfaces_field != null)
  2232                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2233                             complete &= checkNonCyclicInternal(pos, l.head);
  2234                     if (clazz.supertype_field != null) {
  2235                         Type st = clazz.supertype_field;
  2236                         if (st != null && st.hasTag(CLASS))
  2237                             complete &= checkNonCyclicInternal(pos, st);
  2239                     if (c.owner.kind == TYP)
  2240                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2242             } finally {
  2243                 c.flags_field &= ~LOCKED;
  2246         if (complete)
  2247             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2248         if (complete) c.flags_field |= ACYCLIC;
  2249         return complete;
  2252     /** Note that we found an inheritance cycle. */
  2253     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2254         log.error(pos, "cyclic.inheritance", c);
  2255         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2256             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2257         Type st = types.supertype(c.type);
  2258         if (st.hasTag(CLASS))
  2259             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2260         c.type = types.createErrorType(c, c.type);
  2261         c.flags_field |= ACYCLIC;
  2264     /**
  2265      * Check that functional interface methods would make sense when seen
  2266      * from the perspective of the implementing class
  2267      */
  2268     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2269         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2270         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2271         c.interfaces_field = List.of(types.removeWildcards(funcInterface));
  2272         c.supertype_field = syms.objectType;
  2273         c.tsym = csym;
  2274         csym.members_field = new Scope(csym);
  2275         Symbol descSym = types.findDescriptorSymbol(funcInterface.tsym);
  2276         Type descType = types.findDescriptorType(funcInterface);
  2277         csym.members_field.enter(new MethodSymbol(PUBLIC, descSym.name, descType, csym));
  2278         csym.completer = null;
  2279         checkImplementations(tree, csym, csym);
  2282     /** Check that all methods which implement some
  2283      *  method conform to the method they implement.
  2284      *  @param tree         The class definition whose members are checked.
  2285      */
  2286     void checkImplementations(JCClassDecl tree) {
  2287         checkImplementations(tree, tree.sym, tree.sym);
  2289     //where
  2290         /** Check that all methods which implement some
  2291          *  method in `ic' conform to the method they implement.
  2292          */
  2293         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2294             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2295                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2296                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2297                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2298                         if (e.sym.kind == MTH &&
  2299                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2300                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2301                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2302                             if (implmeth != null && implmeth != absmeth &&
  2303                                 (implmeth.owner.flags() & INTERFACE) ==
  2304                                 (origin.flags() & INTERFACE)) {
  2305                                 // don't check if implmeth is in a class, yet
  2306                                 // origin is an interface. This case arises only
  2307                                 // if implmeth is declared in Object. The reason is
  2308                                 // that interfaces really don't inherit from
  2309                                 // Object it's just that the compiler represents
  2310                                 // things that way.
  2311                                 checkOverride(tree, implmeth, absmeth, origin);
  2319     /** Check that all abstract methods implemented by a class are
  2320      *  mutually compatible.
  2321      *  @param pos          Position to be used for error reporting.
  2322      *  @param c            The class whose interfaces are checked.
  2323      */
  2324     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2325         List<Type> supertypes = types.interfaces(c);
  2326         Type supertype = types.supertype(c);
  2327         if (supertype.hasTag(CLASS) &&
  2328             (supertype.tsym.flags() & ABSTRACT) != 0)
  2329             supertypes = supertypes.prepend(supertype);
  2330         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2331             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2332                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2333                 return;
  2334             for (List<Type> m = supertypes; m != l; m = m.tail)
  2335                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2336                     return;
  2338         checkCompatibleConcretes(pos, c);
  2341     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2342         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2343             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2344                 // VM allows methods and variables with differing types
  2345                 if (sym.kind == e.sym.kind &&
  2346                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2347                     sym != e.sym &&
  2348                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2349                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2350                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2351                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2352                     return;
  2358     /** Check that all non-override equivalent methods accessible from 'site'
  2359      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2361      *  @param pos  Position to be used for error reporting.
  2362      *  @param site The class whose methods are checked.
  2363      *  @param sym  The method symbol to be checked.
  2364      */
  2365     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2366          ClashFilter cf = new ClashFilter(site);
  2367         //for each method m1 that is overridden (directly or indirectly)
  2368         //by method 'sym' in 'site'...
  2369         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2370             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2371              //...check each method m2 that is a member of 'site'
  2372              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2373                 if (m2 == m1) continue;
  2374                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2375                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2376                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2377                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2378                     sym.flags_field |= CLASH;
  2379                     String key = m1 == sym ?
  2380                             "name.clash.same.erasure.no.override" :
  2381                             "name.clash.same.erasure.no.override.1";
  2382                     log.error(pos,
  2383                             key,
  2384                             sym, sym.location(),
  2385                             m2, m2.location(),
  2386                             m1, m1.location());
  2387                     return;
  2395     /** Check that all static methods accessible from 'site' are
  2396      *  mutually compatible (JLS 8.4.8).
  2398      *  @param pos  Position to be used for error reporting.
  2399      *  @param site The class whose methods are checked.
  2400      *  @param sym  The method symbol to be checked.
  2401      */
  2402     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2403         ClashFilter cf = new ClashFilter(site);
  2404         //for each method m1 that is a member of 'site'...
  2405         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2406             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2407             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2408             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2409                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2410                 log.error(pos,
  2411                         "name.clash.same.erasure.no.hide",
  2412                         sym, sym.location(),
  2413                         s, s.location());
  2414                 return;
  2419      //where
  2420      private class ClashFilter implements Filter<Symbol> {
  2422          Type site;
  2424          ClashFilter(Type site) {
  2425              this.site = site;
  2428          boolean shouldSkip(Symbol s) {
  2429              return (s.flags() & CLASH) != 0 &&
  2430                 s.owner == site.tsym;
  2433          public boolean accepts(Symbol s) {
  2434              return s.kind == MTH &&
  2435                      (s.flags() & SYNTHETIC) == 0 &&
  2436                      !shouldSkip(s) &&
  2437                      s.isInheritedIn(site.tsym, types) &&
  2438                      !s.isConstructor();
  2442     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2443         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2444         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2445             Assert.check(m.kind == MTH);
  2446             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2447             if (prov.size() > 1) {
  2448                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2449                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2450                 for (MethodSymbol provSym : prov) {
  2451                     if ((provSym.flags() & DEFAULT) != 0) {
  2452                         defaults = defaults.append(provSym);
  2453                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2454                         abstracts = abstracts.append(provSym);
  2456                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2457                         //strong semantics - issue an error if two sibling interfaces
  2458                         //have two override-equivalent defaults - or if one is abstract
  2459                         //and the other is default
  2460                         String errKey;
  2461                         Symbol s1 = defaults.first();
  2462                         Symbol s2;
  2463                         if (defaults.size() > 1) {
  2464                             errKey = "types.incompatible.unrelated.defaults";
  2465                             s2 = defaults.toList().tail.head;
  2466                         } else {
  2467                             errKey = "types.incompatible.abstract.default";
  2468                             s2 = abstracts.first();
  2470                         log.error(pos, errKey,
  2471                                 Kinds.kindName(site.tsym), site,
  2472                                 m.name, types.memberType(site, m).getParameterTypes(),
  2473                                 s1.location(), s2.location());
  2474                         break;
  2481     //where
  2482      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2484          Type site;
  2486          DefaultMethodClashFilter(Type site) {
  2487              this.site = site;
  2490          public boolean accepts(Symbol s) {
  2491              return s.kind == MTH &&
  2492                      (s.flags() & DEFAULT) != 0 &&
  2493                      s.isInheritedIn(site.tsym, types) &&
  2494                      !s.isConstructor();
  2498     /** Report a conflict between a user symbol and a synthetic symbol.
  2499      */
  2500     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2501         if (!sym.type.isErroneous()) {
  2502             if (warnOnSyntheticConflicts) {
  2503                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2505             else {
  2506                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2511     /** Check that class c does not implement directly or indirectly
  2512      *  the same parameterized interface with two different argument lists.
  2513      *  @param pos          Position to be used for error reporting.
  2514      *  @param type         The type whose interfaces are checked.
  2515      */
  2516     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2517         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2519 //where
  2520         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2521          *  with their class symbol as key and their type as value. Make
  2522          *  sure no class is entered with two different types.
  2523          */
  2524         void checkClassBounds(DiagnosticPosition pos,
  2525                               Map<TypeSymbol,Type> seensofar,
  2526                               Type type) {
  2527             if (type.isErroneous()) return;
  2528             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2529                 Type it = l.head;
  2530                 Type oldit = seensofar.put(it.tsym, it);
  2531                 if (oldit != null) {
  2532                     List<Type> oldparams = oldit.allparams();
  2533                     List<Type> newparams = it.allparams();
  2534                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2535                         log.error(pos, "cant.inherit.diff.arg",
  2536                                   it.tsym, Type.toString(oldparams),
  2537                                   Type.toString(newparams));
  2539                 checkClassBounds(pos, seensofar, it);
  2541             Type st = types.supertype(type);
  2542             if (st != null) checkClassBounds(pos, seensofar, st);
  2545     /** Enter interface into into set.
  2546      *  If it existed already, issue a "repeated interface" error.
  2547      */
  2548     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2549         if (its.contains(it))
  2550             log.error(pos, "repeated.interface");
  2551         else {
  2552             its.add(it);
  2556 /* *************************************************************************
  2557  * Check annotations
  2558  **************************************************************************/
  2560     /**
  2561      * Recursively validate annotations values
  2562      */
  2563     void validateAnnotationTree(JCTree tree) {
  2564         class AnnotationValidator extends TreeScanner {
  2565             @Override
  2566             public void visitAnnotation(JCAnnotation tree) {
  2567                 if (!tree.type.isErroneous()) {
  2568                     super.visitAnnotation(tree);
  2569                     validateAnnotation(tree);
  2573         tree.accept(new AnnotationValidator());
  2576     /**
  2577      *  {@literal
  2578      *  Annotation types are restricted to primitives, String, an
  2579      *  enum, an annotation, Class, Class<?>, Class<? extends
  2580      *  Anything>, arrays of the preceding.
  2581      *  }
  2582      */
  2583     void validateAnnotationType(JCTree restype) {
  2584         // restype may be null if an error occurred, so don't bother validating it
  2585         if (restype != null) {
  2586             validateAnnotationType(restype.pos(), restype.type);
  2590     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2591         if (type.isPrimitive()) return;
  2592         if (types.isSameType(type, syms.stringType)) return;
  2593         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2594         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2595         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2596         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2597             validateAnnotationType(pos, types.elemtype(type));
  2598             return;
  2600         log.error(pos, "invalid.annotation.member.type");
  2603     /**
  2604      * "It is also a compile-time error if any method declared in an
  2605      * annotation type has a signature that is override-equivalent to
  2606      * that of any public or protected method declared in class Object
  2607      * or in the interface annotation.Annotation."
  2609      * @jls 9.6 Annotation Types
  2610      */
  2611     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2612         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2613             Scope s = sup.tsym.members();
  2614             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2615                 if (e.sym.kind == MTH &&
  2616                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2617                     types.overrideEquivalent(m.type, e.sym.type))
  2618                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2623     /** Check the annotations of a symbol.
  2624      */
  2625     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2626         for (JCAnnotation a : annotations)
  2627             validateAnnotation(a, s);
  2630     /** Check the type annotations.
  2631      */
  2632     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
  2633         for (JCAnnotation a : annotations)
  2634             validateTypeAnnotation(a, isTypeParameter);
  2637     /** Check an annotation of a symbol.
  2638      */
  2639     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2640         validateAnnotationTree(a);
  2642         if (!annotationApplicable(a, s))
  2643             log.error(a.pos(), "annotation.type.not.applicable");
  2645         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2646             if (!isOverrider(s))
  2647                 log.error(a.pos(), "method.does.not.override.superclass");
  2650         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2651             if (s.kind != TYP) {
  2652                 log.error(a.pos(), "bad.functional.intf.anno");
  2653             } else {
  2654                 try {
  2655                     types.findDescriptorSymbol((TypeSymbol)s);
  2656                 } catch (Types.FunctionDescriptorLookupError ex) {
  2657                     log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
  2663     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2664         Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
  2665         validateAnnotationTree(a);
  2667         if (!isTypeAnnotation(a, isTypeParameter))
  2668             log.error(a.pos(), "annotation.type.not.applicable");
  2671     /**
  2672      * Validate the proposed container 'repeatable' on the
  2673      * annotation type symbol 's'. Report errors at position
  2674      * 'pos'.
  2676      * @param s The (annotation)type declaration annotated with a @Repeatable
  2677      * @param repeatable the @Repeatable on 's'
  2678      * @param pos where to report errors
  2679      */
  2680     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2681         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2683         Type t = null;
  2684         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2685         if (!l.isEmpty()) {
  2686             Assert.check(l.head.fst.name == names.value);
  2687             t = ((Attribute.Class)l.head.snd).getValue();
  2690         if (t == null) {
  2691             // errors should already have been reported during Annotate
  2692             return;
  2695         validateValue(t.tsym, s, pos);
  2696         validateRetention(t.tsym, s, pos);
  2697         validateDocumented(t.tsym, s, pos);
  2698         validateInherited(t.tsym, s, pos);
  2699         validateTarget(t.tsym, s, pos);
  2700         validateDefault(t.tsym, s, pos);
  2703     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2704         Scope.Entry e = container.members().lookup(names.value);
  2705         if (e.scope != null && e.sym.kind == MTH) {
  2706             MethodSymbol m = (MethodSymbol) e.sym;
  2707             Type ret = m.getReturnType();
  2708             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2709                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2710                         container, ret, types.makeArrayType(contained.type));
  2712         } else {
  2713             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2717     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2718         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2719         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2721         boolean error = false;
  2722         switch (containedRetention) {
  2723         case RUNTIME:
  2724             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2725                 error = true;
  2727             break;
  2728         case CLASS:
  2729             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2730                 error = true;
  2733         if (error ) {
  2734             log.error(pos, "invalid.repeatable.annotation.retention",
  2735                       container, containerRetention,
  2736                       contained, containedRetention);
  2740     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2741         if (contained.attribute(syms.documentedType.tsym) != null) {
  2742             if (container.attribute(syms.documentedType.tsym) == null) {
  2743                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2748     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2749         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2750             if (container.attribute(syms.inheritedType.tsym) == null) {
  2751                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2756     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2757         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2759         // If contained has no Target, we are done
  2760         if (containedTarget == null) {
  2761             return;
  2764         // If contained has Target m1, container must have a Target
  2765         // annotation, m2, and m2 must be a subset of m1. (This is
  2766         // trivially true if contained has no target as per above).
  2768         // contained has target, but container has not, error
  2769         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2770         if (containerTarget == null) {
  2771             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2772             return;
  2775         Set<Name> containerTargets = new HashSet<Name>();
  2776         for (Attribute app : containerTarget.values) {
  2777             if (!(app instanceof Attribute.Enum)) {
  2778                 continue; // recovery
  2780             Attribute.Enum e = (Attribute.Enum)app;
  2781             containerTargets.add(e.value.name);
  2784         Set<Name> containedTargets = new HashSet<Name>();
  2785         for (Attribute app : containedTarget.values) {
  2786             if (!(app instanceof Attribute.Enum)) {
  2787                 continue; // recovery
  2789             Attribute.Enum e = (Attribute.Enum)app;
  2790             containedTargets.add(e.value.name);
  2793         if (!isTargetSubset(containedTargets, containerTargets)) {
  2794             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2798     /** Checks that t is a subset of s, with respect to ElementType
  2799      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2800      */
  2801     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2802         // Check that all elements in t are present in s
  2803         for (Name n2 : t) {
  2804             boolean currentElementOk = false;
  2805             for (Name n1 : s) {
  2806                 if (n1 == n2) {
  2807                     currentElementOk = true;
  2808                     break;
  2809                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2810                     currentElementOk = true;
  2811                     break;
  2814             if (!currentElementOk)
  2815                 return false;
  2817         return true;
  2820     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2821         // validate that all other elements of containing type has defaults
  2822         Scope scope = container.members();
  2823         for(Symbol elm : scope.getElements()) {
  2824             if (elm.name != names.value &&
  2825                 elm.kind == Kinds.MTH &&
  2826                 ((MethodSymbol)elm).defaultValue == null) {
  2827                 log.error(pos,
  2828                           "invalid.repeatable.annotation.elem.nondefault",
  2829                           container,
  2830                           elm);
  2835     /** Is s a method symbol that overrides a method in a superclass? */
  2836     boolean isOverrider(Symbol s) {
  2837         if (s.kind != MTH || s.isStatic())
  2838             return false;
  2839         MethodSymbol m = (MethodSymbol)s;
  2840         TypeSymbol owner = (TypeSymbol)m.owner;
  2841         for (Type sup : types.closure(owner.type)) {
  2842             if (sup == owner.type)
  2843                 continue; // skip "this"
  2844             Scope scope = sup.tsym.members();
  2845             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2846                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2847                     return true;
  2850         return false;
  2853     /** Is the annotation applicable to type annotations? */
  2854     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2855         Attribute.Compound atTarget =
  2856             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2857         if (atTarget == null) {
  2858             // An annotation without @Target is not a type annotation.
  2859             return false;
  2862         Attribute atValue = atTarget.member(names.value);
  2863         if (!(atValue instanceof Attribute.Array)) {
  2864             return false; // error recovery
  2867         Attribute.Array arr = (Attribute.Array) atValue;
  2868         for (Attribute app : arr.values) {
  2869             if (!(app instanceof Attribute.Enum)) {
  2870                 return false; // recovery
  2872             Attribute.Enum e = (Attribute.Enum) app;
  2874             if (e.value.name == names.TYPE_USE)
  2875                 return true;
  2876             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  2877                 return true;
  2879         return false;
  2882     /** Is the annotation applicable to the symbol? */
  2883     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2884         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2885         Name[] targets;
  2887         if (arr == null) {
  2888             targets = defaultTargetMetaInfo(a, s);
  2889         } else {
  2890             // TODO: can we optimize this?
  2891             targets = new Name[arr.values.length];
  2892             for (int i=0; i<arr.values.length; ++i) {
  2893                 Attribute app = arr.values[i];
  2894                 if (!(app instanceof Attribute.Enum)) {
  2895                     return true; // recovery
  2897                 Attribute.Enum e = (Attribute.Enum) app;
  2898                 targets[i] = e.value.name;
  2901         for (Name target : targets) {
  2902             if (target == names.TYPE)
  2903                 { if (s.kind == TYP) return true; }
  2904             else if (target == names.FIELD)
  2905                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2906             else if (target == names.METHOD)
  2907                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2908             else if (target == names.PARAMETER)
  2909                 { if (s.kind == VAR &&
  2910                       s.owner.kind == MTH &&
  2911                       (s.flags() & PARAMETER) != 0)
  2912                     return true;
  2914             else if (target == names.CONSTRUCTOR)
  2915                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2916             else if (target == names.LOCAL_VARIABLE)
  2917                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2918                       (s.flags() & PARAMETER) == 0)
  2919                     return true;
  2921             else if (target == names.ANNOTATION_TYPE)
  2922                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2923                     return true;
  2925             else if (target == names.PACKAGE)
  2926                 { if (s.kind == PCK) return true; }
  2927             else if (target == names.TYPE_USE)
  2928                 { if (s.kind == TYP ||
  2929                       s.kind == VAR ||
  2930                       (s.kind == MTH && !s.isConstructor() &&
  2931                       !s.type.getReturnType().hasTag(VOID)) ||
  2932                       (s.kind == MTH && s.isConstructor()))
  2933                     return true;
  2935             else if (target == names.TYPE_PARAMETER)
  2936                 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
  2937                     return true;
  2939             else
  2940                 return true; // recovery
  2942         return false;
  2946     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2947         Attribute.Compound atTarget =
  2948             s.attribute(syms.annotationTargetType.tsym);
  2949         if (atTarget == null) return null; // ok, is applicable
  2950         Attribute atValue = atTarget.member(names.value);
  2951         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2952         return (Attribute.Array) atValue;
  2955     private final Name[] dfltTargetMeta;
  2956     private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
  2957         return dfltTargetMeta;
  2960     /** Check an annotation value.
  2962      * @param a The annotation tree to check
  2963      * @return true if this annotation tree is valid, otherwise false
  2964      */
  2965     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  2966         boolean res = false;
  2967         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  2968         try {
  2969             res = validateAnnotation(a);
  2970         } finally {
  2971             log.popDiagnosticHandler(diagHandler);
  2973         return res;
  2976     private boolean validateAnnotation(JCAnnotation a) {
  2977         boolean isValid = true;
  2978         // collect an inventory of the annotation elements
  2979         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  2980         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2981              e != null;
  2982              e = e.sibling)
  2983             if (e.sym.kind == MTH)
  2984                 members.add((MethodSymbol) e.sym);
  2986         // remove the ones that are assigned values
  2987         for (JCTree arg : a.args) {
  2988             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2989             JCAssign assign = (JCAssign) arg;
  2990             Symbol m = TreeInfo.symbol(assign.lhs);
  2991             if (m == null || m.type.isErroneous()) continue;
  2992             if (!members.remove(m)) {
  2993                 isValid = false;
  2994                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2995                           m.name, a.type);
  2999         // all the remaining ones better have default values
  3000         List<Name> missingDefaults = List.nil();
  3001         for (MethodSymbol m : members) {
  3002             if (m.defaultValue == null && !m.type.isErroneous()) {
  3003                 missingDefaults = missingDefaults.append(m.name);
  3006         missingDefaults = missingDefaults.reverse();
  3007         if (missingDefaults.nonEmpty()) {
  3008             isValid = false;
  3009             String key = (missingDefaults.size() > 1)
  3010                     ? "annotation.missing.default.value.1"
  3011                     : "annotation.missing.default.value";
  3012             log.error(a.pos(), key, a.type, missingDefaults);
  3015         // special case: java.lang.annotation.Target must not have
  3016         // repeated values in its value member
  3017         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  3018             a.args.tail == null)
  3019             return isValid;
  3021         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  3022         JCAssign assign = (JCAssign) a.args.head;
  3023         Symbol m = TreeInfo.symbol(assign.lhs);
  3024         if (m.name != names.value) return false;
  3025         JCTree rhs = assign.rhs;
  3026         if (!rhs.hasTag(NEWARRAY)) return false;
  3027         JCNewArray na = (JCNewArray) rhs;
  3028         Set<Symbol> targets = new HashSet<Symbol>();
  3029         for (JCTree elem : na.elems) {
  3030             if (!targets.add(TreeInfo.symbol(elem))) {
  3031                 isValid = false;
  3032                 log.error(elem.pos(), "repeated.annotation.target");
  3035         return isValid;
  3038     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  3039         if (allowAnnotations &&
  3040             lint.isEnabled(LintCategory.DEP_ANN) &&
  3041             (s.flags() & DEPRECATED) != 0 &&
  3042             !syms.deprecatedType.isErroneous() &&
  3043             s.attribute(syms.deprecatedType.tsym) == null) {
  3044             log.warning(LintCategory.DEP_ANN,
  3045                     pos, "missing.deprecated.annotation");
  3049     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  3050         if ((s.flags() & DEPRECATED) != 0 &&
  3051                 (other.flags() & DEPRECATED) == 0 &&
  3052                 s.outermostClass() != other.outermostClass()) {
  3053             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3054                 @Override
  3055                 public void report() {
  3056                     warnDeprecated(pos, s);
  3058             });
  3062     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  3063         if ((s.flags() & PROPRIETARY) != 0) {
  3064             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3065                 public void report() {
  3066                     if (enableSunApiLintControl)
  3067                       warnSunApi(pos, "sun.proprietary", s);
  3068                     else
  3069                       log.mandatoryWarning(pos, "sun.proprietary", s);
  3071             });
  3075     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
  3076         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
  3077             log.error(pos, "not.in.profile", s, profile);
  3081 /* *************************************************************************
  3082  * Check for recursive annotation elements.
  3083  **************************************************************************/
  3085     /** Check for cycles in the graph of annotation elements.
  3086      */
  3087     void checkNonCyclicElements(JCClassDecl tree) {
  3088         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  3089         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  3090         try {
  3091             tree.sym.flags_field |= LOCKED;
  3092             for (JCTree def : tree.defs) {
  3093                 if (!def.hasTag(METHODDEF)) continue;
  3094                 JCMethodDecl meth = (JCMethodDecl)def;
  3095                 checkAnnotationResType(meth.pos(), meth.restype.type);
  3097         } finally {
  3098             tree.sym.flags_field &= ~LOCKED;
  3099             tree.sym.flags_field |= ACYCLIC_ANN;
  3103     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  3104         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  3105             return;
  3106         if ((tsym.flags_field & LOCKED) != 0) {
  3107             log.error(pos, "cyclic.annotation.element");
  3108             return;
  3110         try {
  3111             tsym.flags_field |= LOCKED;
  3112             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3113                 Symbol s = e.sym;
  3114                 if (s.kind != Kinds.MTH)
  3115                     continue;
  3116                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3118         } finally {
  3119             tsym.flags_field &= ~LOCKED;
  3120             tsym.flags_field |= ACYCLIC_ANN;
  3124     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3125         switch (type.getTag()) {
  3126         case CLASS:
  3127             if ((type.tsym.flags() & ANNOTATION) != 0)
  3128                 checkNonCyclicElementsInternal(pos, type.tsym);
  3129             break;
  3130         case ARRAY:
  3131             checkAnnotationResType(pos, types.elemtype(type));
  3132             break;
  3133         default:
  3134             break; // int etc
  3138 /* *************************************************************************
  3139  * Check for cycles in the constructor call graph.
  3140  **************************************************************************/
  3142     /** Check for cycles in the graph of constructors calling other
  3143      *  constructors.
  3144      */
  3145     void checkCyclicConstructors(JCClassDecl tree) {
  3146         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3148         // enter each constructor this-call into the map
  3149         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3150             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3151             if (app == null) continue;
  3152             JCMethodDecl meth = (JCMethodDecl) l.head;
  3153             if (TreeInfo.name(app.meth) == names._this) {
  3154                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3155             } else {
  3156                 meth.sym.flags_field |= ACYCLIC;
  3160         // Check for cycles in the map
  3161         Symbol[] ctors = new Symbol[0];
  3162         ctors = callMap.keySet().toArray(ctors);
  3163         for (Symbol caller : ctors) {
  3164             checkCyclicConstructor(tree, caller, callMap);
  3168     /** Look in the map to see if the given constructor is part of a
  3169      *  call cycle.
  3170      */
  3171     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3172                                         Map<Symbol,Symbol> callMap) {
  3173         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3174             if ((ctor.flags_field & LOCKED) != 0) {
  3175                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3176                           "recursive.ctor.invocation");
  3177             } else {
  3178                 ctor.flags_field |= LOCKED;
  3179                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3180                 ctor.flags_field &= ~LOCKED;
  3182             ctor.flags_field |= ACYCLIC;
  3186 /* *************************************************************************
  3187  * Miscellaneous
  3188  **************************************************************************/
  3190     /**
  3191      * Return the opcode of the operator but emit an error if it is an
  3192      * error.
  3193      * @param pos        position for error reporting.
  3194      * @param operator   an operator
  3195      * @param tag        a tree tag
  3196      * @param left       type of left hand side
  3197      * @param right      type of right hand side
  3198      */
  3199     int checkOperator(DiagnosticPosition pos,
  3200                        OperatorSymbol operator,
  3201                        JCTree.Tag tag,
  3202                        Type left,
  3203                        Type right) {
  3204         if (operator.opcode == ByteCodes.error) {
  3205             log.error(pos,
  3206                       "operator.cant.be.applied.1",
  3207                       treeinfo.operatorName(tag),
  3208                       left, right);
  3210         return operator.opcode;
  3214     /**
  3215      *  Check for division by integer constant zero
  3216      *  @param pos           Position for error reporting.
  3217      *  @param operator      The operator for the expression
  3218      *  @param operand       The right hand operand for the expression
  3219      */
  3220     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3221         if (operand.constValue() != null
  3222             && lint.isEnabled(LintCategory.DIVZERO)
  3223             && (operand.getTag().isSubRangeOf(LONG))
  3224             && ((Number) (operand.constValue())).longValue() == 0) {
  3225             int opc = ((OperatorSymbol)operator).opcode;
  3226             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3227                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3228                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3233     /**
  3234      * Check for empty statements after if
  3235      */
  3236     void checkEmptyIf(JCIf tree) {
  3237         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3238                 lint.isEnabled(LintCategory.EMPTY))
  3239             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3242     /** Check that symbol is unique in given scope.
  3243      *  @param pos           Position for error reporting.
  3244      *  @param sym           The symbol.
  3245      *  @param s             The scope.
  3246      */
  3247     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3248         if (sym.type.isErroneous())
  3249             return true;
  3250         if (sym.owner.name == names.any) return false;
  3251         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3252             if (sym != e.sym &&
  3253                     (e.sym.flags() & CLASH) == 0 &&
  3254                     sym.kind == e.sym.kind &&
  3255                     sym.name != names.error &&
  3256                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3257                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3258                     varargsDuplicateError(pos, sym, e.sym);
  3259                     return true;
  3260                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3261                     duplicateErasureError(pos, sym, e.sym);
  3262                     sym.flags_field |= CLASH;
  3263                     return true;
  3264                 } else {
  3265                     duplicateError(pos, e.sym);
  3266                     return false;
  3270         return true;
  3273     /** Report duplicate declaration error.
  3274      */
  3275     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3276         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3277             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3281     /** Check that single-type import is not already imported or top-level defined,
  3282      *  but make an exception for two single-type imports which denote the same type.
  3283      *  @param pos           Position for error reporting.
  3284      *  @param sym           The symbol.
  3285      *  @param s             The scope
  3286      */
  3287     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3288         return checkUniqueImport(pos, sym, s, false);
  3291     /** Check that static single-type import is not already imported or top-level defined,
  3292      *  but make an exception for two single-type imports which denote the same type.
  3293      *  @param pos           Position for error reporting.
  3294      *  @param sym           The symbol.
  3295      *  @param s             The scope
  3296      */
  3297     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3298         return checkUniqueImport(pos, sym, s, true);
  3301     /** Check that single-type import is not already imported or top-level defined,
  3302      *  but make an exception for two single-type imports which denote the same type.
  3303      *  @param pos           Position for error reporting.
  3304      *  @param sym           The symbol.
  3305      *  @param s             The scope.
  3306      *  @param staticImport  Whether or not this was a static import
  3307      */
  3308     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3309         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3310             // is encountered class entered via a class declaration?
  3311             boolean isClassDecl = e.scope == s;
  3312             if ((isClassDecl || sym != e.sym) &&
  3313                 sym.kind == e.sym.kind &&
  3314                 sym.name != names.error) {
  3315                 if (!e.sym.type.isErroneous()) {
  3316                     String what = e.sym.toString();
  3317                     if (!isClassDecl) {
  3318                         if (staticImport)
  3319                             log.error(pos, "already.defined.static.single.import", what);
  3320                         else
  3321                             log.error(pos, "already.defined.single.import", what);
  3323                     else if (sym != e.sym)
  3324                         log.error(pos, "already.defined.this.unit", what);
  3326                 return false;
  3329         return true;
  3332     /** Check that a qualified name is in canonical form (for import decls).
  3333      */
  3334     public void checkCanonical(JCTree tree) {
  3335         if (!isCanonical(tree))
  3336             log.error(tree.pos(), "import.requires.canonical",
  3337                       TreeInfo.symbol(tree));
  3339         // where
  3340         private boolean isCanonical(JCTree tree) {
  3341             while (tree.hasTag(SELECT)) {
  3342                 JCFieldAccess s = (JCFieldAccess) tree;
  3343                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3344                     return false;
  3345                 tree = s.selected;
  3347             return true;
  3350     /** Check that an auxiliary class is not accessed from any other file than its own.
  3351      */
  3352     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3353         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3354             (c.flags() & AUXILIARY) != 0 &&
  3355             rs.isAccessible(env, c) &&
  3356             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3358             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3359                         c, c.sourcefile);
  3363     private class ConversionWarner extends Warner {
  3364         final String uncheckedKey;
  3365         final Type found;
  3366         final Type expected;
  3367         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3368             super(pos);
  3369             this.uncheckedKey = uncheckedKey;
  3370             this.found = found;
  3371             this.expected = expected;
  3374         @Override
  3375         public void warn(LintCategory lint) {
  3376             boolean warned = this.warned;
  3377             super.warn(lint);
  3378             if (warned) return; // suppress redundant diagnostics
  3379             switch (lint) {
  3380                 case UNCHECKED:
  3381                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3382                     break;
  3383                 case VARARGS:
  3384                     if (method != null &&
  3385                             method.attribute(syms.trustMeType.tsym) != null &&
  3386                             isTrustMeAllowedOnMethod(method) &&
  3387                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3388                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3390                     break;
  3391                 default:
  3392                     throw new AssertionError("Unexpected lint: " + lint);
  3397     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3398         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3401     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3402         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial