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

Mon, 21 Jan 2013 20:19:53 +0000

author
mcimadamore
date
Mon, 21 Jan 2013 20:19:53 +0000
changeset 1513
cf84b07a82db
parent 1510
7873d37f5b37
child 1521
71f35e4b93a5
permissions
-rw-r--r--

8005166: Add support for static interface methods
Summary: Support public static interface methods
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    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.InferenceContext.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;
    84     // The set of lint options currently in effect. It is initialized
    85     // from the context, and then is set/reset as needed by Attr as it
    86     // visits all the various parts of the trees during attribution.
    87     private Lint lint;
    89     // The method being analyzed in Attr - it is set/reset as needed by
    90     // Attr as it visits new method declarations.
    91     private MethodSymbol method;
    93     public static Check instance(Context context) {
    94         Check instance = context.get(checkKey);
    95         if (instance == null)
    96             instance = new Check(context);
    97         return instance;
    98     }
   100     protected Check(Context context) {
   101         context.put(checkKey, this);
   103         names = Names.instance(context);
   104         log = Log.instance(context);
   105         rs = Resolve.instance(context);
   106         syms = Symtab.instance(context);
   107         enter = Enter.instance(context);
   108         deferredAttr = DeferredAttr.instance(context);
   109         infer = Infer.instance(context);
   110         this.types = Types.instance(context);
   111         diags = JCDiagnostic.Factory.instance(context);
   112         Options options = Options.instance(context);
   113         lint = Lint.instance(context);
   114         treeinfo = TreeInfo.instance(context);
   115         fileManager = context.get(JavaFileManager.class);
   117         Source source = Source.instance(context);
   118         allowGenerics = source.allowGenerics();
   119         allowVarargs = source.allowVarargs();
   120         allowAnnotations = source.allowAnnotations();
   121         allowCovariantReturns = source.allowCovariantReturns();
   122         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   123         allowDefaultMethods = source.allowDefaultMethods();
   124         allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
   125         complexInference = options.isSet("complexinference");
   126         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   127         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   128         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   130         Target target = Target.instance(context);
   131         syntheticNameChar = target.syntheticNameChar();
   133         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   134         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   135         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   136         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   138         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   139                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   140         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   141                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   142         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   143                 enforceMandatoryWarnings, "sunapi", null);
   145         deferredLintHandler = DeferredLintHandler.immediateHandler;
   146     }
   148     /** Switch: generics enabled?
   149      */
   150     boolean allowGenerics;
   152     /** Switch: varargs enabled?
   153      */
   154     boolean allowVarargs;
   156     /** Switch: annotations enabled?
   157      */
   158     boolean allowAnnotations;
   160     /** Switch: covariant returns enabled?
   161      */
   162     boolean allowCovariantReturns;
   164     /** Switch: simplified varargs enabled?
   165      */
   166     boolean allowSimplifiedVarargs;
   168     /** Switch: default methods enabled?
   169      */
   170     boolean allowDefaultMethods;
   172     /** Switch: should unrelated return types trigger a method clash?
   173      */
   174     boolean allowStrictMethodClashCheck;
   176     /** Switch: -complexinference option set?
   177      */
   178     boolean complexInference;
   180     /** Character for synthetic names
   181      */
   182     char syntheticNameChar;
   184     /** A table mapping flat names of all compiled classes in this run to their
   185      *  symbols; maintained from outside.
   186      */
   187     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   189     /** A handler for messages about deprecated usage.
   190      */
   191     private MandatoryWarningHandler deprecationHandler;
   193     /** A handler for messages about unchecked or unsafe usage.
   194      */
   195     private MandatoryWarningHandler uncheckedHandler;
   197     /** A handler for messages about using proprietary API.
   198      */
   199     private MandatoryWarningHandler sunApiHandler;
   201     /** A handler for deferred lint warnings.
   202      */
   203     private DeferredLintHandler deferredLintHandler;
   205 /* *************************************************************************
   206  * Errors and Warnings
   207  **************************************************************************/
   209     Lint setLint(Lint newLint) {
   210         Lint prev = lint;
   211         lint = newLint;
   212         return prev;
   213     }
   215     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   216         DeferredLintHandler prev = deferredLintHandler;
   217         deferredLintHandler = newDeferredLintHandler;
   218         return prev;
   219     }
   221     MethodSymbol setMethod(MethodSymbol newMethod) {
   222         MethodSymbol prev = method;
   223         method = newMethod;
   224         return prev;
   225     }
   227     /** Warn about deprecated symbol.
   228      *  @param pos        Position to be used for error reporting.
   229      *  @param sym        The deprecated symbol.
   230      */
   231     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   232         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   233             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   234     }
   236     /** Warn about unchecked operation.
   237      *  @param pos        Position to be used for error reporting.
   238      *  @param msg        A string describing the problem.
   239      */
   240     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   241         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   242             uncheckedHandler.report(pos, msg, args);
   243     }
   245     /** Warn about unsafe vararg method decl.
   246      *  @param pos        Position to be used for error reporting.
   247      */
   248     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   249         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   250             log.warning(LintCategory.VARARGS, pos, key, args);
   251     }
   253     /** Warn about using proprietary API.
   254      *  @param pos        Position to be used for error reporting.
   255      *  @param msg        A string describing the problem.
   256      */
   257     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   258         if (!lint.isSuppressed(LintCategory.SUNAPI))
   259             sunApiHandler.report(pos, msg, args);
   260     }
   262     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   263         if (lint.isEnabled(LintCategory.STATIC))
   264             log.warning(LintCategory.STATIC, pos, msg, args);
   265     }
   267     /**
   268      * Report any deferred diagnostics.
   269      */
   270     public void reportDeferredDiagnostics() {
   271         deprecationHandler.reportDeferredDiagnostic();
   272         uncheckedHandler.reportDeferredDiagnostic();
   273         sunApiHandler.reportDeferredDiagnostic();
   274     }
   277     /** Report a failure to complete a class.
   278      *  @param pos        Position to be used for error reporting.
   279      *  @param ex         The failure to report.
   280      */
   281     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   282         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   283         if (ex instanceof ClassReader.BadClassFile
   284                 && !suppressAbortOnBadClassFile) throw new Abort();
   285         else return syms.errType;
   286     }
   288     /** Report an error that wrong type tag was found.
   289      *  @param pos        Position to be used for error reporting.
   290      *  @param required   An internationalized string describing the type tag
   291      *                    required.
   292      *  @param found      The type that was found.
   293      */
   294     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   295         // this error used to be raised by the parser,
   296         // but has been delayed to this point:
   297         if (found instanceof Type && ((Type)found).hasTag(VOID)) {
   298             log.error(pos, "illegal.start.of.type");
   299             return syms.errType;
   300         }
   301         log.error(pos, "type.found.req", found, required);
   302         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   303     }
   305     /** Report an error that symbol cannot be referenced before super
   306      *  has been called.
   307      *  @param pos        Position to be used for error reporting.
   308      *  @param sym        The referenced symbol.
   309      */
   310     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   311         log.error(pos, "cant.ref.before.ctor.called", sym);
   312     }
   314     /** Report duplicate declaration error.
   315      */
   316     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   317         if (!sym.type.isErroneous()) {
   318             Symbol location = sym.location();
   319             if (location.kind == MTH &&
   320                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   321                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   322                         kindName(sym.location()), kindName(sym.location().enclClass()),
   323                         sym.location().enclClass());
   324             } else {
   325                 log.error(pos, "already.defined", kindName(sym), sym,
   326                         kindName(sym.location()), sym.location());
   327             }
   328         }
   329     }
   331     /** Report array/varargs duplicate declaration
   332      */
   333     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   334         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   335             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   336         }
   337     }
   339 /* ************************************************************************
   340  * duplicate declaration checking
   341  *************************************************************************/
   343     /** Check that variable does not hide variable with same name in
   344      *  immediately enclosing local scope.
   345      *  @param pos           Position for error reporting.
   346      *  @param v             The symbol.
   347      *  @param s             The scope.
   348      */
   349     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   350         if (s.next != null) {
   351             for (Scope.Entry e = s.next.lookup(v.name);
   352                  e.scope != null && e.sym.owner == v.owner;
   353                  e = e.next()) {
   354                 if (e.sym.kind == VAR &&
   355                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   356                     v.name != names.error) {
   357                     duplicateError(pos, e.sym);
   358                     return;
   359                 }
   360             }
   361         }
   362     }
   364     /** Check that a class or interface does not hide a class or
   365      *  interface with same name in immediately enclosing local scope.
   366      *  @param pos           Position for error reporting.
   367      *  @param c             The symbol.
   368      *  @param s             The scope.
   369      */
   370     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   371         if (s.next != null) {
   372             for (Scope.Entry e = s.next.lookup(c.name);
   373                  e.scope != null && e.sym.owner == c.owner;
   374                  e = e.next()) {
   375                 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
   376                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   377                     c.name != names.error) {
   378                     duplicateError(pos, e.sym);
   379                     return;
   380                 }
   381             }
   382         }
   383     }
   385     /** Check that class does not have the same name as one of
   386      *  its enclosing classes, or as a class defined in its enclosing scope.
   387      *  return true if class is unique in its enclosing scope.
   388      *  @param pos           Position for error reporting.
   389      *  @param name          The class name.
   390      *  @param s             The enclosing scope.
   391      */
   392     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   393         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   394             if (e.sym.kind == TYP && e.sym.name != names.error) {
   395                 duplicateError(pos, e.sym);
   396                 return false;
   397             }
   398         }
   399         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   400             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   401                 duplicateError(pos, sym);
   402                 return true;
   403             }
   404         }
   405         return true;
   406     }
   408 /* *************************************************************************
   409  * Class name generation
   410  **************************************************************************/
   412     /** Return name of local class.
   413      *  This is of the form   {@code <enclClass> $ n <classname> }
   414      *  where
   415      *    enclClass is the flat name of the enclosing class,
   416      *    classname is the simple name of the local class
   417      */
   418     Name localClassName(ClassSymbol c) {
   419         for (int i=1; ; i++) {
   420             Name flatname = names.
   421                 fromString("" + c.owner.enclClass().flatname +
   422                            syntheticNameChar + i +
   423                            c.name);
   424             if (compiled.get(flatname) == null) return flatname;
   425         }
   426     }
   428 /* *************************************************************************
   429  * Type Checking
   430  **************************************************************************/
   432     /**
   433      * A check context is an object that can be used to perform compatibility
   434      * checks - depending on the check context, meaning of 'compatibility' might
   435      * vary significantly.
   436      */
   437     public interface CheckContext {
   438         /**
   439          * Is type 'found' compatible with type 'req' in given context
   440          */
   441         boolean compatible(Type found, Type req, Warner warn);
   442         /**
   443          * Report a check error
   444          */
   445         void report(DiagnosticPosition pos, JCDiagnostic details);
   446         /**
   447          * Obtain a warner for this check context
   448          */
   449         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   451         public Infer.InferenceContext inferenceContext();
   453         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   454     }
   456     /**
   457      * This class represent a check context that is nested within another check
   458      * context - useful to check sub-expressions. The default behavior simply
   459      * redirects all method calls to the enclosing check context leveraging
   460      * the forwarding pattern.
   461      */
   462     static class NestedCheckContext implements CheckContext {
   463         CheckContext enclosingContext;
   465         NestedCheckContext(CheckContext enclosingContext) {
   466             this.enclosingContext = enclosingContext;
   467         }
   469         public boolean compatible(Type found, Type req, Warner warn) {
   470             return enclosingContext.compatible(found, req, warn);
   471         }
   473         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   474             enclosingContext.report(pos, details);
   475         }
   477         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   478             return enclosingContext.checkWarner(pos, found, req);
   479         }
   481         public Infer.InferenceContext inferenceContext() {
   482             return enclosingContext.inferenceContext();
   483         }
   485         public DeferredAttrContext deferredAttrContext() {
   486             return enclosingContext.deferredAttrContext();
   487         }
   488     }
   490     /**
   491      * Check context to be used when evaluating assignment/return statements
   492      */
   493     CheckContext basicHandler = new CheckContext() {
   494         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   495             log.error(pos, "prob.found.req", details);
   496         }
   497         public boolean compatible(Type found, Type req, Warner warn) {
   498             return types.isAssignable(found, req, warn);
   499         }
   501         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   502             return convertWarner(pos, found, req);
   503         }
   505         public InferenceContext inferenceContext() {
   506             return infer.emptyContext;
   507         }
   509         public DeferredAttrContext deferredAttrContext() {
   510             return deferredAttr.emptyDeferredAttrContext;
   511         }
   512     };
   514     /** Check that a given type is assignable to a given proto-type.
   515      *  If it is, return the type, otherwise return errType.
   516      *  @param pos        Position to be used for error reporting.
   517      *  @param found      The type that was found.
   518      *  @param req        The type that was required.
   519      */
   520     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   521         return checkType(pos, found, req, basicHandler);
   522     }
   524     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   525         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   526         if (inferenceContext.free(req)) {
   527             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   528                 @Override
   529                 public void typesInferred(InferenceContext inferenceContext) {
   530                     checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
   531                 }
   532             });
   533         }
   534         if (req.hasTag(ERROR))
   535             return req;
   536         if (req.hasTag(NONE))
   537             return found;
   538         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   539             return found;
   540         } else {
   541             if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
   542                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   543                 return types.createErrorType(found);
   544             }
   545             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   546             return types.createErrorType(found);
   547         }
   548     }
   550     /** Check that a given type can be cast to a given target type.
   551      *  Return the result of the cast.
   552      *  @param pos        Position to be used for error reporting.
   553      *  @param found      The type that is being cast.
   554      *  @param req        The target type of the cast.
   555      */
   556     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   557         return checkCastable(pos, found, req, basicHandler);
   558     }
   559     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   560         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   561             return req;
   562         } else {
   563             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   564             return types.createErrorType(found);
   565         }
   566     }
   568     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   569      * The problem should only be reported for non-292 cast
   570      */
   571     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   572         if (!tree.type.isErroneous() &&
   573                 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   574                 && types.isSameType(tree.expr.type, tree.clazz.type)
   575                 && !is292targetTypeCast(tree)) {
   576             log.warning(Lint.LintCategory.CAST,
   577                     tree.pos(), "redundant.cast", tree.expr.type);
   578         }
   579     }
   580     //where
   581             private boolean is292targetTypeCast(JCTypeCast tree) {
   582                 boolean is292targetTypeCast = false;
   583                 JCExpression expr = TreeInfo.skipParens(tree.expr);
   584                 if (expr.hasTag(APPLY)) {
   585                     JCMethodInvocation apply = (JCMethodInvocation)expr;
   586                     Symbol sym = TreeInfo.symbol(apply.meth);
   587                     is292targetTypeCast = sym != null &&
   588                         sym.kind == MTH &&
   589                         (sym.flags() & HYPOTHETICAL) != 0;
   590                 }
   591                 return is292targetTypeCast;
   592             }
   596 //where
   597         /** Is type a type variable, or a (possibly multi-dimensional) array of
   598          *  type variables?
   599          */
   600         boolean isTypeVar(Type t) {
   601             return t.hasTag(TYPEVAR) || t.hasTag(ARRAY) && isTypeVar(types.elemtype(t));
   602         }
   604     /** Check that a type is within some bounds.
   605      *
   606      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
   607      *  type argument.
   608      *  @param a             The type that should be bounded by bs.
   609      *  @param bound         The bound.
   610      */
   611     private boolean checkExtends(Type a, Type bound) {
   612          if (a.isUnbound()) {
   613              return true;
   614          } else if (!a.hasTag(WILDCARD)) {
   615              a = types.upperBound(a);
   616              return types.isSubtype(a, bound);
   617          } else if (a.isExtendsBound()) {
   618              return types.isCastable(bound, types.upperBound(a), types.noWarnings);
   619          } else if (a.isSuperBound()) {
   620              return !types.notSoftSubtype(types.lowerBound(a), bound);
   621          }
   622          return true;
   623      }
   625     /** Check that type is different from 'void'.
   626      *  @param pos           Position to be used for error reporting.
   627      *  @param t             The type to be checked.
   628      */
   629     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   630         if (t.hasTag(VOID)) {
   631             log.error(pos, "void.not.allowed.here");
   632             return types.createErrorType(t);
   633         } else {
   634             return t;
   635         }
   636     }
   638     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
   639         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
   640             return typeTagError(pos,
   641                                 diags.fragment("type.req.class.array"),
   642                                 asTypeParam(t));
   643         } else {
   644             return t;
   645         }
   646     }
   648     /** Check that type is a class or interface type.
   649      *  @param pos           Position to be used for error reporting.
   650      *  @param t             The type to be checked.
   651      */
   652     Type checkClassType(DiagnosticPosition pos, Type t) {
   653         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
   654             return typeTagError(pos,
   655                                 diags.fragment("type.req.class"),
   656                                 asTypeParam(t));
   657         } else {
   658             return t;
   659         }
   660     }
   661     //where
   662         private Object asTypeParam(Type t) {
   663             return (t.hasTag(TYPEVAR))
   664                                     ? diags.fragment("type.parameter", t)
   665                                     : t;
   666         }
   668     /** Check that type is a valid qualifier for a constructor reference expression
   669      */
   670     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
   671         t = checkClassOrArrayType(pos, t);
   672         if (t.hasTag(CLASS)) {
   673             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
   674                 log.error(pos, "abstract.cant.be.instantiated");
   675                 t = types.createErrorType(t);
   676             } else if ((t.tsym.flags() & ENUM) != 0) {
   677                 log.error(pos, "enum.cant.be.instantiated");
   678                 t = types.createErrorType(t);
   679             }
   680         }
   681         return t;
   682     }
   684     /** Check that type is a class or interface type.
   685      *  @param pos           Position to be used for error reporting.
   686      *  @param t             The type to be checked.
   687      *  @param noBounds    True if type bounds are illegal here.
   688      */
   689     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   690         t = checkClassType(pos, t);
   691         if (noBounds && t.isParameterized()) {
   692             List<Type> args = t.getTypeArguments();
   693             while (args.nonEmpty()) {
   694                 if (args.head.hasTag(WILDCARD))
   695                     return typeTagError(pos,
   696                                         diags.fragment("type.req.exact"),
   697                                         args.head);
   698                 args = args.tail;
   699             }
   700         }
   701         return t;
   702     }
   704     /** Check that type is a reifiable class, interface or array type.
   705      *  @param pos           Position to be used for error reporting.
   706      *  @param t             The type to be checked.
   707      */
   708     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   709         t = checkClassOrArrayType(pos, t);
   710         if (!t.isErroneous() && !types.isReifiable(t)) {
   711             log.error(pos, "illegal.generic.type.for.instof");
   712             return types.createErrorType(t);
   713         } else {
   714             return t;
   715         }
   716     }
   718     /** Check that type is a reference type, i.e. a class, interface or array type
   719      *  or a type variable.
   720      *  @param pos           Position to be used for error reporting.
   721      *  @param t             The type to be checked.
   722      */
   723     Type checkRefType(DiagnosticPosition pos, Type t) {
   724         if (t.isReference())
   725             return t;
   726         else
   727             return typeTagError(pos,
   728                                 diags.fragment("type.req.ref"),
   729                                 t);
   730     }
   732     /** Check that each type is a reference type, i.e. a class, interface or array type
   733      *  or a type variable.
   734      *  @param trees         Original trees, used for error reporting.
   735      *  @param types         The types to be checked.
   736      */
   737     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   738         List<JCExpression> tl = trees;
   739         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   740             l.head = checkRefType(tl.head.pos(), l.head);
   741             tl = tl.tail;
   742         }
   743         return types;
   744     }
   746     /** Check that type is a null or reference type.
   747      *  @param pos           Position to be used for error reporting.
   748      *  @param t             The type to be checked.
   749      */
   750     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   751         if (t.isNullOrReference())
   752             return t;
   753         else
   754             return typeTagError(pos,
   755                                 diags.fragment("type.req.ref"),
   756                                 t);
   757     }
   759     /** Check that flag set does not contain elements of two conflicting sets. s
   760      *  Return true if it doesn't.
   761      *  @param pos           Position to be used for error reporting.
   762      *  @param flags         The set of flags to be checked.
   763      *  @param set1          Conflicting flags set #1.
   764      *  @param set2          Conflicting flags set #2.
   765      */
   766     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   767         if ((flags & set1) != 0 && (flags & set2) != 0) {
   768             log.error(pos,
   769                       "illegal.combination.of.modifiers",
   770                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   771                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   772             return false;
   773         } else
   774             return true;
   775     }
   777     /** Check that usage of diamond operator is correct (i.e. diamond should not
   778      * be used with non-generic classes or in anonymous class creation expressions)
   779      */
   780     Type checkDiamond(JCNewClass tree, Type t) {
   781         if (!TreeInfo.isDiamond(tree) ||
   782                 t.isErroneous()) {
   783             return checkClassType(tree.clazz.pos(), t, true);
   784         } else if (tree.def != null) {
   785             log.error(tree.clazz.pos(),
   786                     "cant.apply.diamond.1",
   787                     t, diags.fragment("diamond.and.anon.class", t));
   788             return types.createErrorType(t);
   789         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   790             log.error(tree.clazz.pos(),
   791                 "cant.apply.diamond.1",
   792                 t, diags.fragment("diamond.non.generic", t));
   793             return types.createErrorType(t);
   794         } else if (tree.typeargs != null &&
   795                 tree.typeargs.nonEmpty()) {
   796             log.error(tree.clazz.pos(),
   797                 "cant.apply.diamond.1",
   798                 t, diags.fragment("diamond.and.explicit.params", t));
   799             return types.createErrorType(t);
   800         } else {
   801             return t;
   802         }
   803     }
   805     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   806         MethodSymbol m = tree.sym;
   807         if (!allowSimplifiedVarargs) return;
   808         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   809         Type varargElemType = null;
   810         if (m.isVarArgs()) {
   811             varargElemType = types.elemtype(tree.params.last().type);
   812         }
   813         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   814             if (varargElemType != null) {
   815                 log.error(tree,
   816                         "varargs.invalid.trustme.anno",
   817                         syms.trustMeType.tsym,
   818                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   819             } else {
   820                 log.error(tree,
   821                             "varargs.invalid.trustme.anno",
   822                             syms.trustMeType.tsym,
   823                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   824             }
   825         } else if (hasTrustMeAnno && varargElemType != null &&
   826                             types.isReifiable(varargElemType)) {
   827             warnUnsafeVararg(tree,
   828                             "varargs.redundant.trustme.anno",
   829                             syms.trustMeType.tsym,
   830                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   831         }
   832         else if (!hasTrustMeAnno && varargElemType != null &&
   833                 !types.isReifiable(varargElemType)) {
   834             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   835         }
   836     }
   837     //where
   838         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   839             return (s.flags() & VARARGS) != 0 &&
   840                 (s.isConstructor() ||
   841                     (s.flags() & (STATIC | FINAL)) != 0);
   842         }
   844     Type checkMethod(Type owntype,
   845                             Symbol sym,
   846                             Env<AttrContext> env,
   847                             final List<JCExpression> argtrees,
   848                             List<Type> argtypes,
   849                             boolean useVarargs,
   850                             boolean unchecked) {
   851         // System.out.println("call   : " + env.tree);
   852         // System.out.println("method : " + owntype);
   853         // System.out.println("actuals: " + argtypes);
   854         List<Type> formals = owntype.getParameterTypes();
   855         Type last = useVarargs ? formals.last() : null;
   856         if (sym.name==names.init &&
   857                 sym.owner == syms.enumSym)
   858                 formals = formals.tail.tail;
   859         List<JCExpression> args = argtrees;
   860         DeferredAttr.DeferredTypeMap checkDeferredMap =
   861                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   862         if (args != null) {
   863             //this is null when type-checking a method reference
   864             while (formals.head != last) {
   865                 JCTree arg = args.head;
   866                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   867                 assertConvertible(arg, arg.type, formals.head, warn);
   868                 args = args.tail;
   869                 formals = formals.tail;
   870             }
   871             if (useVarargs) {
   872                 Type varArg = types.elemtype(last);
   873                 while (args.tail != null) {
   874                     JCTree arg = args.head;
   875                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   876                     assertConvertible(arg, arg.type, varArg, warn);
   877                     args = args.tail;
   878                 }
   879             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   880                 // non-varargs call to varargs method
   881                 Type varParam = owntype.getParameterTypes().last();
   882                 Type lastArg = checkDeferredMap.apply(argtypes.last());
   883                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   884                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   885                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   886                             types.elemtype(varParam), varParam);
   887             }
   888         }
   889         if (unchecked) {
   890             warnUnchecked(env.tree.pos(),
   891                     "unchecked.meth.invocation.applied",
   892                     kindName(sym),
   893                     sym.name,
   894                     rs.methodArguments(sym.type.getParameterTypes()),
   895                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   896                     kindName(sym.location()),
   897                     sym.location());
   898            owntype = new MethodType(owntype.getParameterTypes(),
   899                    types.erasure(owntype.getReturnType()),
   900                    types.erasure(owntype.getThrownTypes()),
   901                    syms.methodClass);
   902         }
   903         if (useVarargs) {
   904             Type argtype = owntype.getParameterTypes().last();
   905             if (!types.isReifiable(argtype) &&
   906                     (!allowSimplifiedVarargs ||
   907                     sym.attribute(syms.trustMeType.tsym) == null ||
   908                     !isTrustMeAllowedOnMethod(sym))) {
   909                 warnUnchecked(env.tree.pos(),
   910                                   "unchecked.generic.array.creation",
   911                                   argtype);
   912             }
   913             if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
   914                 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
   915             }
   916          }
   917          PolyKind pkind = (sym.type.hasTag(FORALL) &&
   918                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
   919                  PolyKind.POLY : PolyKind.STANDALONE;
   920          TreeInfo.setPolyKind(env.tree, pkind);
   921          return owntype;
   922     }
   923     //where
   924         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   925             if (types.isConvertible(actual, formal, warn))
   926                 return;
   928             if (formal.isCompound()
   929                 && types.isSubtype(actual, types.supertype(formal))
   930                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   931                 return;
   932         }
   934     /**
   935      * Check that type 't' is a valid instantiation of a generic class
   936      * (see JLS 4.5)
   937      *
   938      * @param t class type to be checked
   939      * @return true if 't' is well-formed
   940      */
   941     public boolean checkValidGenericType(Type t) {
   942         return firstIncompatibleTypeArg(t) == null;
   943     }
   944     //WHERE
   945         private Type firstIncompatibleTypeArg(Type type) {
   946             List<Type> formals = type.tsym.type.allparams();
   947             List<Type> actuals = type.allparams();
   948             List<Type> args = type.getTypeArguments();
   949             List<Type> forms = type.tsym.type.getTypeArguments();
   950             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   952             // For matching pairs of actual argument types `a' and
   953             // formal type parameters with declared bound `b' ...
   954             while (args.nonEmpty() && forms.nonEmpty()) {
   955                 // exact type arguments needs to know their
   956                 // bounds (for upper and lower bound
   957                 // calculations).  So we create new bounds where
   958                 // type-parameters are replaced with actuals argument types.
   959                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   960                 args = args.tail;
   961                 forms = forms.tail;
   962             }
   964             args = type.getTypeArguments();
   965             List<Type> tvars_cap = types.substBounds(formals,
   966                                       formals,
   967                                       types.capture(type).allparams());
   968             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   969                 // Let the actual arguments know their bound
   970                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   971                 args = args.tail;
   972                 tvars_cap = tvars_cap.tail;
   973             }
   975             args = type.getTypeArguments();
   976             List<Type> bounds = bounds_buf.toList();
   978             while (args.nonEmpty() && bounds.nonEmpty()) {
   979                 Type actual = args.head;
   980                 if (!isTypeArgErroneous(actual) &&
   981                         !bounds.head.isErroneous() &&
   982                         !checkExtends(actual, bounds.head)) {
   983                     return args.head;
   984                 }
   985                 args = args.tail;
   986                 bounds = bounds.tail;
   987             }
   989             args = type.getTypeArguments();
   990             bounds = bounds_buf.toList();
   992             for (Type arg : types.capture(type).getTypeArguments()) {
   993                 if (arg.hasTag(TYPEVAR) &&
   994                         arg.getUpperBound().isErroneous() &&
   995                         !bounds.head.isErroneous() &&
   996                         !isTypeArgErroneous(args.head)) {
   997                     return args.head;
   998                 }
   999                 bounds = bounds.tail;
  1000                 args = args.tail;
  1003             return null;
  1005         //where
  1006         boolean isTypeArgErroneous(Type t) {
  1007             return isTypeArgErroneous.visit(t);
  1010         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1011             public Boolean visitType(Type t, Void s) {
  1012                 return t.isErroneous();
  1014             @Override
  1015             public Boolean visitTypeVar(TypeVar t, Void s) {
  1016                 return visit(t.getUpperBound());
  1018             @Override
  1019             public Boolean visitCapturedType(CapturedType t, Void s) {
  1020                 return visit(t.getUpperBound()) ||
  1021                         visit(t.getLowerBound());
  1023             @Override
  1024             public Boolean visitWildcardType(WildcardType t, Void s) {
  1025                 return visit(t.type);
  1027         };
  1029     /** Check that given modifiers are legal for given symbol and
  1030      *  return modifiers together with any implicit modififiers for that symbol.
  1031      *  Warning: we can't use flags() here since this method
  1032      *  is called during class enter, when flags() would cause a premature
  1033      *  completion.
  1034      *  @param pos           Position to be used for error reporting.
  1035      *  @param flags         The set of modifiers given in a definition.
  1036      *  @param sym           The defined symbol.
  1037      */
  1038     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1039         long mask;
  1040         long implicit = 0;
  1041         switch (sym.kind) {
  1042         case VAR:
  1043             if (sym.owner.kind != TYP)
  1044                 mask = LocalVarFlags;
  1045             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1046                 mask = implicit = InterfaceVarFlags;
  1047             else
  1048                 mask = VarFlags;
  1049             break;
  1050         case MTH:
  1051             if (sym.name == names.init) {
  1052                 if ((sym.owner.flags_field & ENUM) != 0) {
  1053                     // enum constructors cannot be declared public or
  1054                     // protected and must be implicitly or explicitly
  1055                     // private
  1056                     implicit = PRIVATE;
  1057                     mask = PRIVATE;
  1058                 } else
  1059                     mask = ConstructorFlags;
  1060             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1061                 if ((flags & (DEFAULT | STATIC)) != 0) {
  1062                     mask = InterfaceMethodMask;
  1063                     implicit = PUBLIC;
  1064                     if ((flags & DEFAULT) != 0) {
  1065                         implicit |= ABSTRACT;
  1067                 } else {
  1068                     mask = implicit = InterfaceMethodFlags;
  1071             else {
  1072                 mask = MethodFlags;
  1074             // Imply STRICTFP if owner has STRICTFP set.
  1075             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1076               implicit |= sym.owner.flags_field & STRICTFP;
  1077             break;
  1078         case TYP:
  1079             if (sym.isLocal()) {
  1080                 mask = LocalClassFlags;
  1081                 if (sym.name.isEmpty()) { // Anonymous class
  1082                     // Anonymous classes in static methods are themselves static;
  1083                     // that's why we admit STATIC here.
  1084                     mask |= STATIC;
  1085                     // JLS: Anonymous classes are final.
  1086                     implicit |= FINAL;
  1088                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1089                     (flags & ENUM) != 0)
  1090                     log.error(pos, "enums.must.be.static");
  1091             } else if (sym.owner.kind == TYP) {
  1092                 mask = MemberClassFlags;
  1093                 if (sym.owner.owner.kind == PCK ||
  1094                     (sym.owner.flags_field & STATIC) != 0)
  1095                     mask |= STATIC;
  1096                 else if ((flags & ENUM) != 0)
  1097                     log.error(pos, "enums.must.be.static");
  1098                 // Nested interfaces and enums are always STATIC (Spec ???)
  1099                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1100             } else {
  1101                 mask = ClassFlags;
  1103             // Interfaces are always ABSTRACT
  1104             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1106             if ((flags & ENUM) != 0) {
  1107                 // enums can't be declared abstract or final
  1108                 mask &= ~(ABSTRACT | FINAL);
  1109                 implicit |= implicitEnumFinalFlag(tree);
  1111             // Imply STRICTFP if owner has STRICTFP set.
  1112             implicit |= sym.owner.flags_field & STRICTFP;
  1113             break;
  1114         default:
  1115             throw new AssertionError();
  1117         long illegal = flags & ExtendedStandardFlags & ~mask;
  1118         if (illegal != 0) {
  1119             if ((illegal & INTERFACE) != 0) {
  1120                 log.error(pos, "intf.not.allowed.here");
  1121                 mask |= INTERFACE;
  1123             else {
  1124                 log.error(pos,
  1125                           "mod.not.allowed.here", asFlagSet(illegal));
  1128         else if ((sym.kind == TYP ||
  1129                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1130                   // in the presence of inner classes. Should it be deleted here?
  1131                   checkDisjoint(pos, flags,
  1132                                 ABSTRACT,
  1133                                 PRIVATE | STATIC | DEFAULT))
  1134                  &&
  1135                  checkDisjoint(pos, flags,
  1136                                 STATIC,
  1137                                 DEFAULT)
  1138                  &&
  1139                  checkDisjoint(pos, flags,
  1140                                ABSTRACT | INTERFACE,
  1141                                FINAL | NATIVE | SYNCHRONIZED)
  1142                  &&
  1143                  checkDisjoint(pos, flags,
  1144                                PUBLIC,
  1145                                PRIVATE | PROTECTED)
  1146                  &&
  1147                  checkDisjoint(pos, flags,
  1148                                PRIVATE,
  1149                                PUBLIC | PROTECTED)
  1150                  &&
  1151                  checkDisjoint(pos, flags,
  1152                                FINAL,
  1153                                VOLATILE)
  1154                  &&
  1155                  (sym.kind == TYP ||
  1156                   checkDisjoint(pos, flags,
  1157                                 ABSTRACT | NATIVE,
  1158                                 STRICTFP))) {
  1159             // skip
  1161         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1165     /** Determine if this enum should be implicitly final.
  1167      *  If the enum has no specialized enum contants, it is final.
  1169      *  If the enum does have specialized enum contants, it is
  1170      *  <i>not</i> final.
  1171      */
  1172     private long implicitEnumFinalFlag(JCTree tree) {
  1173         if (!tree.hasTag(CLASSDEF)) return 0;
  1174         class SpecialTreeVisitor extends JCTree.Visitor {
  1175             boolean specialized;
  1176             SpecialTreeVisitor() {
  1177                 this.specialized = false;
  1178             };
  1180             @Override
  1181             public void visitTree(JCTree tree) { /* no-op */ }
  1183             @Override
  1184             public void visitVarDef(JCVariableDecl tree) {
  1185                 if ((tree.mods.flags & ENUM) != 0) {
  1186                     if (tree.init instanceof JCNewClass &&
  1187                         ((JCNewClass) tree.init).def != null) {
  1188                         specialized = true;
  1194         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1195         JCClassDecl cdef = (JCClassDecl) tree;
  1196         for (JCTree defs: cdef.defs) {
  1197             defs.accept(sts);
  1198             if (sts.specialized) return 0;
  1200         return FINAL;
  1203 /* *************************************************************************
  1204  * Type Validation
  1205  **************************************************************************/
  1207     /** Validate a type expression. That is,
  1208      *  check that all type arguments of a parametric type are within
  1209      *  their bounds. This must be done in a second phase after type attributon
  1210      *  since a class might have a subclass as type parameter bound. E.g:
  1212      *  <pre>{@code
  1213      *  class B<A extends C> { ... }
  1214      *  class C extends B<C> { ... }
  1215      *  }</pre>
  1217      *  and we can't make sure that the bound is already attributed because
  1218      *  of possible cycles.
  1220      * Visitor method: Validate a type expression, if it is not null, catching
  1221      *  and reporting any completion failures.
  1222      */
  1223     void validate(JCTree tree, Env<AttrContext> env) {
  1224         validate(tree, env, true);
  1226     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1227         new Validator(env).validateTree(tree, checkRaw, true);
  1230     /** Visitor method: Validate a list of type expressions.
  1231      */
  1232     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1233         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1234             validate(l.head, env);
  1237     /** A visitor class for type validation.
  1238      */
  1239     class Validator extends JCTree.Visitor {
  1241         boolean isOuter;
  1242         Env<AttrContext> env;
  1244         Validator(Env<AttrContext> env) {
  1245             this.env = env;
  1248         @Override
  1249         public void visitTypeArray(JCArrayTypeTree tree) {
  1250             tree.elemtype.accept(this);
  1253         @Override
  1254         public void visitTypeApply(JCTypeApply tree) {
  1255             if (tree.type.hasTag(CLASS)) {
  1256                 List<JCExpression> args = tree.arguments;
  1257                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1259                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1260                 if (incompatibleArg != null) {
  1261                     for (JCTree arg : tree.arguments) {
  1262                         if (arg.type == incompatibleArg) {
  1263                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1265                         forms = forms.tail;
  1269                 forms = tree.type.tsym.type.getTypeArguments();
  1271                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1273                 // For matching pairs of actual argument types `a' and
  1274                 // formal type parameters with declared bound `b' ...
  1275                 while (args.nonEmpty() && forms.nonEmpty()) {
  1276                     validateTree(args.head,
  1277                             !(isOuter && is_java_lang_Class),
  1278                             false);
  1279                     args = args.tail;
  1280                     forms = forms.tail;
  1283                 // Check that this type is either fully parameterized, or
  1284                 // not parameterized at all.
  1285                 if (tree.type.getEnclosingType().isRaw())
  1286                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1287                 if (tree.clazz.hasTag(SELECT))
  1288                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1292         @Override
  1293         public void visitTypeParameter(JCTypeParameter tree) {
  1294             validateTrees(tree.bounds, true, isOuter);
  1295             checkClassBounds(tree.pos(), tree.type);
  1298         @Override
  1299         public void visitWildcard(JCWildcard tree) {
  1300             if (tree.inner != null)
  1301                 validateTree(tree.inner, true, isOuter);
  1304         @Override
  1305         public void visitSelect(JCFieldAccess tree) {
  1306             if (tree.type.hasTag(CLASS)) {
  1307                 visitSelectInternal(tree);
  1309                 // Check that this type is either fully parameterized, or
  1310                 // not parameterized at all.
  1311                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1312                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1316         public void visitSelectInternal(JCFieldAccess tree) {
  1317             if (tree.type.tsym.isStatic() &&
  1318                 tree.selected.type.isParameterized()) {
  1319                 // The enclosing type is not a class, so we are
  1320                 // looking at a static member type.  However, the
  1321                 // qualifying expression is parameterized.
  1322                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1323             } else {
  1324                 // otherwise validate the rest of the expression
  1325                 tree.selected.accept(this);
  1329         /** Default visitor method: do nothing.
  1330          */
  1331         @Override
  1332         public void visitTree(JCTree tree) {
  1335         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1336             try {
  1337                 if (tree != null) {
  1338                     this.isOuter = isOuter;
  1339                     tree.accept(this);
  1340                     if (checkRaw)
  1341                         checkRaw(tree, env);
  1343             } catch (CompletionFailure ex) {
  1344                 completionError(tree.pos(), ex);
  1348         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1349             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1350                 validateTree(l.head, checkRaw, isOuter);
  1353         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1354             if (lint.isEnabled(LintCategory.RAW) &&
  1355                 tree.type.hasTag(CLASS) &&
  1356                 !TreeInfo.isDiamond(tree) &&
  1357                 !withinAnonConstr(env) &&
  1358                 tree.type.isRaw()) {
  1359                 log.warning(LintCategory.RAW,
  1360                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1364         boolean withinAnonConstr(Env<AttrContext> env) {
  1365             return env.enclClass.name.isEmpty() &&
  1366                     env.enclMethod != null && env.enclMethod.name == names.init;
  1370 /* *************************************************************************
  1371  * Exception checking
  1372  **************************************************************************/
  1374     /* The following methods treat classes as sets that contain
  1375      * the class itself and all their subclasses
  1376      */
  1378     /** Is given type a subtype of some of the types in given list?
  1379      */
  1380     boolean subset(Type t, List<Type> ts) {
  1381         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1382             if (types.isSubtype(t, l.head)) return true;
  1383         return false;
  1386     /** Is given type a subtype or supertype of
  1387      *  some of the types in given list?
  1388      */
  1389     boolean intersects(Type t, List<Type> ts) {
  1390         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1391             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1392         return false;
  1395     /** Add type set to given type list, unless it is a subclass of some class
  1396      *  in the list.
  1397      */
  1398     List<Type> incl(Type t, List<Type> ts) {
  1399         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1402     /** Remove type set from type set list.
  1403      */
  1404     List<Type> excl(Type t, List<Type> ts) {
  1405         if (ts.isEmpty()) {
  1406             return ts;
  1407         } else {
  1408             List<Type> ts1 = excl(t, ts.tail);
  1409             if (types.isSubtype(ts.head, t)) return ts1;
  1410             else if (ts1 == ts.tail) return ts;
  1411             else return ts1.prepend(ts.head);
  1415     /** Form the union of two type set lists.
  1416      */
  1417     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1418         List<Type> ts = ts1;
  1419         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1420             ts = incl(l.head, ts);
  1421         return ts;
  1424     /** Form the difference of two type lists.
  1425      */
  1426     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1427         List<Type> ts = ts1;
  1428         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1429             ts = excl(l.head, ts);
  1430         return ts;
  1433     /** Form the intersection of two type lists.
  1434      */
  1435     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1436         List<Type> ts = List.nil();
  1437         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1438             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1439         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1440             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1441         return ts;
  1444     /** Is exc an exception symbol that need not be declared?
  1445      */
  1446     boolean isUnchecked(ClassSymbol exc) {
  1447         return
  1448             exc.kind == ERR ||
  1449             exc.isSubClass(syms.errorType.tsym, types) ||
  1450             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1453     /** Is exc an exception type that need not be declared?
  1454      */
  1455     boolean isUnchecked(Type exc) {
  1456         return
  1457             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1458             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1459             exc.hasTag(BOT);
  1462     /** Same, but handling completion failures.
  1463      */
  1464     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1465         try {
  1466             return isUnchecked(exc);
  1467         } catch (CompletionFailure ex) {
  1468             completionError(pos, ex);
  1469             return true;
  1473     /** Is exc handled by given exception list?
  1474      */
  1475     boolean isHandled(Type exc, List<Type> handled) {
  1476         return isUnchecked(exc) || subset(exc, handled);
  1479     /** Return all exceptions in thrown list that are not in handled list.
  1480      *  @param thrown     The list of thrown exceptions.
  1481      *  @param handled    The list of handled exceptions.
  1482      */
  1483     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1484         List<Type> unhandled = List.nil();
  1485         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1486             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1487         return unhandled;
  1490 /* *************************************************************************
  1491  * Overriding/Implementation checking
  1492  **************************************************************************/
  1494     /** The level of access protection given by a flag set,
  1495      *  where PRIVATE is highest and PUBLIC is lowest.
  1496      */
  1497     static int protection(long flags) {
  1498         switch ((short)(flags & AccessFlags)) {
  1499         case PRIVATE: return 3;
  1500         case PROTECTED: return 1;
  1501         default:
  1502         case PUBLIC: return 0;
  1503         case 0: return 2;
  1507     /** A customized "cannot override" error message.
  1508      *  @param m      The overriding method.
  1509      *  @param other  The overridden method.
  1510      *  @return       An internationalized string.
  1511      */
  1512     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1513         String key;
  1514         if ((other.owner.flags() & INTERFACE) == 0)
  1515             key = "cant.override";
  1516         else if ((m.owner.flags() & INTERFACE) == 0)
  1517             key = "cant.implement";
  1518         else
  1519             key = "clashes.with";
  1520         return diags.fragment(key, m, m.location(), other, other.location());
  1523     /** A customized "override" warning message.
  1524      *  @param m      The overriding method.
  1525      *  @param other  The overridden method.
  1526      *  @return       An internationalized string.
  1527      */
  1528     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1529         String key;
  1530         if ((other.owner.flags() & INTERFACE) == 0)
  1531             key = "unchecked.override";
  1532         else if ((m.owner.flags() & INTERFACE) == 0)
  1533             key = "unchecked.implement";
  1534         else
  1535             key = "unchecked.clash.with";
  1536         return diags.fragment(key, m, m.location(), other, other.location());
  1539     /** A customized "override" warning message.
  1540      *  @param m      The overriding method.
  1541      *  @param other  The overridden method.
  1542      *  @return       An internationalized string.
  1543      */
  1544     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1545         String key;
  1546         if ((other.owner.flags() & INTERFACE) == 0)
  1547             key = "varargs.override";
  1548         else  if ((m.owner.flags() & INTERFACE) == 0)
  1549             key = "varargs.implement";
  1550         else
  1551             key = "varargs.clash.with";
  1552         return diags.fragment(key, m, m.location(), other, other.location());
  1555     /** Check that this method conforms with overridden method 'other'.
  1556      *  where `origin' is the class where checking started.
  1557      *  Complications:
  1558      *  (1) Do not check overriding of synthetic methods
  1559      *      (reason: they might be final).
  1560      *      todo: check whether this is still necessary.
  1561      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1562      *      than the method it implements. Augment the proxy methods with the
  1563      *      undeclared exceptions in this case.
  1564      *  (3) When generics are enabled, admit the case where an interface proxy
  1565      *      has a result type
  1566      *      extended by the result type of the method it implements.
  1567      *      Change the proxies result type to the smaller type in this case.
  1569      *  @param tree         The tree from which positions
  1570      *                      are extracted for errors.
  1571      *  @param m            The overriding method.
  1572      *  @param other        The overridden method.
  1573      *  @param origin       The class of which the overriding method
  1574      *                      is a member.
  1575      */
  1576     void checkOverride(JCTree tree,
  1577                        MethodSymbol m,
  1578                        MethodSymbol other,
  1579                        ClassSymbol origin) {
  1580         // Don't check overriding of synthetic methods or by bridge methods.
  1581         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1582             return;
  1585         // Error if static method overrides instance method (JLS 8.4.6.2).
  1586         if ((m.flags() & STATIC) != 0 &&
  1587                    (other.flags() & STATIC) == 0) {
  1588             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1589                       cannotOverride(m, other));
  1590             return;
  1593         // Error if instance method overrides static or final
  1594         // method (JLS 8.4.6.1).
  1595         if ((other.flags() & FINAL) != 0 ||
  1596                  (m.flags() & STATIC) == 0 &&
  1597                  (other.flags() & STATIC) != 0) {
  1598             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1599                       cannotOverride(m, other),
  1600                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1601             return;
  1604         if ((m.owner.flags() & ANNOTATION) != 0) {
  1605             // handled in validateAnnotationMethod
  1606             return;
  1609         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1610         if ((origin.flags() & INTERFACE) == 0 &&
  1611                  protection(m.flags()) > protection(other.flags())) {
  1612             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1613                       cannotOverride(m, other),
  1614                       other.flags() == 0 ?
  1615                           Flag.PACKAGE :
  1616                           asFlagSet(other.flags() & AccessFlags));
  1617             return;
  1620         Type mt = types.memberType(origin.type, m);
  1621         Type ot = types.memberType(origin.type, other);
  1622         // Error if overriding result type is different
  1623         // (or, in the case of generics mode, not a subtype) of
  1624         // overridden result type. We have to rename any type parameters
  1625         // before comparing types.
  1626         List<Type> mtvars = mt.getTypeArguments();
  1627         List<Type> otvars = ot.getTypeArguments();
  1628         Type mtres = mt.getReturnType();
  1629         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1631         overrideWarner.clear();
  1632         boolean resultTypesOK =
  1633             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1634         if (!resultTypesOK) {
  1635             if (!allowCovariantReturns &&
  1636                 m.owner != origin &&
  1637                 m.owner.isSubClass(other.owner, types)) {
  1638                 // allow limited interoperability with covariant returns
  1639             } else {
  1640                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1641                           "override.incompatible.ret",
  1642                           cannotOverride(m, other),
  1643                           mtres, otres);
  1644                 return;
  1646         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1647             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1648                     "override.unchecked.ret",
  1649                     uncheckedOverrides(m, other),
  1650                     mtres, otres);
  1653         // Error if overriding method throws an exception not reported
  1654         // by overridden method.
  1655         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1656         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1657         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1658         if (unhandledErased.nonEmpty()) {
  1659             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1660                       "override.meth.doesnt.throw",
  1661                       cannotOverride(m, other),
  1662                       unhandledUnerased.head);
  1663             return;
  1665         else if (unhandledUnerased.nonEmpty()) {
  1666             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1667                           "override.unchecked.thrown",
  1668                          cannotOverride(m, other),
  1669                          unhandledUnerased.head);
  1670             return;
  1673         // Optional warning if varargs don't agree
  1674         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1675             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1676             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1677                         ((m.flags() & Flags.VARARGS) != 0)
  1678                         ? "override.varargs.missing"
  1679                         : "override.varargs.extra",
  1680                         varargsOverrides(m, other));
  1683         // Warn if instance method overrides bridge method (compiler spec ??)
  1684         if ((other.flags() & BRIDGE) != 0) {
  1685             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1686                         uncheckedOverrides(m, other));
  1689         // Warn if a deprecated method overridden by a non-deprecated one.
  1690         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1691             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1694     // where
  1695         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1696             // If the method, m, is defined in an interface, then ignore the issue if the method
  1697             // is only inherited via a supertype and also implemented in the supertype,
  1698             // because in that case, we will rediscover the issue when examining the method
  1699             // in the supertype.
  1700             // If the method, m, is not defined in an interface, then the only time we need to
  1701             // address the issue is when the method is the supertype implemementation: any other
  1702             // case, we will have dealt with when examining the supertype classes
  1703             ClassSymbol mc = m.enclClass();
  1704             Type st = types.supertype(origin.type);
  1705             if (!st.hasTag(CLASS))
  1706                 return true;
  1707             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1709             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1710                 List<Type> intfs = types.interfaces(origin.type);
  1711                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1713             else
  1714                 return (stimpl != m);
  1718     // used to check if there were any unchecked conversions
  1719     Warner overrideWarner = new Warner();
  1721     /** Check that a class does not inherit two concrete methods
  1722      *  with the same signature.
  1723      *  @param pos          Position to be used for error reporting.
  1724      *  @param site         The class type to be checked.
  1725      */
  1726     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1727         Type sup = types.supertype(site);
  1728         if (!sup.hasTag(CLASS)) return;
  1730         for (Type t1 = sup;
  1731              t1.tsym.type.isParameterized();
  1732              t1 = types.supertype(t1)) {
  1733             for (Scope.Entry e1 = t1.tsym.members().elems;
  1734                  e1 != null;
  1735                  e1 = e1.sibling) {
  1736                 Symbol s1 = e1.sym;
  1737                 if (s1.kind != MTH ||
  1738                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1739                     !s1.isInheritedIn(site.tsym, types) ||
  1740                     ((MethodSymbol)s1).implementation(site.tsym,
  1741                                                       types,
  1742                                                       true) != s1)
  1743                     continue;
  1744                 Type st1 = types.memberType(t1, s1);
  1745                 int s1ArgsLength = st1.getParameterTypes().length();
  1746                 if (st1 == s1.type) continue;
  1748                 for (Type t2 = sup;
  1749                      t2.hasTag(CLASS);
  1750                      t2 = types.supertype(t2)) {
  1751                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1752                          e2.scope != null;
  1753                          e2 = e2.next()) {
  1754                         Symbol s2 = e2.sym;
  1755                         if (s2 == s1 ||
  1756                             s2.kind != MTH ||
  1757                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1758                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1759                             !s2.isInheritedIn(site.tsym, types) ||
  1760                             ((MethodSymbol)s2).implementation(site.tsym,
  1761                                                               types,
  1762                                                               true) != s2)
  1763                             continue;
  1764                         Type st2 = types.memberType(t2, s2);
  1765                         if (types.overrideEquivalent(st1, st2))
  1766                             log.error(pos, "concrete.inheritance.conflict",
  1767                                       s1, t1, s2, t2, sup);
  1774     /** Check that classes (or interfaces) do not each define an abstract
  1775      *  method with same name and arguments but incompatible return types.
  1776      *  @param pos          Position to be used for error reporting.
  1777      *  @param t1           The first argument type.
  1778      *  @param t2           The second argument type.
  1779      */
  1780     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1781                                             Type t1,
  1782                                             Type t2) {
  1783         return checkCompatibleAbstracts(pos, t1, t2,
  1784                                         types.makeCompoundType(t1, t2));
  1787     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1788                                             Type t1,
  1789                                             Type t2,
  1790                                             Type site) {
  1791         return firstIncompatibility(pos, t1, t2, site) == null;
  1794     /** Return the first method which is defined with same args
  1795      *  but different return types in two given interfaces, or null if none
  1796      *  exists.
  1797      *  @param t1     The first type.
  1798      *  @param t2     The second type.
  1799      *  @param site   The most derived type.
  1800      *  @returns symbol from t2 that conflicts with one in t1.
  1801      */
  1802     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1803         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1804         closure(t1, interfaces1);
  1805         Map<TypeSymbol,Type> interfaces2;
  1806         if (t1 == t2)
  1807             interfaces2 = interfaces1;
  1808         else
  1809             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1811         for (Type t3 : interfaces1.values()) {
  1812             for (Type t4 : interfaces2.values()) {
  1813                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1814                 if (s != null) return s;
  1817         return null;
  1820     /** Compute all the supertypes of t, indexed by type symbol. */
  1821     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1822         if (!t.hasTag(CLASS)) return;
  1823         if (typeMap.put(t.tsym, t) == null) {
  1824             closure(types.supertype(t), typeMap);
  1825             for (Type i : types.interfaces(t))
  1826                 closure(i, typeMap);
  1830     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1831     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1832         if (!t.hasTag(CLASS)) return;
  1833         if (typesSkip.get(t.tsym) != null) return;
  1834         if (typeMap.put(t.tsym, t) == null) {
  1835             closure(types.supertype(t), typesSkip, typeMap);
  1836             for (Type i : types.interfaces(t))
  1837                 closure(i, typesSkip, typeMap);
  1841     /** Return the first method in t2 that conflicts with a method from t1. */
  1842     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1843         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1844             Symbol s1 = e1.sym;
  1845             Type st1 = null;
  1846             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1847                     (s1.flags() & SYNTHETIC) != 0) continue;
  1848             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1849             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1850             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1851                 Symbol s2 = e2.sym;
  1852                 if (s1 == s2) continue;
  1853                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1854                         (s2.flags() & SYNTHETIC) != 0) continue;
  1855                 if (st1 == null) st1 = types.memberType(t1, s1);
  1856                 Type st2 = types.memberType(t2, s2);
  1857                 if (types.overrideEquivalent(st1, st2)) {
  1858                     List<Type> tvars1 = st1.getTypeArguments();
  1859                     List<Type> tvars2 = st2.getTypeArguments();
  1860                     Type rt1 = st1.getReturnType();
  1861                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1862                     boolean compat =
  1863                         types.isSameType(rt1, rt2) ||
  1864                         !rt1.isPrimitiveOrVoid() &&
  1865                         !rt2.isPrimitiveOrVoid() &&
  1866                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1867                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1868                          checkCommonOverriderIn(s1,s2,site);
  1869                     if (!compat) {
  1870                         log.error(pos, "types.incompatible.diff.ret",
  1871                             t1, t2, s2.name +
  1872                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1873                         return s2;
  1875                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1876                         !checkCommonOverriderIn(s1, s2, site)) {
  1877                     log.error(pos,
  1878                             "name.clash.same.erasure.no.override",
  1879                             s1, s1.location(),
  1880                             s2, s2.location());
  1881                     return s2;
  1885         return null;
  1887     //WHERE
  1888     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1889         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1890         Type st1 = types.memberType(site, s1);
  1891         Type st2 = types.memberType(site, s2);
  1892         closure(site, supertypes);
  1893         for (Type t : supertypes.values()) {
  1894             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1895                 Symbol s3 = e.sym;
  1896                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1897                 Type st3 = types.memberType(site,s3);
  1898                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1899                     if (s3.owner == site.tsym) {
  1900                         return true;
  1902                     List<Type> tvars1 = st1.getTypeArguments();
  1903                     List<Type> tvars2 = st2.getTypeArguments();
  1904                     List<Type> tvars3 = st3.getTypeArguments();
  1905                     Type rt1 = st1.getReturnType();
  1906                     Type rt2 = st2.getReturnType();
  1907                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1908                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1909                     boolean compat =
  1910                         !rt13.isPrimitiveOrVoid() &&
  1911                         !rt23.isPrimitiveOrVoid() &&
  1912                         (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
  1913                          types.covariantReturnType(rt23, rt2, types.noWarnings));
  1914                     if (compat)
  1915                         return true;
  1919         return false;
  1922     /** Check that a given method conforms with any method it overrides.
  1923      *  @param tree         The tree from which positions are extracted
  1924      *                      for errors.
  1925      *  @param m            The overriding method.
  1926      */
  1927     void checkOverride(JCTree tree, MethodSymbol m) {
  1928         ClassSymbol origin = (ClassSymbol)m.owner;
  1929         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1930             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1931                 log.error(tree.pos(), "enum.no.finalize");
  1932                 return;
  1934         for (Type t = origin.type; t.hasTag(CLASS);
  1935              t = types.supertype(t)) {
  1936             if (t != origin.type) {
  1937                 checkOverride(tree, t, origin, m);
  1939             for (Type t2 : types.interfaces(t)) {
  1940                 checkOverride(tree, t2, origin, m);
  1945     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1946         TypeSymbol c = site.tsym;
  1947         Scope.Entry e = c.members().lookup(m.name);
  1948         while (e.scope != null) {
  1949             if (m.overrides(e.sym, origin, types, false)) {
  1950                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1951                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1954             e = e.next();
  1958     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1959         ClashFilter cf = new ClashFilter(origin.type);
  1960         return (cf.accepts(s1) &&
  1961                 cf.accepts(s2) &&
  1962                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1966     /** Check that all abstract members of given class have definitions.
  1967      *  @param pos          Position to be used for error reporting.
  1968      *  @param c            The class.
  1969      */
  1970     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1971         try {
  1972             MethodSymbol undef = firstUndef(c, c);
  1973             if (undef != null) {
  1974                 if ((c.flags() & ENUM) != 0 &&
  1975                     types.supertype(c.type).tsym == syms.enumSym &&
  1976                     (c.flags() & FINAL) == 0) {
  1977                     // add the ABSTRACT flag to an enum
  1978                     c.flags_field |= ABSTRACT;
  1979                 } else {
  1980                     MethodSymbol undef1 =
  1981                         new MethodSymbol(undef.flags(), undef.name,
  1982                                          types.memberType(c.type, undef), undef.owner);
  1983                     log.error(pos, "does.not.override.abstract",
  1984                               c, undef1, undef1.location());
  1987         } catch (CompletionFailure ex) {
  1988             completionError(pos, ex);
  1991 //where
  1992         /** Return first abstract member of class `c' that is not defined
  1993          *  in `impl', null if there is none.
  1994          */
  1995         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1996             MethodSymbol undef = null;
  1997             // Do not bother to search in classes that are not abstract,
  1998             // since they cannot have abstract members.
  1999             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2000                 Scope s = c.members();
  2001                 for (Scope.Entry e = s.elems;
  2002                      undef == null && e != null;
  2003                      e = e.sibling) {
  2004                     if (e.sym.kind == MTH &&
  2005                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2006                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2007                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2008                         if (implmeth == null || implmeth == absmeth) {
  2009                             //look for default implementations
  2010                             if (allowDefaultMethods) {
  2011                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2012                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2013                                     implmeth = prov;
  2017                         if (implmeth == null || implmeth == absmeth) {
  2018                             undef = absmeth;
  2022                 if (undef == null) {
  2023                     Type st = types.supertype(c.type);
  2024                     if (st.hasTag(CLASS))
  2025                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2027                 for (List<Type> l = types.interfaces(c.type);
  2028                      undef == null && l.nonEmpty();
  2029                      l = l.tail) {
  2030                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2033             return undef;
  2036     void checkNonCyclicDecl(JCClassDecl tree) {
  2037         CycleChecker cc = new CycleChecker();
  2038         cc.scan(tree);
  2039         if (!cc.errorFound && !cc.partialCheck) {
  2040             tree.sym.flags_field |= ACYCLIC;
  2044     class CycleChecker extends TreeScanner {
  2046         List<Symbol> seenClasses = List.nil();
  2047         boolean errorFound = false;
  2048         boolean partialCheck = false;
  2050         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2051             if (sym != null && sym.kind == TYP) {
  2052                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2053                 if (classEnv != null) {
  2054                     DiagnosticSource prevSource = log.currentSource();
  2055                     try {
  2056                         log.useSource(classEnv.toplevel.sourcefile);
  2057                         scan(classEnv.tree);
  2059                     finally {
  2060                         log.useSource(prevSource.getFile());
  2062                 } else if (sym.kind == TYP) {
  2063                     checkClass(pos, sym, List.<JCTree>nil());
  2065             } else {
  2066                 //not completed yet
  2067                 partialCheck = true;
  2071         @Override
  2072         public void visitSelect(JCFieldAccess tree) {
  2073             super.visitSelect(tree);
  2074             checkSymbol(tree.pos(), tree.sym);
  2077         @Override
  2078         public void visitIdent(JCIdent tree) {
  2079             checkSymbol(tree.pos(), tree.sym);
  2082         @Override
  2083         public void visitTypeApply(JCTypeApply tree) {
  2084             scan(tree.clazz);
  2087         @Override
  2088         public void visitTypeArray(JCArrayTypeTree tree) {
  2089             scan(tree.elemtype);
  2092         @Override
  2093         public void visitClassDef(JCClassDecl tree) {
  2094             List<JCTree> supertypes = List.nil();
  2095             if (tree.getExtendsClause() != null) {
  2096                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2098             if (tree.getImplementsClause() != null) {
  2099                 for (JCTree intf : tree.getImplementsClause()) {
  2100                     supertypes = supertypes.prepend(intf);
  2103             checkClass(tree.pos(), tree.sym, supertypes);
  2106         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2107             if ((c.flags_field & ACYCLIC) != 0)
  2108                 return;
  2109             if (seenClasses.contains(c)) {
  2110                 errorFound = true;
  2111                 noteCyclic(pos, (ClassSymbol)c);
  2112             } else if (!c.type.isErroneous()) {
  2113                 try {
  2114                     seenClasses = seenClasses.prepend(c);
  2115                     if (c.type.hasTag(CLASS)) {
  2116                         if (supertypes.nonEmpty()) {
  2117                             scan(supertypes);
  2119                         else {
  2120                             ClassType ct = (ClassType)c.type;
  2121                             if (ct.supertype_field == null ||
  2122                                     ct.interfaces_field == null) {
  2123                                 //not completed yet
  2124                                 partialCheck = true;
  2125                                 return;
  2127                             checkSymbol(pos, ct.supertype_field.tsym);
  2128                             for (Type intf : ct.interfaces_field) {
  2129                                 checkSymbol(pos, intf.tsym);
  2132                         if (c.owner.kind == TYP) {
  2133                             checkSymbol(pos, c.owner);
  2136                 } finally {
  2137                     seenClasses = seenClasses.tail;
  2143     /** Check for cyclic references. Issue an error if the
  2144      *  symbol of the type referred to has a LOCKED flag set.
  2146      *  @param pos      Position to be used for error reporting.
  2147      *  @param t        The type referred to.
  2148      */
  2149     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2150         checkNonCyclicInternal(pos, t);
  2154     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2155         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2158     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2159         final TypeVar tv;
  2160         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2161             return;
  2162         if (seen.contains(t)) {
  2163             tv = (TypeVar)t;
  2164             tv.bound = types.createErrorType(t);
  2165             log.error(pos, "cyclic.inheritance", t);
  2166         } else if (t.hasTag(TYPEVAR)) {
  2167             tv = (TypeVar)t;
  2168             seen = seen.prepend(tv);
  2169             for (Type b : types.getBounds(tv))
  2170                 checkNonCyclic1(pos, b, seen);
  2174     /** Check for cyclic references. Issue an error if the
  2175      *  symbol of the type referred to has a LOCKED flag set.
  2177      *  @param pos      Position to be used for error reporting.
  2178      *  @param t        The type referred to.
  2179      *  @returns        True if the check completed on all attributed classes
  2180      */
  2181     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2182         boolean complete = true; // was the check complete?
  2183         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2184         Symbol c = t.tsym;
  2185         if ((c.flags_field & ACYCLIC) != 0) return true;
  2187         if ((c.flags_field & LOCKED) != 0) {
  2188             noteCyclic(pos, (ClassSymbol)c);
  2189         } else if (!c.type.isErroneous()) {
  2190             try {
  2191                 c.flags_field |= LOCKED;
  2192                 if (c.type.hasTag(CLASS)) {
  2193                     ClassType clazz = (ClassType)c.type;
  2194                     if (clazz.interfaces_field != null)
  2195                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2196                             complete &= checkNonCyclicInternal(pos, l.head);
  2197                     if (clazz.supertype_field != null) {
  2198                         Type st = clazz.supertype_field;
  2199                         if (st != null && st.hasTag(CLASS))
  2200                             complete &= checkNonCyclicInternal(pos, st);
  2202                     if (c.owner.kind == TYP)
  2203                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2205             } finally {
  2206                 c.flags_field &= ~LOCKED;
  2209         if (complete)
  2210             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2211         if (complete) c.flags_field |= ACYCLIC;
  2212         return complete;
  2215     /** Note that we found an inheritance cycle. */
  2216     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2217         log.error(pos, "cyclic.inheritance", c);
  2218         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2219             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2220         Type st = types.supertype(c.type);
  2221         if (st.hasTag(CLASS))
  2222             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2223         c.type = types.createErrorType(c, c.type);
  2224         c.flags_field |= ACYCLIC;
  2227     /**
  2228      * Check that functional interface methods would make sense when seen
  2229      * from the perspective of the implementing class
  2230      */
  2231     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2232         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2233         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2234         c.interfaces_field = List.of(funcInterface);
  2235         c.supertype_field = syms.objectType;
  2236         c.tsym = csym;
  2237         csym.members_field = new Scope(csym);
  2238         csym.completer = null;
  2239         checkImplementations(tree, csym, csym);
  2242     /** Check that all methods which implement some
  2243      *  method conform to the method they implement.
  2244      *  @param tree         The class definition whose members are checked.
  2245      */
  2246     void checkImplementations(JCClassDecl tree) {
  2247         checkImplementations(tree, tree.sym, tree.sym);
  2249 //where
  2250         /** Check that all methods which implement some
  2251          *  method in `ic' conform to the method they implement.
  2252          */
  2253         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2254             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2255                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2256                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2257                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2258                         if (e.sym.kind == MTH &&
  2259                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2260                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2261                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2262                             if (implmeth != null && implmeth != absmeth &&
  2263                                 (implmeth.owner.flags() & INTERFACE) ==
  2264                                 (origin.flags() & INTERFACE)) {
  2265                                 // don't check if implmeth is in a class, yet
  2266                                 // origin is an interface. This case arises only
  2267                                 // if implmeth is declared in Object. The reason is
  2268                                 // that interfaces really don't inherit from
  2269                                 // Object it's just that the compiler represents
  2270                                 // things that way.
  2271                                 checkOverride(tree, implmeth, absmeth, origin);
  2279     /** Check that all abstract methods implemented by a class are
  2280      *  mutually compatible.
  2281      *  @param pos          Position to be used for error reporting.
  2282      *  @param c            The class whose interfaces are checked.
  2283      */
  2284     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2285         List<Type> supertypes = types.interfaces(c);
  2286         Type supertype = types.supertype(c);
  2287         if (supertype.hasTag(CLASS) &&
  2288             (supertype.tsym.flags() & ABSTRACT) != 0)
  2289             supertypes = supertypes.prepend(supertype);
  2290         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2291             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2292                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2293                 return;
  2294             for (List<Type> m = supertypes; m != l; m = m.tail)
  2295                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2296                     return;
  2298         checkCompatibleConcretes(pos, c);
  2301     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2302         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2303             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2304                 // VM allows methods and variables with differing types
  2305                 if (sym.kind == e.sym.kind &&
  2306                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2307                     sym != e.sym &&
  2308                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2309                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2310                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2311                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2312                     return;
  2318     /** Check that all non-override equivalent methods accessible from 'site'
  2319      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2321      *  @param pos  Position to be used for error reporting.
  2322      *  @param site The class whose methods are checked.
  2323      *  @param sym  The method symbol to be checked.
  2324      */
  2325     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2326          ClashFilter cf = new ClashFilter(site);
  2327         //for each method m1 that is overridden (directly or indirectly)
  2328         //by method 'sym' in 'site'...
  2329         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2330             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2331              //...check each method m2 that is a member of 'site'
  2332              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2333                 if (m2 == m1) continue;
  2334                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2335                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2336                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2337                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2338                     sym.flags_field |= CLASH;
  2339                     String key = m1 == sym ?
  2340                             "name.clash.same.erasure.no.override" :
  2341                             "name.clash.same.erasure.no.override.1";
  2342                     log.error(pos,
  2343                             key,
  2344                             sym, sym.location(),
  2345                             m2, m2.location(),
  2346                             m1, m1.location());
  2347                     return;
  2355     /** Check that all static methods accessible from 'site' are
  2356      *  mutually compatible (JLS 8.4.8).
  2358      *  @param pos  Position to be used for error reporting.
  2359      *  @param site The class whose methods are checked.
  2360      *  @param sym  The method symbol to be checked.
  2361      */
  2362     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2363         ClashFilter cf = new ClashFilter(site);
  2364         //for each method m1 that is a member of 'site'...
  2365         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2366             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2367             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2368             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2369                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2370                 log.error(pos,
  2371                         "name.clash.same.erasure.no.hide",
  2372                         sym, sym.location(),
  2373                         s, s.location());
  2374                 return;
  2379      //where
  2380      private class ClashFilter implements Filter<Symbol> {
  2382          Type site;
  2384          ClashFilter(Type site) {
  2385              this.site = site;
  2388          boolean shouldSkip(Symbol s) {
  2389              return (s.flags() & CLASH) != 0 &&
  2390                 s.owner == site.tsym;
  2393          public boolean accepts(Symbol s) {
  2394              return s.kind == MTH &&
  2395                      (s.flags() & SYNTHETIC) == 0 &&
  2396                      !shouldSkip(s) &&
  2397                      s.isInheritedIn(site.tsym, types) &&
  2398                      !s.isConstructor();
  2402     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2403         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2404         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2405             Assert.check(m.kind == MTH);
  2406             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2407             if (prov.size() > 1) {
  2408                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2409                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2410                 for (MethodSymbol provSym : prov) {
  2411                     if ((provSym.flags() & DEFAULT) != 0) {
  2412                         defaults = defaults.append(provSym);
  2413                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2414                         abstracts = abstracts.append(provSym);
  2416                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2417                         //strong semantics - issue an error if two sibling interfaces
  2418                         //have two override-equivalent defaults - or if one is abstract
  2419                         //and the other is default
  2420                         String errKey;
  2421                         Symbol s1 = defaults.first();
  2422                         Symbol s2;
  2423                         if (defaults.size() > 1) {
  2424                             errKey = "types.incompatible.unrelated.defaults";
  2425                             s2 = defaults.toList().tail.head;
  2426                         } else {
  2427                             errKey = "types.incompatible.abstract.default";
  2428                             s2 = abstracts.first();
  2430                         log.error(pos, errKey,
  2431                                 Kinds.kindName(site.tsym), site,
  2432                                 m.name, types.memberType(site, m).getParameterTypes(),
  2433                                 s1.location(), s2.location());
  2434                         break;
  2441     //where
  2442      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2444          Type site;
  2446          DefaultMethodClashFilter(Type site) {
  2447              this.site = site;
  2450          public boolean accepts(Symbol s) {
  2451              return s.kind == MTH &&
  2452                      (s.flags() & DEFAULT) != 0 &&
  2453                      s.isInheritedIn(site.tsym, types) &&
  2454                      !s.isConstructor();
  2458     /** Report a conflict between a user symbol and a synthetic symbol.
  2459      */
  2460     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2461         if (!sym.type.isErroneous()) {
  2462             if (warnOnSyntheticConflicts) {
  2463                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2465             else {
  2466                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2471     /** Check that class c does not implement directly or indirectly
  2472      *  the same parameterized interface with two different argument lists.
  2473      *  @param pos          Position to be used for error reporting.
  2474      *  @param type         The type whose interfaces are checked.
  2475      */
  2476     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2477         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2479 //where
  2480         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2481          *  with their class symbol as key and their type as value. Make
  2482          *  sure no class is entered with two different types.
  2483          */
  2484         void checkClassBounds(DiagnosticPosition pos,
  2485                               Map<TypeSymbol,Type> seensofar,
  2486                               Type type) {
  2487             if (type.isErroneous()) return;
  2488             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2489                 Type it = l.head;
  2490                 Type oldit = seensofar.put(it.tsym, it);
  2491                 if (oldit != null) {
  2492                     List<Type> oldparams = oldit.allparams();
  2493                     List<Type> newparams = it.allparams();
  2494                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2495                         log.error(pos, "cant.inherit.diff.arg",
  2496                                   it.tsym, Type.toString(oldparams),
  2497                                   Type.toString(newparams));
  2499                 checkClassBounds(pos, seensofar, it);
  2501             Type st = types.supertype(type);
  2502             if (st != null) checkClassBounds(pos, seensofar, st);
  2505     /** Enter interface into into set.
  2506      *  If it existed already, issue a "repeated interface" error.
  2507      */
  2508     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2509         if (its.contains(it))
  2510             log.error(pos, "repeated.interface");
  2511         else {
  2512             its.add(it);
  2516 /* *************************************************************************
  2517  * Check annotations
  2518  **************************************************************************/
  2520     /**
  2521      * Recursively validate annotations values
  2522      */
  2523     void validateAnnotationTree(JCTree tree) {
  2524         class AnnotationValidator extends TreeScanner {
  2525             @Override
  2526             public void visitAnnotation(JCAnnotation tree) {
  2527                 if (!tree.type.isErroneous()) {
  2528                     super.visitAnnotation(tree);
  2529                     validateAnnotation(tree);
  2533         tree.accept(new AnnotationValidator());
  2536     /**
  2537      *  {@literal
  2538      *  Annotation types are restricted to primitives, String, an
  2539      *  enum, an annotation, Class, Class<?>, Class<? extends
  2540      *  Anything>, arrays of the preceding.
  2541      *  }
  2542      */
  2543     void validateAnnotationType(JCTree restype) {
  2544         // restype may be null if an error occurred, so don't bother validating it
  2545         if (restype != null) {
  2546             validateAnnotationType(restype.pos(), restype.type);
  2550     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2551         if (type.isPrimitive()) return;
  2552         if (types.isSameType(type, syms.stringType)) return;
  2553         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2554         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2555         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2556         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2557             validateAnnotationType(pos, types.elemtype(type));
  2558             return;
  2560         log.error(pos, "invalid.annotation.member.type");
  2563     /**
  2564      * "It is also a compile-time error if any method declared in an
  2565      * annotation type has a signature that is override-equivalent to
  2566      * that of any public or protected method declared in class Object
  2567      * or in the interface annotation.Annotation."
  2569      * @jls 9.6 Annotation Types
  2570      */
  2571     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2572         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2573             Scope s = sup.tsym.members();
  2574             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2575                 if (e.sym.kind == MTH &&
  2576                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2577                     types.overrideEquivalent(m.type, e.sym.type))
  2578                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2583     /** Check the annotations of a symbol.
  2584      */
  2585     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2586         for (JCAnnotation a : annotations)
  2587             validateAnnotation(a, s);
  2590     /** Check an annotation of a symbol.
  2591      */
  2592     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2593         validateAnnotationTree(a);
  2595         if (!annotationApplicable(a, s))
  2596             log.error(a.pos(), "annotation.type.not.applicable");
  2598         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2599             if (!isOverrider(s))
  2600                 log.error(a.pos(), "method.does.not.override.superclass");
  2603         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2604             if (s.kind != TYP) {
  2605                 log.error(a.pos(), "bad.functional.intf.anno");
  2606             } else {
  2607                 try {
  2608                     types.findDescriptorSymbol((TypeSymbol)s);
  2609                 } catch (Types.FunctionDescriptorLookupError ex) {
  2610                     log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
  2616     /**
  2617      * Validate the proposed container 'repeatable' on the
  2618      * annotation type symbol 's'. Report errors at position
  2619      * 'pos'.
  2621      * @param s The (annotation)type declaration annotated with a @Repeatable
  2622      * @param repeatable the @Repeatable on 's'
  2623      * @param pos where to report errors
  2624      */
  2625     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2626         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2628         Type t = null;
  2629         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2630         if (!l.isEmpty()) {
  2631             Assert.check(l.head.fst.name == names.value);
  2632             t = ((Attribute.Class)l.head.snd).getValue();
  2635         if (t == null) {
  2636             // errors should already have been reported during Annotate
  2637             return;
  2640         validateValue(t.tsym, s, pos);
  2641         validateRetention(t.tsym, s, pos);
  2642         validateDocumented(t.tsym, s, pos);
  2643         validateInherited(t.tsym, s, pos);
  2644         validateTarget(t.tsym, s, pos);
  2645         validateDefault(t.tsym, s, pos);
  2648     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2649         Scope.Entry e = container.members().lookup(names.value);
  2650         if (e.scope != null && e.sym.kind == MTH) {
  2651             MethodSymbol m = (MethodSymbol) e.sym;
  2652             Type ret = m.getReturnType();
  2653             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2654                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2655                         container, ret, types.makeArrayType(contained.type));
  2657         } else {
  2658             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2662     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2663         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2664         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2666         boolean error = false;
  2667         switch (containedRetention) {
  2668         case RUNTIME:
  2669             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2670                 error = true;
  2672             break;
  2673         case CLASS:
  2674             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2675                 error = true;
  2678         if (error ) {
  2679             log.error(pos, "invalid.repeatable.annotation.retention",
  2680                       container, containerRetention,
  2681                       contained, containedRetention);
  2685     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2686         if (contained.attribute(syms.documentedType.tsym) != null) {
  2687             if (container.attribute(syms.documentedType.tsym) == null) {
  2688                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2693     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2694         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2695             if (container.attribute(syms.inheritedType.tsym) == null) {
  2696                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2701     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2702         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2704         // If contained has no Target, we are done
  2705         if (containedTarget == null) {
  2706             return;
  2709         // If contained has Target m1, container must have a Target
  2710         // annotation, m2, and m2 must be a subset of m1. (This is
  2711         // trivially true if contained has no target as per above).
  2713         // contained has target, but container has not, error
  2714         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2715         if (containerTarget == null) {
  2716             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2717             return;
  2720         Set<Name> containerTargets = new HashSet<Name>();
  2721         for (Attribute app : containerTarget.values) {
  2722             if (!(app instanceof Attribute.Enum)) {
  2723                 continue; // recovery
  2725             Attribute.Enum e = (Attribute.Enum)app;
  2726             containerTargets.add(e.value.name);
  2729         Set<Name> containedTargets = new HashSet<Name>();
  2730         for (Attribute app : containedTarget.values) {
  2731             if (!(app instanceof Attribute.Enum)) {
  2732                 continue; // recovery
  2734             Attribute.Enum e = (Attribute.Enum)app;
  2735             containedTargets.add(e.value.name);
  2738         if (!isTargetSubset(containedTargets, containerTargets)) {
  2739             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2743     /** Checks that t is a subset of s, with respect to ElementType
  2744      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2745      */
  2746     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2747         // Check that all elements in t are present in s
  2748         for (Name n2 : t) {
  2749             boolean currentElementOk = false;
  2750             for (Name n1 : s) {
  2751                 if (n1 == n2) {
  2752                     currentElementOk = true;
  2753                     break;
  2754                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2755                     currentElementOk = true;
  2756                     break;
  2759             if (!currentElementOk)
  2760                 return false;
  2762         return true;
  2765     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2766         // validate that all other elements of containing type has defaults
  2767         Scope scope = container.members();
  2768         for(Symbol elm : scope.getElements()) {
  2769             if (elm.name != names.value &&
  2770                 elm.kind == Kinds.MTH &&
  2771                 ((MethodSymbol)elm).defaultValue == null) {
  2772                 log.error(pos,
  2773                           "invalid.repeatable.annotation.elem.nondefault",
  2774                           container,
  2775                           elm);
  2780     /** Is s a method symbol that overrides a method in a superclass? */
  2781     boolean isOverrider(Symbol s) {
  2782         if (s.kind != MTH || s.isStatic())
  2783             return false;
  2784         MethodSymbol m = (MethodSymbol)s;
  2785         TypeSymbol owner = (TypeSymbol)m.owner;
  2786         for (Type sup : types.closure(owner.type)) {
  2787             if (sup == owner.type)
  2788                 continue; // skip "this"
  2789             Scope scope = sup.tsym.members();
  2790             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2791                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2792                     return true;
  2795         return false;
  2798     /** Is the annotation applicable to the symbol? */
  2799     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2800         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2801         if (arr == null) {
  2802             return true;
  2804         for (Attribute app : arr.values) {
  2805             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2806             Attribute.Enum e = (Attribute.Enum) app;
  2807             if (e.value.name == names.TYPE)
  2808                 { if (s.kind == TYP) return true; }
  2809             else if (e.value.name == names.FIELD)
  2810                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2811             else if (e.value.name == names.METHOD)
  2812                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2813             else if (e.value.name == names.PARAMETER)
  2814                 { if (s.kind == VAR &&
  2815                       s.owner.kind == MTH &&
  2816                       (s.flags() & PARAMETER) != 0)
  2817                     return true;
  2819             else if (e.value.name == names.CONSTRUCTOR)
  2820                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2821             else if (e.value.name == names.LOCAL_VARIABLE)
  2822                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2823                       (s.flags() & PARAMETER) == 0)
  2824                     return true;
  2826             else if (e.value.name == names.ANNOTATION_TYPE)
  2827                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2828                     return true;
  2830             else if (e.value.name == names.PACKAGE)
  2831                 { if (s.kind == PCK) return true; }
  2832             else if (e.value.name == names.TYPE_USE)
  2833                 { if (s.kind == TYP ||
  2834                       s.kind == VAR ||
  2835                       (s.kind == MTH && !s.isConstructor() &&
  2836                        !s.type.getReturnType().hasTag(VOID)))
  2837                     return true;
  2839             else
  2840                 return true; // recovery
  2842         return false;
  2846     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2847         Attribute.Compound atTarget =
  2848             s.attribute(syms.annotationTargetType.tsym);
  2849         if (atTarget == null) return null; // ok, is applicable
  2850         Attribute atValue = atTarget.member(names.value);
  2851         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2852         return (Attribute.Array) atValue;
  2855     /** Check an annotation value.
  2857      * @param a The annotation tree to check
  2858      * @return true if this annotation tree is valid, otherwise false
  2859      */
  2860     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  2861         boolean res = false;
  2862         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  2863         try {
  2864             res = validateAnnotation(a);
  2865         } finally {
  2866             log.popDiagnosticHandler(diagHandler);
  2868         return res;
  2871     private boolean validateAnnotation(JCAnnotation a) {
  2872         boolean isValid = true;
  2873         // collect an inventory of the annotation elements
  2874         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  2875         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2876              e != null;
  2877              e = e.sibling)
  2878             if (e.sym.kind == MTH)
  2879                 members.add((MethodSymbol) e.sym);
  2881         // remove the ones that are assigned values
  2882         for (JCTree arg : a.args) {
  2883             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2884             JCAssign assign = (JCAssign) arg;
  2885             Symbol m = TreeInfo.symbol(assign.lhs);
  2886             if (m == null || m.type.isErroneous()) continue;
  2887             if (!members.remove(m)) {
  2888                 isValid = false;
  2889                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2890                           m.name, a.type);
  2894         // all the remaining ones better have default values
  2895         List<Name> missingDefaults = List.nil();
  2896         for (MethodSymbol m : members) {
  2897             if (m.defaultValue == null && !m.type.isErroneous()) {
  2898                 missingDefaults = missingDefaults.append(m.name);
  2901         missingDefaults = missingDefaults.reverse();
  2902         if (missingDefaults.nonEmpty()) {
  2903             isValid = false;
  2904             String key = (missingDefaults.size() > 1)
  2905                     ? "annotation.missing.default.value.1"
  2906                     : "annotation.missing.default.value";
  2907             log.error(a.pos(), key, a.type, missingDefaults);
  2910         // special case: java.lang.annotation.Target must not have
  2911         // repeated values in its value member
  2912         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2913             a.args.tail == null)
  2914             return isValid;
  2916         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  2917         JCAssign assign = (JCAssign) a.args.head;
  2918         Symbol m = TreeInfo.symbol(assign.lhs);
  2919         if (m.name != names.value) return false;
  2920         JCTree rhs = assign.rhs;
  2921         if (!rhs.hasTag(NEWARRAY)) return false;
  2922         JCNewArray na = (JCNewArray) rhs;
  2923         Set<Symbol> targets = new HashSet<Symbol>();
  2924         for (JCTree elem : na.elems) {
  2925             if (!targets.add(TreeInfo.symbol(elem))) {
  2926                 isValid = false;
  2927                 log.error(elem.pos(), "repeated.annotation.target");
  2930         return isValid;
  2933     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2934         if (allowAnnotations &&
  2935             lint.isEnabled(LintCategory.DEP_ANN) &&
  2936             (s.flags() & DEPRECATED) != 0 &&
  2937             !syms.deprecatedType.isErroneous() &&
  2938             s.attribute(syms.deprecatedType.tsym) == null) {
  2939             log.warning(LintCategory.DEP_ANN,
  2940                     pos, "missing.deprecated.annotation");
  2944     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2945         if ((s.flags() & DEPRECATED) != 0 &&
  2946                 (other.flags() & DEPRECATED) == 0 &&
  2947                 s.outermostClass() != other.outermostClass()) {
  2948             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2949                 @Override
  2950                 public void report() {
  2951                     warnDeprecated(pos, s);
  2953             });
  2957     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2958         if ((s.flags() & PROPRIETARY) != 0) {
  2959             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2960                 public void report() {
  2961                     if (enableSunApiLintControl)
  2962                       warnSunApi(pos, "sun.proprietary", s);
  2963                     else
  2964                       log.mandatoryWarning(pos, "sun.proprietary", s);
  2966             });
  2970 /* *************************************************************************
  2971  * Check for recursive annotation elements.
  2972  **************************************************************************/
  2974     /** Check for cycles in the graph of annotation elements.
  2975      */
  2976     void checkNonCyclicElements(JCClassDecl tree) {
  2977         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2978         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2979         try {
  2980             tree.sym.flags_field |= LOCKED;
  2981             for (JCTree def : tree.defs) {
  2982                 if (!def.hasTag(METHODDEF)) continue;
  2983                 JCMethodDecl meth = (JCMethodDecl)def;
  2984                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2986         } finally {
  2987             tree.sym.flags_field &= ~LOCKED;
  2988             tree.sym.flags_field |= ACYCLIC_ANN;
  2992     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2993         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2994             return;
  2995         if ((tsym.flags_field & LOCKED) != 0) {
  2996             log.error(pos, "cyclic.annotation.element");
  2997             return;
  2999         try {
  3000             tsym.flags_field |= LOCKED;
  3001             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3002                 Symbol s = e.sym;
  3003                 if (s.kind != Kinds.MTH)
  3004                     continue;
  3005                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3007         } finally {
  3008             tsym.flags_field &= ~LOCKED;
  3009             tsym.flags_field |= ACYCLIC_ANN;
  3013     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3014         switch (type.getTag()) {
  3015         case CLASS:
  3016             if ((type.tsym.flags() & ANNOTATION) != 0)
  3017                 checkNonCyclicElementsInternal(pos, type.tsym);
  3018             break;
  3019         case ARRAY:
  3020             checkAnnotationResType(pos, types.elemtype(type));
  3021             break;
  3022         default:
  3023             break; // int etc
  3027 /* *************************************************************************
  3028  * Check for cycles in the constructor call graph.
  3029  **************************************************************************/
  3031     /** Check for cycles in the graph of constructors calling other
  3032      *  constructors.
  3033      */
  3034     void checkCyclicConstructors(JCClassDecl tree) {
  3035         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3037         // enter each constructor this-call into the map
  3038         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3039             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3040             if (app == null) continue;
  3041             JCMethodDecl meth = (JCMethodDecl) l.head;
  3042             if (TreeInfo.name(app.meth) == names._this) {
  3043                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3044             } else {
  3045                 meth.sym.flags_field |= ACYCLIC;
  3049         // Check for cycles in the map
  3050         Symbol[] ctors = new Symbol[0];
  3051         ctors = callMap.keySet().toArray(ctors);
  3052         for (Symbol caller : ctors) {
  3053             checkCyclicConstructor(tree, caller, callMap);
  3057     /** Look in the map to see if the given constructor is part of a
  3058      *  call cycle.
  3059      */
  3060     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3061                                         Map<Symbol,Symbol> callMap) {
  3062         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3063             if ((ctor.flags_field & LOCKED) != 0) {
  3064                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3065                           "recursive.ctor.invocation");
  3066             } else {
  3067                 ctor.flags_field |= LOCKED;
  3068                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3069                 ctor.flags_field &= ~LOCKED;
  3071             ctor.flags_field |= ACYCLIC;
  3075 /* *************************************************************************
  3076  * Miscellaneous
  3077  **************************************************************************/
  3079     /**
  3080      * Return the opcode of the operator but emit an error if it is an
  3081      * error.
  3082      * @param pos        position for error reporting.
  3083      * @param operator   an operator
  3084      * @param tag        a tree tag
  3085      * @param left       type of left hand side
  3086      * @param right      type of right hand side
  3087      */
  3088     int checkOperator(DiagnosticPosition pos,
  3089                        OperatorSymbol operator,
  3090                        JCTree.Tag tag,
  3091                        Type left,
  3092                        Type right) {
  3093         if (operator.opcode == ByteCodes.error) {
  3094             log.error(pos,
  3095                       "operator.cant.be.applied.1",
  3096                       treeinfo.operatorName(tag),
  3097                       left, right);
  3099         return operator.opcode;
  3103     /**
  3104      *  Check for division by integer constant zero
  3105      *  @param pos           Position for error reporting.
  3106      *  @param operator      The operator for the expression
  3107      *  @param operand       The right hand operand for the expression
  3108      */
  3109     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3110         if (operand.constValue() != null
  3111             && lint.isEnabled(LintCategory.DIVZERO)
  3112             && (operand.getTag().isSubRangeOf(LONG))
  3113             && ((Number) (operand.constValue())).longValue() == 0) {
  3114             int opc = ((OperatorSymbol)operator).opcode;
  3115             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3116                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3117                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3122     /**
  3123      * Check for empty statements after if
  3124      */
  3125     void checkEmptyIf(JCIf tree) {
  3126         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3127                 lint.isEnabled(LintCategory.EMPTY))
  3128             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3131     /** Check that symbol is unique in given scope.
  3132      *  @param pos           Position for error reporting.
  3133      *  @param sym           The symbol.
  3134      *  @param s             The scope.
  3135      */
  3136     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3137         if (sym.type.isErroneous())
  3138             return true;
  3139         if (sym.owner.name == names.any) return false;
  3140         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3141             if (sym != e.sym &&
  3142                     (e.sym.flags() & CLASH) == 0 &&
  3143                     sym.kind == e.sym.kind &&
  3144                     sym.name != names.error &&
  3145                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3146                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3147                     varargsDuplicateError(pos, sym, e.sym);
  3148                     return true;
  3149                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3150                     duplicateErasureError(pos, sym, e.sym);
  3151                     sym.flags_field |= CLASH;
  3152                     return true;
  3153                 } else {
  3154                     duplicateError(pos, e.sym);
  3155                     return false;
  3159         return true;
  3162     /** Report duplicate declaration error.
  3163      */
  3164     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3165         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3166             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3170     /** Check that single-type import is not already imported or top-level defined,
  3171      *  but make an exception for two single-type imports which denote the same type.
  3172      *  @param pos           Position for error reporting.
  3173      *  @param sym           The symbol.
  3174      *  @param s             The scope
  3175      */
  3176     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3177         return checkUniqueImport(pos, sym, s, false);
  3180     /** Check that static single-type import is not already imported or top-level defined,
  3181      *  but make an exception for two single-type imports which denote the same type.
  3182      *  @param pos           Position for error reporting.
  3183      *  @param sym           The symbol.
  3184      *  @param s             The scope
  3185      */
  3186     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3187         return checkUniqueImport(pos, sym, s, true);
  3190     /** Check that single-type import is not already imported or top-level defined,
  3191      *  but make an exception for two single-type imports which denote the same type.
  3192      *  @param pos           Position for error reporting.
  3193      *  @param sym           The symbol.
  3194      *  @param s             The scope.
  3195      *  @param staticImport  Whether or not this was a static import
  3196      */
  3197     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3198         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3199             // is encountered class entered via a class declaration?
  3200             boolean isClassDecl = e.scope == s;
  3201             if ((isClassDecl || sym != e.sym) &&
  3202                 sym.kind == e.sym.kind &&
  3203                 sym.name != names.error) {
  3204                 if (!e.sym.type.isErroneous()) {
  3205                     String what = e.sym.toString();
  3206                     if (!isClassDecl) {
  3207                         if (staticImport)
  3208                             log.error(pos, "already.defined.static.single.import", what);
  3209                         else
  3210                             log.error(pos, "already.defined.single.import", what);
  3212                     else if (sym != e.sym)
  3213                         log.error(pos, "already.defined.this.unit", what);
  3215                 return false;
  3218         return true;
  3221     /** Check that a qualified name is in canonical form (for import decls).
  3222      */
  3223     public void checkCanonical(JCTree tree) {
  3224         if (!isCanonical(tree))
  3225             log.error(tree.pos(), "import.requires.canonical",
  3226                       TreeInfo.symbol(tree));
  3228         // where
  3229         private boolean isCanonical(JCTree tree) {
  3230             while (tree.hasTag(SELECT)) {
  3231                 JCFieldAccess s = (JCFieldAccess) tree;
  3232                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3233                     return false;
  3234                 tree = s.selected;
  3236             return true;
  3239     /** Check that an auxiliary class is not accessed from any other file than its own.
  3240      */
  3241     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3242         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3243             (c.flags() & AUXILIARY) != 0 &&
  3244             rs.isAccessible(env, c) &&
  3245             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3247             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3248                         c, c.sourcefile);
  3252     private class ConversionWarner extends Warner {
  3253         final String uncheckedKey;
  3254         final Type found;
  3255         final Type expected;
  3256         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3257             super(pos);
  3258             this.uncheckedKey = uncheckedKey;
  3259             this.found = found;
  3260             this.expected = expected;
  3263         @Override
  3264         public void warn(LintCategory lint) {
  3265             boolean warned = this.warned;
  3266             super.warn(lint);
  3267             if (warned) return; // suppress redundant diagnostics
  3268             switch (lint) {
  3269                 case UNCHECKED:
  3270                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3271                     break;
  3272                 case VARARGS:
  3273                     if (method != null &&
  3274                             method.attribute(syms.trustMeType.tsym) != null &&
  3275                             isTrustMeAllowedOnMethod(method) &&
  3276                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3277                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3279                     break;
  3280                 default:
  3281                     throw new AssertionError("Unexpected lint: " + lint);
  3286     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3287         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3290     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3291         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial