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

Thu, 06 Jun 2013 15:33:40 +0100

author
mcimadamore
date
Thu, 06 Jun 2013 15:33:40 +0100
changeset 1811
349160289ba2
parent 1780
6e5076af4660
child 1812
f8472e561a97
permissions
-rw-r--r--

8008627: Compiler mishandles three-way return-type-substitutability
Summary: Compiler should not enforce an order in how ambiguous methods should be resolved
Reviewed-by: jjg, vromero

     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(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, 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", t.tsym);
   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             } else {
   679                 t = checkClassType(pos, t, true);
   680             }
   681         } else if (t.hasTag(ARRAY)) {
   682             if (!types.isReifiable(((ArrayType)t).elemtype)) {
   683                 log.error(pos, "generic.array.creation");
   684                 t = types.createErrorType(t);
   685             }
   686         }
   687         return t;
   688     }
   690     /** Check that type is a class or interface type.
   691      *  @param pos           Position to be used for error reporting.
   692      *  @param t             The type to be checked.
   693      *  @param noBounds    True if type bounds are illegal here.
   694      */
   695     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   696         t = checkClassType(pos, t);
   697         if (noBounds && t.isParameterized()) {
   698             List<Type> args = t.getTypeArguments();
   699             while (args.nonEmpty()) {
   700                 if (args.head.hasTag(WILDCARD))
   701                     return typeTagError(pos,
   702                                         diags.fragment("type.req.exact"),
   703                                         args.head);
   704                 args = args.tail;
   705             }
   706         }
   707         return t;
   708     }
   710     /** Check that type is a reifiable class, interface or array type.
   711      *  @param pos           Position to be used for error reporting.
   712      *  @param t             The type to be checked.
   713      */
   714     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   715         t = checkClassOrArrayType(pos, t);
   716         if (!t.isErroneous() && !types.isReifiable(t)) {
   717             log.error(pos, "illegal.generic.type.for.instof");
   718             return types.createErrorType(t);
   719         } else {
   720             return t;
   721         }
   722     }
   724     /** Check that type is a reference type, i.e. a class, interface or array type
   725      *  or a type variable.
   726      *  @param pos           Position to be used for error reporting.
   727      *  @param t             The type to be checked.
   728      */
   729     Type checkRefType(DiagnosticPosition pos, Type t) {
   730         if (t.isReference())
   731             return t;
   732         else
   733             return typeTagError(pos,
   734                                 diags.fragment("type.req.ref"),
   735                                 t);
   736     }
   738     /** Check that each type is a reference type, i.e. a class, interface or array type
   739      *  or a type variable.
   740      *  @param trees         Original trees, used for error reporting.
   741      *  @param types         The types to be checked.
   742      */
   743     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   744         List<JCExpression> tl = trees;
   745         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   746             l.head = checkRefType(tl.head.pos(), l.head);
   747             tl = tl.tail;
   748         }
   749         return types;
   750     }
   752     /** Check that type is a null or reference type.
   753      *  @param pos           Position to be used for error reporting.
   754      *  @param t             The type to be checked.
   755      */
   756     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   757         if (t.isNullOrReference())
   758             return t;
   759         else
   760             return typeTagError(pos,
   761                                 diags.fragment("type.req.ref"),
   762                                 t);
   763     }
   765     /** Check that flag set does not contain elements of two conflicting sets. s
   766      *  Return true if it doesn't.
   767      *  @param pos           Position to be used for error reporting.
   768      *  @param flags         The set of flags to be checked.
   769      *  @param set1          Conflicting flags set #1.
   770      *  @param set2          Conflicting flags set #2.
   771      */
   772     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   773         if ((flags & set1) != 0 && (flags & set2) != 0) {
   774             log.error(pos,
   775                       "illegal.combination.of.modifiers",
   776                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   777                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   778             return false;
   779         } else
   780             return true;
   781     }
   783     /** Check that usage of diamond operator is correct (i.e. diamond should not
   784      * be used with non-generic classes or in anonymous class creation expressions)
   785      */
   786     Type checkDiamond(JCNewClass tree, Type t) {
   787         if (!TreeInfo.isDiamond(tree) ||
   788                 t.isErroneous()) {
   789             return checkClassType(tree.clazz.pos(), t, true);
   790         } else if (tree.def != null) {
   791             log.error(tree.clazz.pos(),
   792                     "cant.apply.diamond.1",
   793                     t, diags.fragment("diamond.and.anon.class", t));
   794             return types.createErrorType(t);
   795         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   796             log.error(tree.clazz.pos(),
   797                 "cant.apply.diamond.1",
   798                 t, diags.fragment("diamond.non.generic", t));
   799             return types.createErrorType(t);
   800         } else if (tree.typeargs != null &&
   801                 tree.typeargs.nonEmpty()) {
   802             log.error(tree.clazz.pos(),
   803                 "cant.apply.diamond.1",
   804                 t, diags.fragment("diamond.and.explicit.params", t));
   805             return types.createErrorType(t);
   806         } else {
   807             return t;
   808         }
   809     }
   811     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   812         MethodSymbol m = tree.sym;
   813         if (!allowSimplifiedVarargs) return;
   814         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   815         Type varargElemType = null;
   816         if (m.isVarArgs()) {
   817             varargElemType = types.elemtype(tree.params.last().type);
   818         }
   819         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   820             if (varargElemType != null) {
   821                 log.error(tree,
   822                         "varargs.invalid.trustme.anno",
   823                         syms.trustMeType.tsym,
   824                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   825             } else {
   826                 log.error(tree,
   827                             "varargs.invalid.trustme.anno",
   828                             syms.trustMeType.tsym,
   829                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   830             }
   831         } else if (hasTrustMeAnno && varargElemType != null &&
   832                             types.isReifiable(varargElemType)) {
   833             warnUnsafeVararg(tree,
   834                             "varargs.redundant.trustme.anno",
   835                             syms.trustMeType.tsym,
   836                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   837         }
   838         else if (!hasTrustMeAnno && varargElemType != null &&
   839                 !types.isReifiable(varargElemType)) {
   840             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   841         }
   842     }
   843     //where
   844         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   845             return (s.flags() & VARARGS) != 0 &&
   846                 (s.isConstructor() ||
   847                     (s.flags() & (STATIC | FINAL)) != 0);
   848         }
   850     Type checkMethod(Type owntype,
   851                             Symbol sym,
   852                             Env<AttrContext> env,
   853                             final List<JCExpression> argtrees,
   854                             List<Type> argtypes,
   855                             boolean useVarargs,
   856                             boolean unchecked,
   857                             InferenceContext inferenceContext) {
   858         // System.out.println("call   : " + env.tree);
   859         // System.out.println("method : " + owntype);
   860         // System.out.println("actuals: " + argtypes);
   861         List<Type> formals = owntype.getParameterTypes();
   862         Type last = useVarargs ? formals.last() : null;
   863         if (sym.name == names.init &&
   864                 sym.owner == syms.enumSym)
   865                 formals = formals.tail.tail;
   866         List<JCExpression> args = argtrees;
   867         DeferredAttr.DeferredTypeMap checkDeferredMap =
   868                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   869         if (args != null) {
   870             //this is null when type-checking a method reference
   871             while (formals.head != last) {
   872                 JCTree arg = args.head;
   873                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   874                 assertConvertible(arg, arg.type, formals.head, warn);
   875                 args = args.tail;
   876                 formals = formals.tail;
   877             }
   878             if (useVarargs) {
   879                 Type varArg = types.elemtype(last);
   880                 while (args.tail != null) {
   881                     JCTree arg = args.head;
   882                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   883                     assertConvertible(arg, arg.type, varArg, warn);
   884                     args = args.tail;
   885                 }
   886             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   887                 // non-varargs call to varargs method
   888                 Type varParam = owntype.getParameterTypes().last();
   889                 Type lastArg = checkDeferredMap.apply(argtypes.last());
   890                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   891                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   892                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   893                             types.elemtype(varParam), varParam);
   894             }
   895         }
   896         if (unchecked) {
   897             warnUnchecked(env.tree.pos(),
   898                     "unchecked.meth.invocation.applied",
   899                     kindName(sym),
   900                     sym.name,
   901                     rs.methodArguments(sym.type.getParameterTypes()),
   902                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   903                     kindName(sym.location()),
   904                     sym.location());
   905            owntype = new MethodType(owntype.getParameterTypes(),
   906                    types.erasure(owntype.getReturnType()),
   907                    types.erasure(owntype.getThrownTypes()),
   908                    syms.methodClass);
   909         }
   910         if (useVarargs) {
   911             Type argtype = owntype.getParameterTypes().last();
   912             if (!types.isReifiable(argtype) &&
   913                     (!allowSimplifiedVarargs ||
   914                     sym.attribute(syms.trustMeType.tsym) == null ||
   915                     !isTrustMeAllowedOnMethod(sym))) {
   916                 warnUnchecked(env.tree.pos(),
   917                                   "unchecked.generic.array.creation",
   918                                   argtype);
   919             }
   920             if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
   921                 setVarargsElement(env, types.elemtype(argtype), inferenceContext);
   922             }
   923          }
   924          PolyKind pkind = (sym.type.hasTag(FORALL) &&
   925                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
   926                  PolyKind.POLY : PolyKind.STANDALONE;
   927          TreeInfo.setPolyKind(env.tree, pkind);
   928          return owntype;
   929     }
   930     //where
   931         private void setVarargsElement(final Env<AttrContext> env, final Type elemtype, InferenceContext inferenceContext) {
   932             if (inferenceContext.free(elemtype)) {
   933                 inferenceContext.addFreeTypeListener(List.of(elemtype), new FreeTypeListener() {
   934                     public void typesInferred(InferenceContext inferenceContext) {
   935                         setVarargsElement(env, inferenceContext.asInstType(elemtype), inferenceContext);
   936                     }
   937                 });
   938             }
   939             TreeInfo.setVarargsElement(env.tree, elemtype);
   940         }
   942         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   943             if (types.isConvertible(actual, formal, warn))
   944                 return;
   946             if (formal.isCompound()
   947                 && types.isSubtype(actual, types.supertype(formal))
   948                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   949                 return;
   950         }
   952     /**
   953      * Check that type 't' is a valid instantiation of a generic class
   954      * (see JLS 4.5)
   955      *
   956      * @param t class type to be checked
   957      * @return true if 't' is well-formed
   958      */
   959     public boolean checkValidGenericType(Type t) {
   960         return firstIncompatibleTypeArg(t) == null;
   961     }
   962     //WHERE
   963         private Type firstIncompatibleTypeArg(Type type) {
   964             List<Type> formals = type.tsym.type.allparams();
   965             List<Type> actuals = type.allparams();
   966             List<Type> args = type.getTypeArguments();
   967             List<Type> forms = type.tsym.type.getTypeArguments();
   968             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   970             // For matching pairs of actual argument types `a' and
   971             // formal type parameters with declared bound `b' ...
   972             while (args.nonEmpty() && forms.nonEmpty()) {
   973                 // exact type arguments needs to know their
   974                 // bounds (for upper and lower bound
   975                 // calculations).  So we create new bounds where
   976                 // type-parameters are replaced with actuals argument types.
   977                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   978                 args = args.tail;
   979                 forms = forms.tail;
   980             }
   982             args = type.getTypeArguments();
   983             List<Type> tvars_cap = types.substBounds(formals,
   984                                       formals,
   985                                       types.capture(type).allparams());
   986             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   987                 // Let the actual arguments know their bound
   988                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   989                 args = args.tail;
   990                 tvars_cap = tvars_cap.tail;
   991             }
   993             args = type.getTypeArguments();
   994             List<Type> bounds = bounds_buf.toList();
   996             while (args.nonEmpty() && bounds.nonEmpty()) {
   997                 Type actual = args.head;
   998                 if (!isTypeArgErroneous(actual) &&
   999                         !bounds.head.isErroneous() &&
  1000                         !checkExtends(actual, bounds.head)) {
  1001                     return args.head;
  1003                 args = args.tail;
  1004                 bounds = bounds.tail;
  1007             args = type.getTypeArguments();
  1008             bounds = bounds_buf.toList();
  1010             for (Type arg : types.capture(type).getTypeArguments()) {
  1011                 if (arg.hasTag(TYPEVAR) &&
  1012                         arg.getUpperBound().isErroneous() &&
  1013                         !bounds.head.isErroneous() &&
  1014                         !isTypeArgErroneous(args.head)) {
  1015                     return args.head;
  1017                 bounds = bounds.tail;
  1018                 args = args.tail;
  1021             return null;
  1023         //where
  1024         boolean isTypeArgErroneous(Type t) {
  1025             return isTypeArgErroneous.visit(t);
  1028         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1029             public Boolean visitType(Type t, Void s) {
  1030                 return t.isErroneous();
  1032             @Override
  1033             public Boolean visitTypeVar(TypeVar t, Void s) {
  1034                 return visit(t.getUpperBound());
  1036             @Override
  1037             public Boolean visitCapturedType(CapturedType t, Void s) {
  1038                 return visit(t.getUpperBound()) ||
  1039                         visit(t.getLowerBound());
  1041             @Override
  1042             public Boolean visitWildcardType(WildcardType t, Void s) {
  1043                 return visit(t.type);
  1045         };
  1047     /** Check that given modifiers are legal for given symbol and
  1048      *  return modifiers together with any implicit modifiers for that symbol.
  1049      *  Warning: we can't use flags() here since this method
  1050      *  is called during class enter, when flags() would cause a premature
  1051      *  completion.
  1052      *  @param pos           Position to be used for error reporting.
  1053      *  @param flags         The set of modifiers given in a definition.
  1054      *  @param sym           The defined symbol.
  1055      */
  1056     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1057         long mask;
  1058         long implicit = 0;
  1059         switch (sym.kind) {
  1060         case VAR:
  1061             if (sym.owner.kind != TYP)
  1062                 mask = LocalVarFlags;
  1063             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1064                 mask = implicit = InterfaceVarFlags;
  1065             else
  1066                 mask = VarFlags;
  1067             break;
  1068         case MTH:
  1069             if (sym.name == names.init) {
  1070                 if ((sym.owner.flags_field & ENUM) != 0) {
  1071                     // enum constructors cannot be declared public or
  1072                     // protected and must be implicitly or explicitly
  1073                     // private
  1074                     implicit = PRIVATE;
  1075                     mask = PRIVATE;
  1076                 } else
  1077                     mask = ConstructorFlags;
  1078             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1079                 if ((flags & (DEFAULT | STATIC)) != 0) {
  1080                     mask = InterfaceMethodMask;
  1081                     implicit = PUBLIC;
  1082                     if ((flags & DEFAULT) != 0) {
  1083                         implicit |= ABSTRACT;
  1085                 } else {
  1086                     mask = implicit = InterfaceMethodFlags;
  1089             else {
  1090                 mask = MethodFlags;
  1092             // Imply STRICTFP if owner has STRICTFP set.
  1093             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
  1094                 ((flags) & Flags.DEFAULT) != 0)
  1095                 implicit |= sym.owner.flags_field & STRICTFP;
  1096             break;
  1097         case TYP:
  1098             if (sym.isLocal()) {
  1099                 mask = LocalClassFlags;
  1100                 if (sym.name.isEmpty()) { // Anonymous class
  1101                     // Anonymous classes in static methods are themselves static;
  1102                     // that's why we admit STATIC here.
  1103                     mask |= STATIC;
  1104                     // JLS: Anonymous classes are final.
  1105                     implicit |= FINAL;
  1107                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1108                     (flags & ENUM) != 0)
  1109                     log.error(pos, "enums.must.be.static");
  1110             } else if (sym.owner.kind == TYP) {
  1111                 mask = MemberClassFlags;
  1112                 if (sym.owner.owner.kind == PCK ||
  1113                     (sym.owner.flags_field & STATIC) != 0)
  1114                     mask |= STATIC;
  1115                 else if ((flags & ENUM) != 0)
  1116                     log.error(pos, "enums.must.be.static");
  1117                 // Nested interfaces and enums are always STATIC (Spec ???)
  1118                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1119             } else {
  1120                 mask = ClassFlags;
  1122             // Interfaces are always ABSTRACT
  1123             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1125             if ((flags & ENUM) != 0) {
  1126                 // enums can't be declared abstract or final
  1127                 mask &= ~(ABSTRACT | FINAL);
  1128                 implicit |= implicitEnumFinalFlag(tree);
  1130             // Imply STRICTFP if owner has STRICTFP set.
  1131             implicit |= sym.owner.flags_field & STRICTFP;
  1132             break;
  1133         default:
  1134             throw new AssertionError();
  1136         long illegal = flags & ExtendedStandardFlags & ~mask;
  1137         if (illegal != 0) {
  1138             if ((illegal & INTERFACE) != 0) {
  1139                 log.error(pos, "intf.not.allowed.here");
  1140                 mask |= INTERFACE;
  1142             else {
  1143                 log.error(pos,
  1144                           "mod.not.allowed.here", asFlagSet(illegal));
  1147         else if ((sym.kind == TYP ||
  1148                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1149                   // in the presence of inner classes. Should it be deleted here?
  1150                   checkDisjoint(pos, flags,
  1151                                 ABSTRACT,
  1152                                 PRIVATE | STATIC | DEFAULT))
  1153                  &&
  1154                  checkDisjoint(pos, flags,
  1155                                 STATIC,
  1156                                 DEFAULT)
  1157                  &&
  1158                  checkDisjoint(pos, flags,
  1159                                ABSTRACT | INTERFACE,
  1160                                FINAL | NATIVE | SYNCHRONIZED)
  1161                  &&
  1162                  checkDisjoint(pos, flags,
  1163                                PUBLIC,
  1164                                PRIVATE | PROTECTED)
  1165                  &&
  1166                  checkDisjoint(pos, flags,
  1167                                PRIVATE,
  1168                                PUBLIC | PROTECTED)
  1169                  &&
  1170                  checkDisjoint(pos, flags,
  1171                                FINAL,
  1172                                VOLATILE)
  1173                  &&
  1174                  (sym.kind == TYP ||
  1175                   checkDisjoint(pos, flags,
  1176                                 ABSTRACT | NATIVE,
  1177                                 STRICTFP))) {
  1178             // skip
  1180         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1184     /** Determine if this enum should be implicitly final.
  1186      *  If the enum has no specialized enum contants, it is final.
  1188      *  If the enum does have specialized enum contants, it is
  1189      *  <i>not</i> final.
  1190      */
  1191     private long implicitEnumFinalFlag(JCTree tree) {
  1192         if (!tree.hasTag(CLASSDEF)) return 0;
  1193         class SpecialTreeVisitor extends JCTree.Visitor {
  1194             boolean specialized;
  1195             SpecialTreeVisitor() {
  1196                 this.specialized = false;
  1197             };
  1199             @Override
  1200             public void visitTree(JCTree tree) { /* no-op */ }
  1202             @Override
  1203             public void visitVarDef(JCVariableDecl tree) {
  1204                 if ((tree.mods.flags & ENUM) != 0) {
  1205                     if (tree.init instanceof JCNewClass &&
  1206                         ((JCNewClass) tree.init).def != null) {
  1207                         specialized = true;
  1213         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1214         JCClassDecl cdef = (JCClassDecl) tree;
  1215         for (JCTree defs: cdef.defs) {
  1216             defs.accept(sts);
  1217             if (sts.specialized) return 0;
  1219         return FINAL;
  1222 /* *************************************************************************
  1223  * Type Validation
  1224  **************************************************************************/
  1226     /** Validate a type expression. That is,
  1227      *  check that all type arguments of a parametric type are within
  1228      *  their bounds. This must be done in a second phase after type attribution
  1229      *  since a class might have a subclass as type parameter bound. E.g:
  1231      *  <pre>{@code
  1232      *  class B<A extends C> { ... }
  1233      *  class C extends B<C> { ... }
  1234      *  }</pre>
  1236      *  and we can't make sure that the bound is already attributed because
  1237      *  of possible cycles.
  1239      * Visitor method: Validate a type expression, if it is not null, catching
  1240      *  and reporting any completion failures.
  1241      */
  1242     void validate(JCTree tree, Env<AttrContext> env) {
  1243         validate(tree, env, true);
  1245     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1246         new Validator(env).validateTree(tree, checkRaw, true);
  1249     /** Visitor method: Validate a list of type expressions.
  1250      */
  1251     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1252         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1253             validate(l.head, env);
  1256     /** A visitor class for type validation.
  1257      */
  1258     class Validator extends JCTree.Visitor {
  1260         boolean isOuter;
  1261         Env<AttrContext> env;
  1263         Validator(Env<AttrContext> env) {
  1264             this.env = env;
  1267         @Override
  1268         public void visitTypeArray(JCArrayTypeTree tree) {
  1269             tree.elemtype.accept(this);
  1272         @Override
  1273         public void visitTypeApply(JCTypeApply tree) {
  1274             if (tree.type.hasTag(CLASS)) {
  1275                 List<JCExpression> args = tree.arguments;
  1276                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1278                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1279                 if (incompatibleArg != null) {
  1280                     for (JCTree arg : tree.arguments) {
  1281                         if (arg.type == incompatibleArg) {
  1282                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1284                         forms = forms.tail;
  1288                 forms = tree.type.tsym.type.getTypeArguments();
  1290                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1292                 // For matching pairs of actual argument types `a' and
  1293                 // formal type parameters with declared bound `b' ...
  1294                 while (args.nonEmpty() && forms.nonEmpty()) {
  1295                     validateTree(args.head,
  1296                             !(isOuter && is_java_lang_Class),
  1297                             false);
  1298                     args = args.tail;
  1299                     forms = forms.tail;
  1302                 // Check that this type is either fully parameterized, or
  1303                 // not parameterized at all.
  1304                 if (tree.type.getEnclosingType().isRaw())
  1305                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1306                 if (tree.clazz.hasTag(SELECT))
  1307                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1311         @Override
  1312         public void visitTypeParameter(JCTypeParameter tree) {
  1313             validateTrees(tree.bounds, true, isOuter);
  1314             checkClassBounds(tree.pos(), tree.type);
  1317         @Override
  1318         public void visitWildcard(JCWildcard tree) {
  1319             if (tree.inner != null)
  1320                 validateTree(tree.inner, true, isOuter);
  1323         @Override
  1324         public void visitSelect(JCFieldAccess tree) {
  1325             if (tree.type.hasTag(CLASS)) {
  1326                 visitSelectInternal(tree);
  1328                 // Check that this type is either fully parameterized, or
  1329                 // not parameterized at all.
  1330                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1331                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1335         public void visitSelectInternal(JCFieldAccess tree) {
  1336             if (tree.type.tsym.isStatic() &&
  1337                 tree.selected.type.isParameterized()) {
  1338                 // The enclosing type is not a class, so we are
  1339                 // looking at a static member type.  However, the
  1340                 // qualifying expression is parameterized.
  1341                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1342             } else {
  1343                 // otherwise validate the rest of the expression
  1344                 tree.selected.accept(this);
  1348         @Override
  1349         public void visitAnnotatedType(JCAnnotatedType tree) {
  1350             tree.underlyingType.accept(this);
  1353         /** Default visitor method: do nothing.
  1354          */
  1355         @Override
  1356         public void visitTree(JCTree tree) {
  1359         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1360             try {
  1361                 if (tree != null) {
  1362                     this.isOuter = isOuter;
  1363                     tree.accept(this);
  1364                     if (checkRaw)
  1365                         checkRaw(tree, env);
  1367             } catch (CompletionFailure ex) {
  1368                 completionError(tree.pos(), ex);
  1372         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1373             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1374                 validateTree(l.head, checkRaw, isOuter);
  1378     void checkRaw(JCTree tree, Env<AttrContext> env) {
  1379         if (lint.isEnabled(LintCategory.RAW) &&
  1380             tree.type.hasTag(CLASS) &&
  1381             !TreeInfo.isDiamond(tree) &&
  1382             !withinAnonConstr(env) &&
  1383             tree.type.isRaw()) {
  1384             log.warning(LintCategory.RAW,
  1385                     tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1388     //where
  1389         private boolean withinAnonConstr(Env<AttrContext> env) {
  1390             return env.enclClass.name.isEmpty() &&
  1391                     env.enclMethod != null && env.enclMethod.name == names.init;
  1394 /* *************************************************************************
  1395  * Exception checking
  1396  **************************************************************************/
  1398     /* The following methods treat classes as sets that contain
  1399      * the class itself and all their subclasses
  1400      */
  1402     /** Is given type a subtype of some of the types in given list?
  1403      */
  1404     boolean subset(Type t, List<Type> ts) {
  1405         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1406             if (types.isSubtype(t, l.head)) return true;
  1407         return false;
  1410     /** Is given type a subtype or supertype of
  1411      *  some of the types in given list?
  1412      */
  1413     boolean intersects(Type t, List<Type> ts) {
  1414         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1415             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1416         return false;
  1419     /** Add type set to given type list, unless it is a subclass of some class
  1420      *  in the list.
  1421      */
  1422     List<Type> incl(Type t, List<Type> ts) {
  1423         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1426     /** Remove type set from type set list.
  1427      */
  1428     List<Type> excl(Type t, List<Type> ts) {
  1429         if (ts.isEmpty()) {
  1430             return ts;
  1431         } else {
  1432             List<Type> ts1 = excl(t, ts.tail);
  1433             if (types.isSubtype(ts.head, t)) return ts1;
  1434             else if (ts1 == ts.tail) return ts;
  1435             else return ts1.prepend(ts.head);
  1439     /** Form the union of two type set lists.
  1440      */
  1441     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1442         List<Type> ts = ts1;
  1443         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1444             ts = incl(l.head, ts);
  1445         return ts;
  1448     /** Form the difference of two type lists.
  1449      */
  1450     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1451         List<Type> ts = ts1;
  1452         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1453             ts = excl(l.head, ts);
  1454         return ts;
  1457     /** Form the intersection of two type lists.
  1458      */
  1459     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1460         List<Type> ts = List.nil();
  1461         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1462             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1463         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1464             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1465         return ts;
  1468     /** Is exc an exception symbol that need not be declared?
  1469      */
  1470     boolean isUnchecked(ClassSymbol exc) {
  1471         return
  1472             exc.kind == ERR ||
  1473             exc.isSubClass(syms.errorType.tsym, types) ||
  1474             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1477     /** Is exc an exception type that need not be declared?
  1478      */
  1479     boolean isUnchecked(Type exc) {
  1480         return
  1481             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1482             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1483             exc.hasTag(BOT);
  1486     /** Same, but handling completion failures.
  1487      */
  1488     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1489         try {
  1490             return isUnchecked(exc);
  1491         } catch (CompletionFailure ex) {
  1492             completionError(pos, ex);
  1493             return true;
  1497     /** Is exc handled by given exception list?
  1498      */
  1499     boolean isHandled(Type exc, List<Type> handled) {
  1500         return isUnchecked(exc) || subset(exc, handled);
  1503     /** Return all exceptions in thrown list that are not in handled list.
  1504      *  @param thrown     The list of thrown exceptions.
  1505      *  @param handled    The list of handled exceptions.
  1506      */
  1507     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1508         List<Type> unhandled = List.nil();
  1509         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1510             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1511         return unhandled;
  1514 /* *************************************************************************
  1515  * Overriding/Implementation checking
  1516  **************************************************************************/
  1518     /** The level of access protection given by a flag set,
  1519      *  where PRIVATE is highest and PUBLIC is lowest.
  1520      */
  1521     static int protection(long flags) {
  1522         switch ((short)(flags & AccessFlags)) {
  1523         case PRIVATE: return 3;
  1524         case PROTECTED: return 1;
  1525         default:
  1526         case PUBLIC: return 0;
  1527         case 0: return 2;
  1531     /** A customized "cannot override" error message.
  1532      *  @param m      The overriding method.
  1533      *  @param other  The overridden method.
  1534      *  @return       An internationalized string.
  1535      */
  1536     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1537         String key;
  1538         if ((other.owner.flags() & INTERFACE) == 0)
  1539             key = "cant.override";
  1540         else if ((m.owner.flags() & INTERFACE) == 0)
  1541             key = "cant.implement";
  1542         else
  1543             key = "clashes.with";
  1544         return diags.fragment(key, m, m.location(), other, other.location());
  1547     /** A customized "override" warning message.
  1548      *  @param m      The overriding method.
  1549      *  @param other  The overridden method.
  1550      *  @return       An internationalized string.
  1551      */
  1552     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1553         String key;
  1554         if ((other.owner.flags() & INTERFACE) == 0)
  1555             key = "unchecked.override";
  1556         else if ((m.owner.flags() & INTERFACE) == 0)
  1557             key = "unchecked.implement";
  1558         else
  1559             key = "unchecked.clash.with";
  1560         return diags.fragment(key, m, m.location(), other, other.location());
  1563     /** A customized "override" warning message.
  1564      *  @param m      The overriding method.
  1565      *  @param other  The overridden method.
  1566      *  @return       An internationalized string.
  1567      */
  1568     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1569         String key;
  1570         if ((other.owner.flags() & INTERFACE) == 0)
  1571             key = "varargs.override";
  1572         else  if ((m.owner.flags() & INTERFACE) == 0)
  1573             key = "varargs.implement";
  1574         else
  1575             key = "varargs.clash.with";
  1576         return diags.fragment(key, m, m.location(), other, other.location());
  1579     /** Check that this method conforms with overridden method 'other'.
  1580      *  where `origin' is the class where checking started.
  1581      *  Complications:
  1582      *  (1) Do not check overriding of synthetic methods
  1583      *      (reason: they might be final).
  1584      *      todo: check whether this is still necessary.
  1585      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1586      *      than the method it implements. Augment the proxy methods with the
  1587      *      undeclared exceptions in this case.
  1588      *  (3) When generics are enabled, admit the case where an interface proxy
  1589      *      has a result type
  1590      *      extended by the result type of the method it implements.
  1591      *      Change the proxies result type to the smaller type in this case.
  1593      *  @param tree         The tree from which positions
  1594      *                      are extracted for errors.
  1595      *  @param m            The overriding method.
  1596      *  @param other        The overridden method.
  1597      *  @param origin       The class of which the overriding method
  1598      *                      is a member.
  1599      */
  1600     void checkOverride(JCTree tree,
  1601                        MethodSymbol m,
  1602                        MethodSymbol other,
  1603                        ClassSymbol origin) {
  1604         // Don't check overriding of synthetic methods or by bridge methods.
  1605         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1606             return;
  1609         // Error if static method overrides instance method (JLS 8.4.6.2).
  1610         if ((m.flags() & STATIC) != 0 &&
  1611                    (other.flags() & STATIC) == 0) {
  1612             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1613                       cannotOverride(m, other));
  1614             m.flags_field |= BAD_OVERRIDE;
  1615             return;
  1618         // Error if instance method overrides static or final
  1619         // method (JLS 8.4.6.1).
  1620         if ((other.flags() & FINAL) != 0 ||
  1621                  (m.flags() & STATIC) == 0 &&
  1622                  (other.flags() & STATIC) != 0) {
  1623             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1624                       cannotOverride(m, other),
  1625                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1626             m.flags_field |= BAD_OVERRIDE;
  1627             return;
  1630         if ((m.owner.flags() & ANNOTATION) != 0) {
  1631             // handled in validateAnnotationMethod
  1632             return;
  1635         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1636         if ((origin.flags() & INTERFACE) == 0 &&
  1637                  protection(m.flags()) > protection(other.flags())) {
  1638             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1639                       cannotOverride(m, other),
  1640                       other.flags() == 0 ?
  1641                           Flag.PACKAGE :
  1642                           asFlagSet(other.flags() & AccessFlags));
  1643             m.flags_field |= BAD_OVERRIDE;
  1644             return;
  1647         Type mt = types.memberType(origin.type, m);
  1648         Type ot = types.memberType(origin.type, other);
  1649         // Error if overriding result type is different
  1650         // (or, in the case of generics mode, not a subtype) of
  1651         // overridden result type. We have to rename any type parameters
  1652         // before comparing types.
  1653         List<Type> mtvars = mt.getTypeArguments();
  1654         List<Type> otvars = ot.getTypeArguments();
  1655         Type mtres = mt.getReturnType();
  1656         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1658         overrideWarner.clear();
  1659         boolean resultTypesOK =
  1660             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1661         if (!resultTypesOK) {
  1662             if (!allowCovariantReturns &&
  1663                 m.owner != origin &&
  1664                 m.owner.isSubClass(other.owner, types)) {
  1665                 // allow limited interoperability with covariant returns
  1666             } else {
  1667                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1668                           "override.incompatible.ret",
  1669                           cannotOverride(m, other),
  1670                           mtres, otres);
  1671                 m.flags_field |= BAD_OVERRIDE;
  1672                 return;
  1674         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1675             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1676                     "override.unchecked.ret",
  1677                     uncheckedOverrides(m, other),
  1678                     mtres, otres);
  1681         // Error if overriding method throws an exception not reported
  1682         // by overridden method.
  1683         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1684         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1685         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1686         if (unhandledErased.nonEmpty()) {
  1687             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1688                       "override.meth.doesnt.throw",
  1689                       cannotOverride(m, other),
  1690                       unhandledUnerased.head);
  1691             m.flags_field |= BAD_OVERRIDE;
  1692             return;
  1694         else if (unhandledUnerased.nonEmpty()) {
  1695             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1696                           "override.unchecked.thrown",
  1697                          cannotOverride(m, other),
  1698                          unhandledUnerased.head);
  1699             return;
  1702         // Optional warning if varargs don't agree
  1703         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1704             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1705             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1706                         ((m.flags() & Flags.VARARGS) != 0)
  1707                         ? "override.varargs.missing"
  1708                         : "override.varargs.extra",
  1709                         varargsOverrides(m, other));
  1712         // Warn if instance method overrides bridge method (compiler spec ??)
  1713         if ((other.flags() & BRIDGE) != 0) {
  1714             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1715                         uncheckedOverrides(m, other));
  1718         // Warn if a deprecated method overridden by a non-deprecated one.
  1719         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1720             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1723     // where
  1724         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1725             // If the method, m, is defined in an interface, then ignore the issue if the method
  1726             // is only inherited via a supertype and also implemented in the supertype,
  1727             // because in that case, we will rediscover the issue when examining the method
  1728             // in the supertype.
  1729             // If the method, m, is not defined in an interface, then the only time we need to
  1730             // address the issue is when the method is the supertype implemementation: any other
  1731             // case, we will have dealt with when examining the supertype classes
  1732             ClassSymbol mc = m.enclClass();
  1733             Type st = types.supertype(origin.type);
  1734             if (!st.hasTag(CLASS))
  1735                 return true;
  1736             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1738             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1739                 List<Type> intfs = types.interfaces(origin.type);
  1740                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1742             else
  1743                 return (stimpl != m);
  1747     // used to check if there were any unchecked conversions
  1748     Warner overrideWarner = new Warner();
  1750     /** Check that a class does not inherit two concrete methods
  1751      *  with the same signature.
  1752      *  @param pos          Position to be used for error reporting.
  1753      *  @param site         The class type to be checked.
  1754      */
  1755     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1756         Type sup = types.supertype(site);
  1757         if (!sup.hasTag(CLASS)) return;
  1759         for (Type t1 = sup;
  1760              t1.tsym.type.isParameterized();
  1761              t1 = types.supertype(t1)) {
  1762             for (Scope.Entry e1 = t1.tsym.members().elems;
  1763                  e1 != null;
  1764                  e1 = e1.sibling) {
  1765                 Symbol s1 = e1.sym;
  1766                 if (s1.kind != MTH ||
  1767                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1768                     !s1.isInheritedIn(site.tsym, types) ||
  1769                     ((MethodSymbol)s1).implementation(site.tsym,
  1770                                                       types,
  1771                                                       true) != s1)
  1772                     continue;
  1773                 Type st1 = types.memberType(t1, s1);
  1774                 int s1ArgsLength = st1.getParameterTypes().length();
  1775                 if (st1 == s1.type) continue;
  1777                 for (Type t2 = sup;
  1778                      t2.hasTag(CLASS);
  1779                      t2 = types.supertype(t2)) {
  1780                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1781                          e2.scope != null;
  1782                          e2 = e2.next()) {
  1783                         Symbol s2 = e2.sym;
  1784                         if (s2 == s1 ||
  1785                             s2.kind != MTH ||
  1786                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1787                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1788                             !s2.isInheritedIn(site.tsym, types) ||
  1789                             ((MethodSymbol)s2).implementation(site.tsym,
  1790                                                               types,
  1791                                                               true) != s2)
  1792                             continue;
  1793                         Type st2 = types.memberType(t2, s2);
  1794                         if (types.overrideEquivalent(st1, st2))
  1795                             log.error(pos, "concrete.inheritance.conflict",
  1796                                       s1, t1, s2, t2, sup);
  1803     /** Check that classes (or interfaces) do not each define an abstract
  1804      *  method with same name and arguments but incompatible return types.
  1805      *  @param pos          Position to be used for error reporting.
  1806      *  @param t1           The first argument type.
  1807      *  @param t2           The second argument type.
  1808      */
  1809     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1810                                             Type t1,
  1811                                             Type t2) {
  1812         return checkCompatibleAbstracts(pos, t1, t2,
  1813                                         types.makeCompoundType(t1, t2));
  1816     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1817                                             Type t1,
  1818                                             Type t2,
  1819                                             Type site) {
  1820         return firstIncompatibility(pos, t1, t2, site) == null;
  1823     /** Return the first method which is defined with same args
  1824      *  but different return types in two given interfaces, or null if none
  1825      *  exists.
  1826      *  @param t1     The first type.
  1827      *  @param t2     The second type.
  1828      *  @param site   The most derived type.
  1829      *  @returns symbol from t2 that conflicts with one in t1.
  1830      */
  1831     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1832         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1833         closure(t1, interfaces1);
  1834         Map<TypeSymbol,Type> interfaces2;
  1835         if (t1 == t2)
  1836             interfaces2 = interfaces1;
  1837         else
  1838             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1840         for (Type t3 : interfaces1.values()) {
  1841             for (Type t4 : interfaces2.values()) {
  1842                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1843                 if (s != null) return s;
  1846         return null;
  1849     /** Compute all the supertypes of t, indexed by type symbol. */
  1850     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1851         if (!t.hasTag(CLASS)) return;
  1852         if (typeMap.put(t.tsym, t) == null) {
  1853             closure(types.supertype(t), typeMap);
  1854             for (Type i : types.interfaces(t))
  1855                 closure(i, typeMap);
  1859     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1860     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1861         if (!t.hasTag(CLASS)) return;
  1862         if (typesSkip.get(t.tsym) != null) return;
  1863         if (typeMap.put(t.tsym, t) == null) {
  1864             closure(types.supertype(t), typesSkip, typeMap);
  1865             for (Type i : types.interfaces(t))
  1866                 closure(i, typesSkip, typeMap);
  1870     /** Return the first method in t2 that conflicts with a method from t1. */
  1871     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1872         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1873             Symbol s1 = e1.sym;
  1874             Type st1 = null;
  1875             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1876                     (s1.flags() & SYNTHETIC) != 0) continue;
  1877             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1878             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1879             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1880                 Symbol s2 = e2.sym;
  1881                 if (s1 == s2) continue;
  1882                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1883                         (s2.flags() & SYNTHETIC) != 0) continue;
  1884                 if (st1 == null) st1 = types.memberType(t1, s1);
  1885                 Type st2 = types.memberType(t2, s2);
  1886                 if (types.overrideEquivalent(st1, st2)) {
  1887                     List<Type> tvars1 = st1.getTypeArguments();
  1888                     List<Type> tvars2 = st2.getTypeArguments();
  1889                     Type rt1 = st1.getReturnType();
  1890                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1891                     boolean compat =
  1892                         types.isSameType(rt1, rt2) ||
  1893                         !rt1.isPrimitiveOrVoid() &&
  1894                         !rt2.isPrimitiveOrVoid() &&
  1895                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1896                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1897                          checkCommonOverriderIn(s1,s2,site);
  1898                     if (!compat) {
  1899                         log.error(pos, "types.incompatible.diff.ret",
  1900                             t1, t2, s2.name +
  1901                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1902                         return s2;
  1904                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1905                         !checkCommonOverriderIn(s1, s2, site)) {
  1906                     log.error(pos,
  1907                             "name.clash.same.erasure.no.override",
  1908                             s1, s1.location(),
  1909                             s2, s2.location());
  1910                     return s2;
  1914         return null;
  1916     //WHERE
  1917     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1918         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1919         Type st1 = types.memberType(site, s1);
  1920         Type st2 = types.memberType(site, s2);
  1921         closure(site, supertypes);
  1922         for (Type t : supertypes.values()) {
  1923             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1924                 Symbol s3 = e.sym;
  1925                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1926                 Type st3 = types.memberType(site,s3);
  1927                 if (types.overrideEquivalent(st3, st1) &&
  1928                         types.overrideEquivalent(st3, st2) &&
  1929                         types.returnTypeSubstitutable(st3, st1) &&
  1930                         types.returnTypeSubstitutable(st3, st2)) {
  1931                     return true;
  1935         return false;
  1938     /** Check that a given method conforms with any method it overrides.
  1939      *  @param tree         The tree from which positions are extracted
  1940      *                      for errors.
  1941      *  @param m            The overriding method.
  1942      */
  1943     void checkOverride(JCTree tree, MethodSymbol m) {
  1944         ClassSymbol origin = (ClassSymbol)m.owner;
  1945         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1946             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1947                 log.error(tree.pos(), "enum.no.finalize");
  1948                 return;
  1950         for (Type t = origin.type; t.hasTag(CLASS);
  1951              t = types.supertype(t)) {
  1952             if (t != origin.type) {
  1953                 checkOverride(tree, t, origin, m);
  1955             for (Type t2 : types.interfaces(t)) {
  1956                 checkOverride(tree, t2, origin, m);
  1961     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1962         TypeSymbol c = site.tsym;
  1963         Scope.Entry e = c.members().lookup(m.name);
  1964         while (e.scope != null) {
  1965             if (m.overrides(e.sym, origin, types, false)) {
  1966                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1967                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1970             e = e.next();
  1974     private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
  1975         public boolean accepts(Symbol s) {
  1976             return MethodSymbol.implementation_filter.accepts(s) &&
  1977                     (s.flags() & BAD_OVERRIDE) == 0;
  1980     };
  1982     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
  1983             ClassSymbol someClass) {
  1984         /* At present, annotations cannot possibly have a method that is override
  1985          * equivalent with Object.equals(Object) but in any case the condition is
  1986          * fine for completeness.
  1987          */
  1988         if (someClass == (ClassSymbol)syms.objectType.tsym ||
  1989             someClass.isInterface() || someClass.isEnum() ||
  1990             (someClass.flags() & ANNOTATION) != 0 ||
  1991             (someClass.flags() & ABSTRACT) != 0) return;
  1992         //anonymous inner classes implementing interfaces need especial treatment
  1993         if (someClass.isAnonymous()) {
  1994             List<Type> interfaces =  types.interfaces(someClass.type);
  1995             if (interfaces != null && !interfaces.isEmpty() &&
  1996                 interfaces.head.tsym == syms.comparatorType.tsym) return;
  1998         checkClassOverrideEqualsAndHash(pos, someClass);
  2001     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
  2002             ClassSymbol someClass) {
  2003         if (lint.isEnabled(LintCategory.OVERRIDES)) {
  2004             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
  2005                     .tsym.members().lookup(names.equals).sym;
  2006             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
  2007                     .tsym.members().lookup(names.hashCode).sym;
  2008             boolean overridesEquals = types.implementation(equalsAtObject,
  2009                 someClass, false, equalsHasCodeFilter).owner == someClass;
  2010             boolean overridesHashCode = types.implementation(hashCodeAtObject,
  2011                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
  2013             if (overridesEquals && !overridesHashCode) {
  2014                 log.warning(LintCategory.OVERRIDES, pos,
  2015                         "override.equals.but.not.hashcode", someClass);
  2020     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  2021         ClashFilter cf = new ClashFilter(origin.type);
  2022         return (cf.accepts(s1) &&
  2023                 cf.accepts(s2) &&
  2024                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  2028     /** Check that all abstract members of given class have definitions.
  2029      *  @param pos          Position to be used for error reporting.
  2030      *  @param c            The class.
  2031      */
  2032     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  2033         try {
  2034             MethodSymbol undef = firstUndef(c, c);
  2035             if (undef != null) {
  2036                 if ((c.flags() & ENUM) != 0 &&
  2037                     types.supertype(c.type).tsym == syms.enumSym &&
  2038                     (c.flags() & FINAL) == 0) {
  2039                     // add the ABSTRACT flag to an enum
  2040                     c.flags_field |= ABSTRACT;
  2041                 } else {
  2042                     MethodSymbol undef1 =
  2043                         new MethodSymbol(undef.flags(), undef.name,
  2044                                          types.memberType(c.type, undef), undef.owner);
  2045                     log.error(pos, "does.not.override.abstract",
  2046                               c, undef1, undef1.location());
  2049         } catch (CompletionFailure ex) {
  2050             completionError(pos, ex);
  2053 //where
  2054         /** Return first abstract member of class `c' that is not defined
  2055          *  in `impl', null if there is none.
  2056          */
  2057         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  2058             MethodSymbol undef = null;
  2059             // Do not bother to search in classes that are not abstract,
  2060             // since they cannot have abstract members.
  2061             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2062                 Scope s = c.members();
  2063                 for (Scope.Entry e = s.elems;
  2064                      undef == null && e != null;
  2065                      e = e.sibling) {
  2066                     if (e.sym.kind == MTH &&
  2067                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2068                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2069                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2070                         if (implmeth == null || implmeth == absmeth) {
  2071                             //look for default implementations
  2072                             if (allowDefaultMethods) {
  2073                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2074                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2075                                     implmeth = prov;
  2079                         if (implmeth == null || implmeth == absmeth) {
  2080                             undef = absmeth;
  2084                 if (undef == null) {
  2085                     Type st = types.supertype(c.type);
  2086                     if (st.hasTag(CLASS))
  2087                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2089                 for (List<Type> l = types.interfaces(c.type);
  2090                      undef == null && l.nonEmpty();
  2091                      l = l.tail) {
  2092                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2095             return undef;
  2098     void checkNonCyclicDecl(JCClassDecl tree) {
  2099         CycleChecker cc = new CycleChecker();
  2100         cc.scan(tree);
  2101         if (!cc.errorFound && !cc.partialCheck) {
  2102             tree.sym.flags_field |= ACYCLIC;
  2106     class CycleChecker extends TreeScanner {
  2108         List<Symbol> seenClasses = List.nil();
  2109         boolean errorFound = false;
  2110         boolean partialCheck = false;
  2112         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2113             if (sym != null && sym.kind == TYP) {
  2114                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2115                 if (classEnv != null) {
  2116                     DiagnosticSource prevSource = log.currentSource();
  2117                     try {
  2118                         log.useSource(classEnv.toplevel.sourcefile);
  2119                         scan(classEnv.tree);
  2121                     finally {
  2122                         log.useSource(prevSource.getFile());
  2124                 } else if (sym.kind == TYP) {
  2125                     checkClass(pos, sym, List.<JCTree>nil());
  2127             } else {
  2128                 //not completed yet
  2129                 partialCheck = true;
  2133         @Override
  2134         public void visitSelect(JCFieldAccess tree) {
  2135             super.visitSelect(tree);
  2136             checkSymbol(tree.pos(), tree.sym);
  2139         @Override
  2140         public void visitIdent(JCIdent tree) {
  2141             checkSymbol(tree.pos(), tree.sym);
  2144         @Override
  2145         public void visitTypeApply(JCTypeApply tree) {
  2146             scan(tree.clazz);
  2149         @Override
  2150         public void visitTypeArray(JCArrayTypeTree tree) {
  2151             scan(tree.elemtype);
  2154         @Override
  2155         public void visitClassDef(JCClassDecl tree) {
  2156             List<JCTree> supertypes = List.nil();
  2157             if (tree.getExtendsClause() != null) {
  2158                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2160             if (tree.getImplementsClause() != null) {
  2161                 for (JCTree intf : tree.getImplementsClause()) {
  2162                     supertypes = supertypes.prepend(intf);
  2165             checkClass(tree.pos(), tree.sym, supertypes);
  2168         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2169             if ((c.flags_field & ACYCLIC) != 0)
  2170                 return;
  2171             if (seenClasses.contains(c)) {
  2172                 errorFound = true;
  2173                 noteCyclic(pos, (ClassSymbol)c);
  2174             } else if (!c.type.isErroneous()) {
  2175                 try {
  2176                     seenClasses = seenClasses.prepend(c);
  2177                     if (c.type.hasTag(CLASS)) {
  2178                         if (supertypes.nonEmpty()) {
  2179                             scan(supertypes);
  2181                         else {
  2182                             ClassType ct = (ClassType)c.type;
  2183                             if (ct.supertype_field == null ||
  2184                                     ct.interfaces_field == null) {
  2185                                 //not completed yet
  2186                                 partialCheck = true;
  2187                                 return;
  2189                             checkSymbol(pos, ct.supertype_field.tsym);
  2190                             for (Type intf : ct.interfaces_field) {
  2191                                 checkSymbol(pos, intf.tsym);
  2194                         if (c.owner.kind == TYP) {
  2195                             checkSymbol(pos, c.owner);
  2198                 } finally {
  2199                     seenClasses = seenClasses.tail;
  2205     /** Check for cyclic references. Issue an error if the
  2206      *  symbol of the type referred to has a LOCKED flag set.
  2208      *  @param pos      Position to be used for error reporting.
  2209      *  @param t        The type referred to.
  2210      */
  2211     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2212         checkNonCyclicInternal(pos, t);
  2216     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2217         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2220     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2221         final TypeVar tv;
  2222         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2223             return;
  2224         if (seen.contains(t)) {
  2225             tv = (TypeVar)t;
  2226             tv.bound = types.createErrorType(t);
  2227             log.error(pos, "cyclic.inheritance", t);
  2228         } else if (t.hasTag(TYPEVAR)) {
  2229             tv = (TypeVar)t;
  2230             seen = seen.prepend(tv);
  2231             for (Type b : types.getBounds(tv))
  2232                 checkNonCyclic1(pos, b, seen);
  2236     /** Check for cyclic references. Issue an error if the
  2237      *  symbol of the type referred to has a LOCKED flag set.
  2239      *  @param pos      Position to be used for error reporting.
  2240      *  @param t        The type referred to.
  2241      *  @returns        True if the check completed on all attributed classes
  2242      */
  2243     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2244         boolean complete = true; // was the check complete?
  2245         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2246         Symbol c = t.tsym;
  2247         if ((c.flags_field & ACYCLIC) != 0) return true;
  2249         if ((c.flags_field & LOCKED) != 0) {
  2250             noteCyclic(pos, (ClassSymbol)c);
  2251         } else if (!c.type.isErroneous()) {
  2252             try {
  2253                 c.flags_field |= LOCKED;
  2254                 if (c.type.hasTag(CLASS)) {
  2255                     ClassType clazz = (ClassType)c.type;
  2256                     if (clazz.interfaces_field != null)
  2257                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2258                             complete &= checkNonCyclicInternal(pos, l.head);
  2259                     if (clazz.supertype_field != null) {
  2260                         Type st = clazz.supertype_field;
  2261                         if (st != null && st.hasTag(CLASS))
  2262                             complete &= checkNonCyclicInternal(pos, st);
  2264                     if (c.owner.kind == TYP)
  2265                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2267             } finally {
  2268                 c.flags_field &= ~LOCKED;
  2271         if (complete)
  2272             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2273         if (complete) c.flags_field |= ACYCLIC;
  2274         return complete;
  2277     /** Note that we found an inheritance cycle. */
  2278     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2279         log.error(pos, "cyclic.inheritance", c);
  2280         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2281             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2282         Type st = types.supertype(c.type);
  2283         if (st.hasTag(CLASS))
  2284             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2285         c.type = types.createErrorType(c, c.type);
  2286         c.flags_field |= ACYCLIC;
  2289     /**
  2290      * Check that functional interface methods would make sense when seen
  2291      * from the perspective of the implementing class
  2292      */
  2293     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2294         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2295         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2296         c.interfaces_field = List.of(types.removeWildcards(funcInterface));
  2297         c.supertype_field = syms.objectType;
  2298         c.tsym = csym;
  2299         csym.members_field = new Scope(csym);
  2300         Symbol descSym = types.findDescriptorSymbol(funcInterface.tsym);
  2301         Type descType = types.findDescriptorType(funcInterface);
  2302         csym.members_field.enter(new MethodSymbol(PUBLIC, descSym.name, descType, csym));
  2303         csym.completer = null;
  2304         checkImplementations(tree, csym, csym);
  2307     /** Check that all methods which implement some
  2308      *  method conform to the method they implement.
  2309      *  @param tree         The class definition whose members are checked.
  2310      */
  2311     void checkImplementations(JCClassDecl tree) {
  2312         checkImplementations(tree, tree.sym, tree.sym);
  2314     //where
  2315         /** Check that all methods which implement some
  2316          *  method in `ic' conform to the method they implement.
  2317          */
  2318         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2319             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2320                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2321                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2322                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2323                         if (e.sym.kind == MTH &&
  2324                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2325                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2326                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2327                             if (implmeth != null && implmeth != absmeth &&
  2328                                 (implmeth.owner.flags() & INTERFACE) ==
  2329                                 (origin.flags() & INTERFACE)) {
  2330                                 // don't check if implmeth is in a class, yet
  2331                                 // origin is an interface. This case arises only
  2332                                 // if implmeth is declared in Object. The reason is
  2333                                 // that interfaces really don't inherit from
  2334                                 // Object it's just that the compiler represents
  2335                                 // things that way.
  2336                                 checkOverride(tree, implmeth, absmeth, origin);
  2344     /** Check that all abstract methods implemented by a class are
  2345      *  mutually compatible.
  2346      *  @param pos          Position to be used for error reporting.
  2347      *  @param c            The class whose interfaces are checked.
  2348      */
  2349     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2350         List<Type> supertypes = types.interfaces(c);
  2351         Type supertype = types.supertype(c);
  2352         if (supertype.hasTag(CLASS) &&
  2353             (supertype.tsym.flags() & ABSTRACT) != 0)
  2354             supertypes = supertypes.prepend(supertype);
  2355         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2356             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2357                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2358                 return;
  2359             for (List<Type> m = supertypes; m != l; m = m.tail)
  2360                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2361                     return;
  2363         checkCompatibleConcretes(pos, c);
  2366     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2367         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2368             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2369                 // VM allows methods and variables with differing types
  2370                 if (sym.kind == e.sym.kind &&
  2371                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2372                     sym != e.sym &&
  2373                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2374                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2375                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2376                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2377                     return;
  2383     /** Check that all non-override equivalent methods accessible from 'site'
  2384      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2386      *  @param pos  Position to be used for error reporting.
  2387      *  @param site The class whose methods are checked.
  2388      *  @param sym  The method symbol to be checked.
  2389      */
  2390     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2391          ClashFilter cf = new ClashFilter(site);
  2392         //for each method m1 that is overridden (directly or indirectly)
  2393         //by method 'sym' in 'site'...
  2394         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2395             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2396              //...check each method m2 that is a member of 'site'
  2397              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2398                 if (m2 == m1) continue;
  2399                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2400                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2401                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2402                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2403                     sym.flags_field |= CLASH;
  2404                     String key = m1 == sym ?
  2405                             "name.clash.same.erasure.no.override" :
  2406                             "name.clash.same.erasure.no.override.1";
  2407                     log.error(pos,
  2408                             key,
  2409                             sym, sym.location(),
  2410                             m2, m2.location(),
  2411                             m1, m1.location());
  2412                     return;
  2420     /** Check that all static methods accessible from 'site' are
  2421      *  mutually compatible (JLS 8.4.8).
  2423      *  @param pos  Position to be used for error reporting.
  2424      *  @param site The class whose methods are checked.
  2425      *  @param sym  The method symbol to be checked.
  2426      */
  2427     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2428         ClashFilter cf = new ClashFilter(site);
  2429         //for each method m1 that is a member of 'site'...
  2430         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2431             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2432             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2433             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2434                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2435                 log.error(pos,
  2436                         "name.clash.same.erasure.no.hide",
  2437                         sym, sym.location(),
  2438                         s, s.location());
  2439                 return;
  2444      //where
  2445      private class ClashFilter implements Filter<Symbol> {
  2447          Type site;
  2449          ClashFilter(Type site) {
  2450              this.site = site;
  2453          boolean shouldSkip(Symbol s) {
  2454              return (s.flags() & CLASH) != 0 &&
  2455                 s.owner == site.tsym;
  2458          public boolean accepts(Symbol s) {
  2459              return s.kind == MTH &&
  2460                      (s.flags() & SYNTHETIC) == 0 &&
  2461                      !shouldSkip(s) &&
  2462                      s.isInheritedIn(site.tsym, types) &&
  2463                      !s.isConstructor();
  2467     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2468         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2469         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2470             Assert.check(m.kind == MTH);
  2471             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2472             if (prov.size() > 1) {
  2473                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2474                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2475                 for (MethodSymbol provSym : prov) {
  2476                     if ((provSym.flags() & DEFAULT) != 0) {
  2477                         defaults = defaults.append(provSym);
  2478                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2479                         abstracts = abstracts.append(provSym);
  2481                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2482                         //strong semantics - issue an error if two sibling interfaces
  2483                         //have two override-equivalent defaults - or if one is abstract
  2484                         //and the other is default
  2485                         String errKey;
  2486                         Symbol s1 = defaults.first();
  2487                         Symbol s2;
  2488                         if (defaults.size() > 1) {
  2489                             errKey = "types.incompatible.unrelated.defaults";
  2490                             s2 = defaults.toList().tail.head;
  2491                         } else {
  2492                             errKey = "types.incompatible.abstract.default";
  2493                             s2 = abstracts.first();
  2495                         log.error(pos, errKey,
  2496                                 Kinds.kindName(site.tsym), site,
  2497                                 m.name, types.memberType(site, m).getParameterTypes(),
  2498                                 s1.location(), s2.location());
  2499                         break;
  2506     //where
  2507      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2509          Type site;
  2511          DefaultMethodClashFilter(Type site) {
  2512              this.site = site;
  2515          public boolean accepts(Symbol s) {
  2516              return s.kind == MTH &&
  2517                      (s.flags() & DEFAULT) != 0 &&
  2518                      s.isInheritedIn(site.tsym, types) &&
  2519                      !s.isConstructor();
  2523     /** Report a conflict between a user symbol and a synthetic symbol.
  2524      */
  2525     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2526         if (!sym.type.isErroneous()) {
  2527             if (warnOnSyntheticConflicts) {
  2528                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2530             else {
  2531                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2536     /** Check that class c does not implement directly or indirectly
  2537      *  the same parameterized interface with two different argument lists.
  2538      *  @param pos          Position to be used for error reporting.
  2539      *  @param type         The type whose interfaces are checked.
  2540      */
  2541     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2542         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2544 //where
  2545         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2546          *  with their class symbol as key and their type as value. Make
  2547          *  sure no class is entered with two different types.
  2548          */
  2549         void checkClassBounds(DiagnosticPosition pos,
  2550                               Map<TypeSymbol,Type> seensofar,
  2551                               Type type) {
  2552             if (type.isErroneous()) return;
  2553             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2554                 Type it = l.head;
  2555                 Type oldit = seensofar.put(it.tsym, it);
  2556                 if (oldit != null) {
  2557                     List<Type> oldparams = oldit.allparams();
  2558                     List<Type> newparams = it.allparams();
  2559                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2560                         log.error(pos, "cant.inherit.diff.arg",
  2561                                   it.tsym, Type.toString(oldparams),
  2562                                   Type.toString(newparams));
  2564                 checkClassBounds(pos, seensofar, it);
  2566             Type st = types.supertype(type);
  2567             if (st != null) checkClassBounds(pos, seensofar, st);
  2570     /** Enter interface into into set.
  2571      *  If it existed already, issue a "repeated interface" error.
  2572      */
  2573     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2574         if (its.contains(it))
  2575             log.error(pos, "repeated.interface");
  2576         else {
  2577             its.add(it);
  2581 /* *************************************************************************
  2582  * Check annotations
  2583  **************************************************************************/
  2585     /**
  2586      * Recursively validate annotations values
  2587      */
  2588     void validateAnnotationTree(JCTree tree) {
  2589         class AnnotationValidator extends TreeScanner {
  2590             @Override
  2591             public void visitAnnotation(JCAnnotation tree) {
  2592                 if (!tree.type.isErroneous()) {
  2593                     super.visitAnnotation(tree);
  2594                     validateAnnotation(tree);
  2598         tree.accept(new AnnotationValidator());
  2601     /**
  2602      *  {@literal
  2603      *  Annotation types are restricted to primitives, String, an
  2604      *  enum, an annotation, Class, Class<?>, Class<? extends
  2605      *  Anything>, arrays of the preceding.
  2606      *  }
  2607      */
  2608     void validateAnnotationType(JCTree restype) {
  2609         // restype may be null if an error occurred, so don't bother validating it
  2610         if (restype != null) {
  2611             validateAnnotationType(restype.pos(), restype.type);
  2615     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2616         if (type.isPrimitive()) return;
  2617         if (types.isSameType(type, syms.stringType)) return;
  2618         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2619         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2620         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2621         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2622             validateAnnotationType(pos, types.elemtype(type));
  2623             return;
  2625         log.error(pos, "invalid.annotation.member.type");
  2628     /**
  2629      * "It is also a compile-time error if any method declared in an
  2630      * annotation type has a signature that is override-equivalent to
  2631      * that of any public or protected method declared in class Object
  2632      * or in the interface annotation.Annotation."
  2634      * @jls 9.6 Annotation Types
  2635      */
  2636     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2637         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2638             Scope s = sup.tsym.members();
  2639             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2640                 if (e.sym.kind == MTH &&
  2641                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2642                     types.overrideEquivalent(m.type, e.sym.type))
  2643                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2648     /** Check the annotations of a symbol.
  2649      */
  2650     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2651         for (JCAnnotation a : annotations)
  2652             validateAnnotation(a, s);
  2655     /** Check the type annotations.
  2656      */
  2657     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
  2658         for (JCAnnotation a : annotations)
  2659             validateTypeAnnotation(a, isTypeParameter);
  2662     /** Check an annotation of a symbol.
  2663      */
  2664     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2665         validateAnnotationTree(a);
  2667         if (!annotationApplicable(a, s))
  2668             log.error(a.pos(), "annotation.type.not.applicable");
  2670         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2671             if (!isOverrider(s))
  2672                 log.error(a.pos(), "method.does.not.override.superclass");
  2675         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2676             if (s.kind != TYP) {
  2677                 log.error(a.pos(), "bad.functional.intf.anno");
  2678             } else {
  2679                 try {
  2680                     types.findDescriptorSymbol((TypeSymbol)s);
  2681                 } catch (Types.FunctionDescriptorLookupError ex) {
  2682                     log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
  2688     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2689         Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
  2690         validateAnnotationTree(a);
  2692         if (!isTypeAnnotation(a, isTypeParameter))
  2693             log.error(a.pos(), "annotation.type.not.applicable");
  2696     /**
  2697      * Validate the proposed container 'repeatable' on the
  2698      * annotation type symbol 's'. Report errors at position
  2699      * 'pos'.
  2701      * @param s The (annotation)type declaration annotated with a @Repeatable
  2702      * @param repeatable the @Repeatable on 's'
  2703      * @param pos where to report errors
  2704      */
  2705     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2706         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2708         Type t = null;
  2709         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2710         if (!l.isEmpty()) {
  2711             Assert.check(l.head.fst.name == names.value);
  2712             t = ((Attribute.Class)l.head.snd).getValue();
  2715         if (t == null) {
  2716             // errors should already have been reported during Annotate
  2717             return;
  2720         validateValue(t.tsym, s, pos);
  2721         validateRetention(t.tsym, s, pos);
  2722         validateDocumented(t.tsym, s, pos);
  2723         validateInherited(t.tsym, s, pos);
  2724         validateTarget(t.tsym, s, pos);
  2725         validateDefault(t.tsym, s, pos);
  2728     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2729         Scope.Entry e = container.members().lookup(names.value);
  2730         if (e.scope != null && e.sym.kind == MTH) {
  2731             MethodSymbol m = (MethodSymbol) e.sym;
  2732             Type ret = m.getReturnType();
  2733             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2734                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2735                         container, ret, types.makeArrayType(contained.type));
  2737         } else {
  2738             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2742     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2743         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2744         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2746         boolean error = false;
  2747         switch (containedRetention) {
  2748         case RUNTIME:
  2749             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2750                 error = true;
  2752             break;
  2753         case CLASS:
  2754             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2755                 error = true;
  2758         if (error ) {
  2759             log.error(pos, "invalid.repeatable.annotation.retention",
  2760                       container, containerRetention,
  2761                       contained, containedRetention);
  2765     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2766         if (contained.attribute(syms.documentedType.tsym) != null) {
  2767             if (container.attribute(syms.documentedType.tsym) == null) {
  2768                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2773     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2774         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2775             if (container.attribute(syms.inheritedType.tsym) == null) {
  2776                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2781     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2782         // The set of targets the container is applicable to must be a subset
  2783         // (with respect to annotation target semantics) of the set of targets
  2784         // the contained is applicable to. The target sets may be implicit or
  2785         // explicit.
  2787         Set<Name> containerTargets;
  2788         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2789         if (containerTarget == null) {
  2790             containerTargets = getDefaultTargetSet();
  2791         } else {
  2792             containerTargets = new HashSet<Name>();
  2793         for (Attribute app : containerTarget.values) {
  2794             if (!(app instanceof Attribute.Enum)) {
  2795                 continue; // recovery
  2797             Attribute.Enum e = (Attribute.Enum)app;
  2798             containerTargets.add(e.value.name);
  2802         Set<Name> containedTargets;
  2803         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2804         if (containedTarget == null) {
  2805             containedTargets = getDefaultTargetSet();
  2806         } else {
  2807             containedTargets = new HashSet<Name>();
  2808         for (Attribute app : containedTarget.values) {
  2809             if (!(app instanceof Attribute.Enum)) {
  2810                 continue; // recovery
  2812             Attribute.Enum e = (Attribute.Enum)app;
  2813             containedTargets.add(e.value.name);
  2817         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
  2818             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2822     /* get a set of names for the default target */
  2823     private Set<Name> getDefaultTargetSet() {
  2824         if (defaultTargets == null) {
  2825             Set<Name> targets = new HashSet<Name>();
  2826             targets.add(names.ANNOTATION_TYPE);
  2827             targets.add(names.CONSTRUCTOR);
  2828             targets.add(names.FIELD);
  2829             targets.add(names.LOCAL_VARIABLE);
  2830             targets.add(names.METHOD);
  2831             targets.add(names.PACKAGE);
  2832             targets.add(names.PARAMETER);
  2833             targets.add(names.TYPE);
  2835             defaultTargets = java.util.Collections.unmodifiableSet(targets);
  2838         return defaultTargets;
  2840     private Set<Name> defaultTargets;
  2843     /** Checks that s is a subset of t, with respect to ElementType
  2844      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2845      */
  2846     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
  2847         // Check that all elements in s are present in t
  2848         for (Name n2 : s) {
  2849             boolean currentElementOk = false;
  2850             for (Name n1 : t) {
  2851                 if (n1 == n2) {
  2852                     currentElementOk = true;
  2853                     break;
  2854                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2855                     currentElementOk = true;
  2856                     break;
  2859             if (!currentElementOk)
  2860                 return false;
  2862         return true;
  2865     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2866         // validate that all other elements of containing type has defaults
  2867         Scope scope = container.members();
  2868         for(Symbol elm : scope.getElements()) {
  2869             if (elm.name != names.value &&
  2870                 elm.kind == Kinds.MTH &&
  2871                 ((MethodSymbol)elm).defaultValue == null) {
  2872                 log.error(pos,
  2873                           "invalid.repeatable.annotation.elem.nondefault",
  2874                           container,
  2875                           elm);
  2880     /** Is s a method symbol that overrides a method in a superclass? */
  2881     boolean isOverrider(Symbol s) {
  2882         if (s.kind != MTH || s.isStatic())
  2883             return false;
  2884         MethodSymbol m = (MethodSymbol)s;
  2885         TypeSymbol owner = (TypeSymbol)m.owner;
  2886         for (Type sup : types.closure(owner.type)) {
  2887             if (sup == owner.type)
  2888                 continue; // skip "this"
  2889             Scope scope = sup.tsym.members();
  2890             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2891                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2892                     return true;
  2895         return false;
  2898     /** Is the annotation applicable to type annotations? */
  2899     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2900         Attribute.Compound atTarget =
  2901             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2902         if (atTarget == null) {
  2903             // An annotation without @Target is not a type annotation.
  2904             return false;
  2907         Attribute atValue = atTarget.member(names.value);
  2908         if (!(atValue instanceof Attribute.Array)) {
  2909             return false; // error recovery
  2912         Attribute.Array arr = (Attribute.Array) atValue;
  2913         for (Attribute app : arr.values) {
  2914             if (!(app instanceof Attribute.Enum)) {
  2915                 return false; // recovery
  2917             Attribute.Enum e = (Attribute.Enum) app;
  2919             if (e.value.name == names.TYPE_USE)
  2920                 return true;
  2921             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  2922                 return true;
  2924         return false;
  2927     /** Is the annotation applicable to the symbol? */
  2928     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2929         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2930         Name[] targets;
  2932         if (arr == null) {
  2933             targets = defaultTargetMetaInfo(a, s);
  2934         } else {
  2935             // TODO: can we optimize this?
  2936             targets = new Name[arr.values.length];
  2937             for (int i=0; i<arr.values.length; ++i) {
  2938                 Attribute app = arr.values[i];
  2939                 if (!(app instanceof Attribute.Enum)) {
  2940                     return true; // recovery
  2942                 Attribute.Enum e = (Attribute.Enum) app;
  2943                 targets[i] = e.value.name;
  2946         for (Name target : targets) {
  2947             if (target == names.TYPE)
  2948                 { if (s.kind == TYP) return true; }
  2949             else if (target == names.FIELD)
  2950                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2951             else if (target == names.METHOD)
  2952                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2953             else if (target == names.PARAMETER)
  2954                 { if (s.kind == VAR &&
  2955                       s.owner.kind == MTH &&
  2956                       (s.flags() & PARAMETER) != 0)
  2957                     return true;
  2959             else if (target == names.CONSTRUCTOR)
  2960                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2961             else if (target == names.LOCAL_VARIABLE)
  2962                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2963                       (s.flags() & PARAMETER) == 0)
  2964                     return true;
  2966             else if (target == names.ANNOTATION_TYPE)
  2967                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2968                     return true;
  2970             else if (target == names.PACKAGE)
  2971                 { if (s.kind == PCK) return true; }
  2972             else if (target == names.TYPE_USE)
  2973                 { if (s.kind == TYP ||
  2974                       s.kind == VAR ||
  2975                       (s.kind == MTH && !s.isConstructor() &&
  2976                       !s.type.getReturnType().hasTag(VOID)) ||
  2977                       (s.kind == MTH && s.isConstructor()))
  2978                     return true;
  2980             else if (target == names.TYPE_PARAMETER)
  2981                 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
  2982                     return true;
  2984             else
  2985                 return true; // recovery
  2987         return false;
  2991     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2992         Attribute.Compound atTarget =
  2993             s.attribute(syms.annotationTargetType.tsym);
  2994         if (atTarget == null) return null; // ok, is applicable
  2995         Attribute atValue = atTarget.member(names.value);
  2996         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2997         return (Attribute.Array) atValue;
  3000     private final Name[] dfltTargetMeta;
  3001     private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
  3002         return dfltTargetMeta;
  3005     /** Check an annotation value.
  3007      * @param a The annotation tree to check
  3008      * @return true if this annotation tree is valid, otherwise false
  3009      */
  3010     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  3011         boolean res = false;
  3012         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  3013         try {
  3014             res = validateAnnotation(a);
  3015         } finally {
  3016             log.popDiagnosticHandler(diagHandler);
  3018         return res;
  3021     private boolean validateAnnotation(JCAnnotation a) {
  3022         boolean isValid = true;
  3023         // collect an inventory of the annotation elements
  3024         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  3025         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  3026                 e != null;
  3027                 e = e.sibling)
  3028             if (e.sym.kind == MTH && e.sym.name != names.clinit)
  3029                 members.add((MethodSymbol) e.sym);
  3031         // remove the ones that are assigned values
  3032         for (JCTree arg : a.args) {
  3033             if (!arg.hasTag(ASSIGN)) continue; // recovery
  3034             JCAssign assign = (JCAssign) arg;
  3035             Symbol m = TreeInfo.symbol(assign.lhs);
  3036             if (m == null || m.type.isErroneous()) continue;
  3037             if (!members.remove(m)) {
  3038                 isValid = false;
  3039                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  3040                           m.name, a.type);
  3044         // all the remaining ones better have default values
  3045         List<Name> missingDefaults = List.nil();
  3046         for (MethodSymbol m : members) {
  3047             if (m.defaultValue == null && !m.type.isErroneous()) {
  3048                 missingDefaults = missingDefaults.append(m.name);
  3051         missingDefaults = missingDefaults.reverse();
  3052         if (missingDefaults.nonEmpty()) {
  3053             isValid = false;
  3054             String key = (missingDefaults.size() > 1)
  3055                     ? "annotation.missing.default.value.1"
  3056                     : "annotation.missing.default.value";
  3057             log.error(a.pos(), key, a.type, missingDefaults);
  3060         // special case: java.lang.annotation.Target must not have
  3061         // repeated values in its value member
  3062         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  3063             a.args.tail == null)
  3064             return isValid;
  3066         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  3067         JCAssign assign = (JCAssign) a.args.head;
  3068         Symbol m = TreeInfo.symbol(assign.lhs);
  3069         if (m.name != names.value) return false;
  3070         JCTree rhs = assign.rhs;
  3071         if (!rhs.hasTag(NEWARRAY)) return false;
  3072         JCNewArray na = (JCNewArray) rhs;
  3073         Set<Symbol> targets = new HashSet<Symbol>();
  3074         for (JCTree elem : na.elems) {
  3075             if (!targets.add(TreeInfo.symbol(elem))) {
  3076                 isValid = false;
  3077                 log.error(elem.pos(), "repeated.annotation.target");
  3080         return isValid;
  3083     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  3084         if (allowAnnotations &&
  3085             lint.isEnabled(LintCategory.DEP_ANN) &&
  3086             (s.flags() & DEPRECATED) != 0 &&
  3087             !syms.deprecatedType.isErroneous() &&
  3088             s.attribute(syms.deprecatedType.tsym) == null) {
  3089             log.warning(LintCategory.DEP_ANN,
  3090                     pos, "missing.deprecated.annotation");
  3094     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  3095         if ((s.flags() & DEPRECATED) != 0 &&
  3096                 (other.flags() & DEPRECATED) == 0 &&
  3097                 s.outermostClass() != other.outermostClass()) {
  3098             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3099                 @Override
  3100                 public void report() {
  3101                     warnDeprecated(pos, s);
  3103             });
  3107     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  3108         if ((s.flags() & PROPRIETARY) != 0) {
  3109             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3110                 public void report() {
  3111                     if (enableSunApiLintControl)
  3112                       warnSunApi(pos, "sun.proprietary", s);
  3113                     else
  3114                       log.mandatoryWarning(pos, "sun.proprietary", s);
  3116             });
  3120     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
  3121         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
  3122             log.error(pos, "not.in.profile", s, profile);
  3126 /* *************************************************************************
  3127  * Check for recursive annotation elements.
  3128  **************************************************************************/
  3130     /** Check for cycles in the graph of annotation elements.
  3131      */
  3132     void checkNonCyclicElements(JCClassDecl tree) {
  3133         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  3134         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  3135         try {
  3136             tree.sym.flags_field |= LOCKED;
  3137             for (JCTree def : tree.defs) {
  3138                 if (!def.hasTag(METHODDEF)) continue;
  3139                 JCMethodDecl meth = (JCMethodDecl)def;
  3140                 checkAnnotationResType(meth.pos(), meth.restype.type);
  3142         } finally {
  3143             tree.sym.flags_field &= ~LOCKED;
  3144             tree.sym.flags_field |= ACYCLIC_ANN;
  3148     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  3149         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  3150             return;
  3151         if ((tsym.flags_field & LOCKED) != 0) {
  3152             log.error(pos, "cyclic.annotation.element");
  3153             return;
  3155         try {
  3156             tsym.flags_field |= LOCKED;
  3157             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3158                 Symbol s = e.sym;
  3159                 if (s.kind != Kinds.MTH)
  3160                     continue;
  3161                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3163         } finally {
  3164             tsym.flags_field &= ~LOCKED;
  3165             tsym.flags_field |= ACYCLIC_ANN;
  3169     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3170         switch (type.getTag()) {
  3171         case CLASS:
  3172             if ((type.tsym.flags() & ANNOTATION) != 0)
  3173                 checkNonCyclicElementsInternal(pos, type.tsym);
  3174             break;
  3175         case ARRAY:
  3176             checkAnnotationResType(pos, types.elemtype(type));
  3177             break;
  3178         default:
  3179             break; // int etc
  3183 /* *************************************************************************
  3184  * Check for cycles in the constructor call graph.
  3185  **************************************************************************/
  3187     /** Check for cycles in the graph of constructors calling other
  3188      *  constructors.
  3189      */
  3190     void checkCyclicConstructors(JCClassDecl tree) {
  3191         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3193         // enter each constructor this-call into the map
  3194         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3195             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3196             if (app == null) continue;
  3197             JCMethodDecl meth = (JCMethodDecl) l.head;
  3198             if (TreeInfo.name(app.meth) == names._this) {
  3199                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3200             } else {
  3201                 meth.sym.flags_field |= ACYCLIC;
  3205         // Check for cycles in the map
  3206         Symbol[] ctors = new Symbol[0];
  3207         ctors = callMap.keySet().toArray(ctors);
  3208         for (Symbol caller : ctors) {
  3209             checkCyclicConstructor(tree, caller, callMap);
  3213     /** Look in the map to see if the given constructor is part of a
  3214      *  call cycle.
  3215      */
  3216     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3217                                         Map<Symbol,Symbol> callMap) {
  3218         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3219             if ((ctor.flags_field & LOCKED) != 0) {
  3220                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3221                           "recursive.ctor.invocation");
  3222             } else {
  3223                 ctor.flags_field |= LOCKED;
  3224                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3225                 ctor.flags_field &= ~LOCKED;
  3227             ctor.flags_field |= ACYCLIC;
  3231 /* *************************************************************************
  3232  * Miscellaneous
  3233  **************************************************************************/
  3235     /**
  3236      * Return the opcode of the operator but emit an error if it is an
  3237      * error.
  3238      * @param pos        position for error reporting.
  3239      * @param operator   an operator
  3240      * @param tag        a tree tag
  3241      * @param left       type of left hand side
  3242      * @param right      type of right hand side
  3243      */
  3244     int checkOperator(DiagnosticPosition pos,
  3245                        OperatorSymbol operator,
  3246                        JCTree.Tag tag,
  3247                        Type left,
  3248                        Type right) {
  3249         if (operator.opcode == ByteCodes.error) {
  3250             log.error(pos,
  3251                       "operator.cant.be.applied.1",
  3252                       treeinfo.operatorName(tag),
  3253                       left, right);
  3255         return operator.opcode;
  3259     /**
  3260      *  Check for division by integer constant zero
  3261      *  @param pos           Position for error reporting.
  3262      *  @param operator      The operator for the expression
  3263      *  @param operand       The right hand operand for the expression
  3264      */
  3265     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3266         if (operand.constValue() != null
  3267             && lint.isEnabled(LintCategory.DIVZERO)
  3268             && (operand.getTag().isSubRangeOf(LONG))
  3269             && ((Number) (operand.constValue())).longValue() == 0) {
  3270             int opc = ((OperatorSymbol)operator).opcode;
  3271             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3272                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3273                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3278     /**
  3279      * Check for empty statements after if
  3280      */
  3281     void checkEmptyIf(JCIf tree) {
  3282         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3283                 lint.isEnabled(LintCategory.EMPTY))
  3284             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3287     /** Check that symbol is unique in given scope.
  3288      *  @param pos           Position for error reporting.
  3289      *  @param sym           The symbol.
  3290      *  @param s             The scope.
  3291      */
  3292     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3293         if (sym.type.isErroneous())
  3294             return true;
  3295         if (sym.owner.name == names.any) return false;
  3296         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3297             if (sym != e.sym &&
  3298                     (e.sym.flags() & CLASH) == 0 &&
  3299                     sym.kind == e.sym.kind &&
  3300                     sym.name != names.error &&
  3301                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3302                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3303                     varargsDuplicateError(pos, sym, e.sym);
  3304                     return true;
  3305                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3306                     duplicateErasureError(pos, sym, e.sym);
  3307                     sym.flags_field |= CLASH;
  3308                     return true;
  3309                 } else {
  3310                     duplicateError(pos, e.sym);
  3311                     return false;
  3315         return true;
  3318     /** Report duplicate declaration error.
  3319      */
  3320     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3321         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3322             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3326     /** Check that single-type import is not already imported or top-level defined,
  3327      *  but make an exception for two single-type imports which denote the same type.
  3328      *  @param pos           Position for error reporting.
  3329      *  @param sym           The symbol.
  3330      *  @param s             The scope
  3331      */
  3332     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3333         return checkUniqueImport(pos, sym, s, false);
  3336     /** Check that static single-type import is not already imported or top-level defined,
  3337      *  but make an exception for two single-type imports which denote the same type.
  3338      *  @param pos           Position for error reporting.
  3339      *  @param sym           The symbol.
  3340      *  @param s             The scope
  3341      */
  3342     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3343         return checkUniqueImport(pos, sym, s, true);
  3346     /** Check that single-type import is not already imported or top-level defined,
  3347      *  but make an exception for two single-type imports which denote the same type.
  3348      *  @param pos           Position for error reporting.
  3349      *  @param sym           The symbol.
  3350      *  @param s             The scope.
  3351      *  @param staticImport  Whether or not this was a static import
  3352      */
  3353     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3354         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3355             // is encountered class entered via a class declaration?
  3356             boolean isClassDecl = e.scope == s;
  3357             if ((isClassDecl || sym != e.sym) &&
  3358                 sym.kind == e.sym.kind &&
  3359                 sym.name != names.error) {
  3360                 if (!e.sym.type.isErroneous()) {
  3361                     String what = e.sym.toString();
  3362                     if (!isClassDecl) {
  3363                         if (staticImport)
  3364                             log.error(pos, "already.defined.static.single.import", what);
  3365                         else
  3366                             log.error(pos, "already.defined.single.import", what);
  3368                     else if (sym != e.sym)
  3369                         log.error(pos, "already.defined.this.unit", what);
  3371                 return false;
  3374         return true;
  3377     /** Check that a qualified name is in canonical form (for import decls).
  3378      */
  3379     public void checkCanonical(JCTree tree) {
  3380         if (!isCanonical(tree))
  3381             log.error(tree.pos(), "import.requires.canonical",
  3382                       TreeInfo.symbol(tree));
  3384         // where
  3385         private boolean isCanonical(JCTree tree) {
  3386             while (tree.hasTag(SELECT)) {
  3387                 JCFieldAccess s = (JCFieldAccess) tree;
  3388                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3389                     return false;
  3390                 tree = s.selected;
  3392             return true;
  3395     /** Check that an auxiliary class is not accessed from any other file than its own.
  3396      */
  3397     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3398         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3399             (c.flags() & AUXILIARY) != 0 &&
  3400             rs.isAccessible(env, c) &&
  3401             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3403             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3404                         c, c.sourcefile);
  3408     private class ConversionWarner extends Warner {
  3409         final String uncheckedKey;
  3410         final Type found;
  3411         final Type expected;
  3412         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3413             super(pos);
  3414             this.uncheckedKey = uncheckedKey;
  3415             this.found = found;
  3416             this.expected = expected;
  3419         @Override
  3420         public void warn(LintCategory lint) {
  3421             boolean warned = this.warned;
  3422             super.warn(lint);
  3423             if (warned) return; // suppress redundant diagnostics
  3424             switch (lint) {
  3425                 case UNCHECKED:
  3426                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3427                     break;
  3428                 case VARARGS:
  3429                     if (method != null &&
  3430                             method.attribute(syms.trustMeType.tsym) != null &&
  3431                             isTrustMeAllowedOnMethod(method) &&
  3432                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3433                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3435                     break;
  3436                 default:
  3437                     throw new AssertionError("Unexpected lint: " + lint);
  3442     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3443         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3446     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3447         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial