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

Mon, 21 Jan 2013 20:13:56 +0000

author
mcimadamore
date
Mon, 21 Jan 2013 20:13:56 +0000
changeset 1510
7873d37f5b37
parent 1497
7aa2025bbb7b
child 1513
cf84b07a82db
permissions
-rw-r--r--

8005244: Implement overload resolution as per latest spec EDR
Summary: Add support for stuck expressions and provisional applicability
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) != 0) {
  1062                     mask = InterfaceDefaultMethodMask;
  1063                     implicit = PUBLIC | ABSTRACT;
  1064                 } else {
  1065                     mask = implicit = InterfaceMethodFlags;
  1068             else {
  1069                 mask = MethodFlags;
  1071             // Imply STRICTFP if owner has STRICTFP set.
  1072             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1073               implicit |= sym.owner.flags_field & STRICTFP;
  1074             break;
  1075         case TYP:
  1076             if (sym.isLocal()) {
  1077                 mask = LocalClassFlags;
  1078                 if (sym.name.isEmpty()) { // Anonymous class
  1079                     // Anonymous classes in static methods are themselves static;
  1080                     // that's why we admit STATIC here.
  1081                     mask |= STATIC;
  1082                     // JLS: Anonymous classes are final.
  1083                     implicit |= FINAL;
  1085                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1086                     (flags & ENUM) != 0)
  1087                     log.error(pos, "enums.must.be.static");
  1088             } else if (sym.owner.kind == TYP) {
  1089                 mask = MemberClassFlags;
  1090                 if (sym.owner.owner.kind == PCK ||
  1091                     (sym.owner.flags_field & STATIC) != 0)
  1092                     mask |= STATIC;
  1093                 else if ((flags & ENUM) != 0)
  1094                     log.error(pos, "enums.must.be.static");
  1095                 // Nested interfaces and enums are always STATIC (Spec ???)
  1096                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1097             } else {
  1098                 mask = ClassFlags;
  1100             // Interfaces are always ABSTRACT
  1101             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1103             if ((flags & ENUM) != 0) {
  1104                 // enums can't be declared abstract or final
  1105                 mask &= ~(ABSTRACT | FINAL);
  1106                 implicit |= implicitEnumFinalFlag(tree);
  1108             // Imply STRICTFP if owner has STRICTFP set.
  1109             implicit |= sym.owner.flags_field & STRICTFP;
  1110             break;
  1111         default:
  1112             throw new AssertionError();
  1114         long illegal = flags & ExtendedStandardFlags & ~mask;
  1115         if (illegal != 0) {
  1116             if ((illegal & INTERFACE) != 0) {
  1117                 log.error(pos, "intf.not.allowed.here");
  1118                 mask |= INTERFACE;
  1120             else {
  1121                 log.error(pos,
  1122                           "mod.not.allowed.here", asFlagSet(illegal));
  1125         else if ((sym.kind == TYP ||
  1126                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1127                   // in the presence of inner classes. Should it be deleted here?
  1128                   checkDisjoint(pos, flags,
  1129                                 ABSTRACT,
  1130                                 PRIVATE | STATIC | DEFAULT))
  1131                  &&
  1132                  checkDisjoint(pos, flags,
  1133                                ABSTRACT | INTERFACE,
  1134                                FINAL | NATIVE | SYNCHRONIZED)
  1135                  &&
  1136                  checkDisjoint(pos, flags,
  1137                                PUBLIC,
  1138                                PRIVATE | PROTECTED)
  1139                  &&
  1140                  checkDisjoint(pos, flags,
  1141                                PRIVATE,
  1142                                PUBLIC | PROTECTED)
  1143                  &&
  1144                  checkDisjoint(pos, flags,
  1145                                FINAL,
  1146                                VOLATILE)
  1147                  &&
  1148                  (sym.kind == TYP ||
  1149                   checkDisjoint(pos, flags,
  1150                                 ABSTRACT | NATIVE,
  1151                                 STRICTFP))) {
  1152             // skip
  1154         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1158     /** Determine if this enum should be implicitly final.
  1160      *  If the enum has no specialized enum contants, it is final.
  1162      *  If the enum does have specialized enum contants, it is
  1163      *  <i>not</i> final.
  1164      */
  1165     private long implicitEnumFinalFlag(JCTree tree) {
  1166         if (!tree.hasTag(CLASSDEF)) return 0;
  1167         class SpecialTreeVisitor extends JCTree.Visitor {
  1168             boolean specialized;
  1169             SpecialTreeVisitor() {
  1170                 this.specialized = false;
  1171             };
  1173             @Override
  1174             public void visitTree(JCTree tree) { /* no-op */ }
  1176             @Override
  1177             public void visitVarDef(JCVariableDecl tree) {
  1178                 if ((tree.mods.flags & ENUM) != 0) {
  1179                     if (tree.init instanceof JCNewClass &&
  1180                         ((JCNewClass) tree.init).def != null) {
  1181                         specialized = true;
  1187         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1188         JCClassDecl cdef = (JCClassDecl) tree;
  1189         for (JCTree defs: cdef.defs) {
  1190             defs.accept(sts);
  1191             if (sts.specialized) return 0;
  1193         return FINAL;
  1196 /* *************************************************************************
  1197  * Type Validation
  1198  **************************************************************************/
  1200     /** Validate a type expression. That is,
  1201      *  check that all type arguments of a parametric type are within
  1202      *  their bounds. This must be done in a second phase after type attributon
  1203      *  since a class might have a subclass as type parameter bound. E.g:
  1205      *  <pre>{@code
  1206      *  class B<A extends C> { ... }
  1207      *  class C extends B<C> { ... }
  1208      *  }</pre>
  1210      *  and we can't make sure that the bound is already attributed because
  1211      *  of possible cycles.
  1213      * Visitor method: Validate a type expression, if it is not null, catching
  1214      *  and reporting any completion failures.
  1215      */
  1216     void validate(JCTree tree, Env<AttrContext> env) {
  1217         validate(tree, env, true);
  1219     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1220         new Validator(env).validateTree(tree, checkRaw, true);
  1223     /** Visitor method: Validate a list of type expressions.
  1224      */
  1225     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1226         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1227             validate(l.head, env);
  1230     /** A visitor class for type validation.
  1231      */
  1232     class Validator extends JCTree.Visitor {
  1234         boolean isOuter;
  1235         Env<AttrContext> env;
  1237         Validator(Env<AttrContext> env) {
  1238             this.env = env;
  1241         @Override
  1242         public void visitTypeArray(JCArrayTypeTree tree) {
  1243             tree.elemtype.accept(this);
  1246         @Override
  1247         public void visitTypeApply(JCTypeApply tree) {
  1248             if (tree.type.hasTag(CLASS)) {
  1249                 List<JCExpression> args = tree.arguments;
  1250                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1252                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1253                 if (incompatibleArg != null) {
  1254                     for (JCTree arg : tree.arguments) {
  1255                         if (arg.type == incompatibleArg) {
  1256                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1258                         forms = forms.tail;
  1262                 forms = tree.type.tsym.type.getTypeArguments();
  1264                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1266                 // For matching pairs of actual argument types `a' and
  1267                 // formal type parameters with declared bound `b' ...
  1268                 while (args.nonEmpty() && forms.nonEmpty()) {
  1269                     validateTree(args.head,
  1270                             !(isOuter && is_java_lang_Class),
  1271                             false);
  1272                     args = args.tail;
  1273                     forms = forms.tail;
  1276                 // Check that this type is either fully parameterized, or
  1277                 // not parameterized at all.
  1278                 if (tree.type.getEnclosingType().isRaw())
  1279                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1280                 if (tree.clazz.hasTag(SELECT))
  1281                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1285         @Override
  1286         public void visitTypeParameter(JCTypeParameter tree) {
  1287             validateTrees(tree.bounds, true, isOuter);
  1288             checkClassBounds(tree.pos(), tree.type);
  1291         @Override
  1292         public void visitWildcard(JCWildcard tree) {
  1293             if (tree.inner != null)
  1294                 validateTree(tree.inner, true, isOuter);
  1297         @Override
  1298         public void visitSelect(JCFieldAccess tree) {
  1299             if (tree.type.hasTag(CLASS)) {
  1300                 visitSelectInternal(tree);
  1302                 // Check that this type is either fully parameterized, or
  1303                 // not parameterized at all.
  1304                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1305                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1309         public void visitSelectInternal(JCFieldAccess tree) {
  1310             if (tree.type.tsym.isStatic() &&
  1311                 tree.selected.type.isParameterized()) {
  1312                 // The enclosing type is not a class, so we are
  1313                 // looking at a static member type.  However, the
  1314                 // qualifying expression is parameterized.
  1315                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1316             } else {
  1317                 // otherwise validate the rest of the expression
  1318                 tree.selected.accept(this);
  1322         /** Default visitor method: do nothing.
  1323          */
  1324         @Override
  1325         public void visitTree(JCTree tree) {
  1328         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1329             try {
  1330                 if (tree != null) {
  1331                     this.isOuter = isOuter;
  1332                     tree.accept(this);
  1333                     if (checkRaw)
  1334                         checkRaw(tree, env);
  1336             } catch (CompletionFailure ex) {
  1337                 completionError(tree.pos(), ex);
  1341         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1342             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1343                 validateTree(l.head, checkRaw, isOuter);
  1346         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1347             if (lint.isEnabled(LintCategory.RAW) &&
  1348                 tree.type.hasTag(CLASS) &&
  1349                 !TreeInfo.isDiamond(tree) &&
  1350                 !withinAnonConstr(env) &&
  1351                 tree.type.isRaw()) {
  1352                 log.warning(LintCategory.RAW,
  1353                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1357         boolean withinAnonConstr(Env<AttrContext> env) {
  1358             return env.enclClass.name.isEmpty() &&
  1359                     env.enclMethod != null && env.enclMethod.name == names.init;
  1363 /* *************************************************************************
  1364  * Exception checking
  1365  **************************************************************************/
  1367     /* The following methods treat classes as sets that contain
  1368      * the class itself and all their subclasses
  1369      */
  1371     /** Is given type a subtype of some of the types in given list?
  1372      */
  1373     boolean subset(Type t, List<Type> ts) {
  1374         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1375             if (types.isSubtype(t, l.head)) return true;
  1376         return false;
  1379     /** Is given type a subtype or supertype of
  1380      *  some of the types in given list?
  1381      */
  1382     boolean intersects(Type t, List<Type> ts) {
  1383         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1384             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1385         return false;
  1388     /** Add type set to given type list, unless it is a subclass of some class
  1389      *  in the list.
  1390      */
  1391     List<Type> incl(Type t, List<Type> ts) {
  1392         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1395     /** Remove type set from type set list.
  1396      */
  1397     List<Type> excl(Type t, List<Type> ts) {
  1398         if (ts.isEmpty()) {
  1399             return ts;
  1400         } else {
  1401             List<Type> ts1 = excl(t, ts.tail);
  1402             if (types.isSubtype(ts.head, t)) return ts1;
  1403             else if (ts1 == ts.tail) return ts;
  1404             else return ts1.prepend(ts.head);
  1408     /** Form the union of two type set lists.
  1409      */
  1410     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1411         List<Type> ts = ts1;
  1412         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1413             ts = incl(l.head, ts);
  1414         return ts;
  1417     /** Form the difference of two type lists.
  1418      */
  1419     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1420         List<Type> ts = ts1;
  1421         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1422             ts = excl(l.head, ts);
  1423         return ts;
  1426     /** Form the intersection of two type lists.
  1427      */
  1428     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1429         List<Type> ts = List.nil();
  1430         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1431             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1432         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1433             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1434         return ts;
  1437     /** Is exc an exception symbol that need not be declared?
  1438      */
  1439     boolean isUnchecked(ClassSymbol exc) {
  1440         return
  1441             exc.kind == ERR ||
  1442             exc.isSubClass(syms.errorType.tsym, types) ||
  1443             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1446     /** Is exc an exception type that need not be declared?
  1447      */
  1448     boolean isUnchecked(Type exc) {
  1449         return
  1450             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1451             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1452             exc.hasTag(BOT);
  1455     /** Same, but handling completion failures.
  1456      */
  1457     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1458         try {
  1459             return isUnchecked(exc);
  1460         } catch (CompletionFailure ex) {
  1461             completionError(pos, ex);
  1462             return true;
  1466     /** Is exc handled by given exception list?
  1467      */
  1468     boolean isHandled(Type exc, List<Type> handled) {
  1469         return isUnchecked(exc) || subset(exc, handled);
  1472     /** Return all exceptions in thrown list that are not in handled list.
  1473      *  @param thrown     The list of thrown exceptions.
  1474      *  @param handled    The list of handled exceptions.
  1475      */
  1476     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1477         List<Type> unhandled = List.nil();
  1478         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1479             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1480         return unhandled;
  1483 /* *************************************************************************
  1484  * Overriding/Implementation checking
  1485  **************************************************************************/
  1487     /** The level of access protection given by a flag set,
  1488      *  where PRIVATE is highest and PUBLIC is lowest.
  1489      */
  1490     static int protection(long flags) {
  1491         switch ((short)(flags & AccessFlags)) {
  1492         case PRIVATE: return 3;
  1493         case PROTECTED: return 1;
  1494         default:
  1495         case PUBLIC: return 0;
  1496         case 0: return 2;
  1500     /** A customized "cannot override" error message.
  1501      *  @param m      The overriding method.
  1502      *  @param other  The overridden method.
  1503      *  @return       An internationalized string.
  1504      */
  1505     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1506         String key;
  1507         if ((other.owner.flags() & INTERFACE) == 0)
  1508             key = "cant.override";
  1509         else if ((m.owner.flags() & INTERFACE) == 0)
  1510             key = "cant.implement";
  1511         else
  1512             key = "clashes.with";
  1513         return diags.fragment(key, m, m.location(), other, other.location());
  1516     /** A customized "override" warning message.
  1517      *  @param m      The overriding method.
  1518      *  @param other  The overridden method.
  1519      *  @return       An internationalized string.
  1520      */
  1521     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1522         String key;
  1523         if ((other.owner.flags() & INTERFACE) == 0)
  1524             key = "unchecked.override";
  1525         else if ((m.owner.flags() & INTERFACE) == 0)
  1526             key = "unchecked.implement";
  1527         else
  1528             key = "unchecked.clash.with";
  1529         return diags.fragment(key, m, m.location(), other, other.location());
  1532     /** A customized "override" warning message.
  1533      *  @param m      The overriding method.
  1534      *  @param other  The overridden method.
  1535      *  @return       An internationalized string.
  1536      */
  1537     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1538         String key;
  1539         if ((other.owner.flags() & INTERFACE) == 0)
  1540             key = "varargs.override";
  1541         else  if ((m.owner.flags() & INTERFACE) == 0)
  1542             key = "varargs.implement";
  1543         else
  1544             key = "varargs.clash.with";
  1545         return diags.fragment(key, m, m.location(), other, other.location());
  1548     /** Check that this method conforms with overridden method 'other'.
  1549      *  where `origin' is the class where checking started.
  1550      *  Complications:
  1551      *  (1) Do not check overriding of synthetic methods
  1552      *      (reason: they might be final).
  1553      *      todo: check whether this is still necessary.
  1554      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1555      *      than the method it implements. Augment the proxy methods with the
  1556      *      undeclared exceptions in this case.
  1557      *  (3) When generics are enabled, admit the case where an interface proxy
  1558      *      has a result type
  1559      *      extended by the result type of the method it implements.
  1560      *      Change the proxies result type to the smaller type in this case.
  1562      *  @param tree         The tree from which positions
  1563      *                      are extracted for errors.
  1564      *  @param m            The overriding method.
  1565      *  @param other        The overridden method.
  1566      *  @param origin       The class of which the overriding method
  1567      *                      is a member.
  1568      */
  1569     void checkOverride(JCTree tree,
  1570                        MethodSymbol m,
  1571                        MethodSymbol other,
  1572                        ClassSymbol origin) {
  1573         // Don't check overriding of synthetic methods or by bridge methods.
  1574         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1575             return;
  1578         // Error if static method overrides instance method (JLS 8.4.6.2).
  1579         if ((m.flags() & STATIC) != 0 &&
  1580                    (other.flags() & STATIC) == 0) {
  1581             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1582                       cannotOverride(m, other));
  1583             return;
  1586         // Error if instance method overrides static or final
  1587         // method (JLS 8.4.6.1).
  1588         if ((other.flags() & FINAL) != 0 ||
  1589                  (m.flags() & STATIC) == 0 &&
  1590                  (other.flags() & STATIC) != 0) {
  1591             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1592                       cannotOverride(m, other),
  1593                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1594             return;
  1597         if ((m.owner.flags() & ANNOTATION) != 0) {
  1598             // handled in validateAnnotationMethod
  1599             return;
  1602         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1603         if ((origin.flags() & INTERFACE) == 0 &&
  1604                  protection(m.flags()) > protection(other.flags())) {
  1605             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1606                       cannotOverride(m, other),
  1607                       other.flags() == 0 ?
  1608                           Flag.PACKAGE :
  1609                           asFlagSet(other.flags() & AccessFlags));
  1610             return;
  1613         Type mt = types.memberType(origin.type, m);
  1614         Type ot = types.memberType(origin.type, other);
  1615         // Error if overriding result type is different
  1616         // (or, in the case of generics mode, not a subtype) of
  1617         // overridden result type. We have to rename any type parameters
  1618         // before comparing types.
  1619         List<Type> mtvars = mt.getTypeArguments();
  1620         List<Type> otvars = ot.getTypeArguments();
  1621         Type mtres = mt.getReturnType();
  1622         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1624         overrideWarner.clear();
  1625         boolean resultTypesOK =
  1626             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1627         if (!resultTypesOK) {
  1628             if (!allowCovariantReturns &&
  1629                 m.owner != origin &&
  1630                 m.owner.isSubClass(other.owner, types)) {
  1631                 // allow limited interoperability with covariant returns
  1632             } else {
  1633                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1634                           "override.incompatible.ret",
  1635                           cannotOverride(m, other),
  1636                           mtres, otres);
  1637                 return;
  1639         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1640             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1641                     "override.unchecked.ret",
  1642                     uncheckedOverrides(m, other),
  1643                     mtres, otres);
  1646         // Error if overriding method throws an exception not reported
  1647         // by overridden method.
  1648         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1649         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1650         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1651         if (unhandledErased.nonEmpty()) {
  1652             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1653                       "override.meth.doesnt.throw",
  1654                       cannotOverride(m, other),
  1655                       unhandledUnerased.head);
  1656             return;
  1658         else if (unhandledUnerased.nonEmpty()) {
  1659             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1660                           "override.unchecked.thrown",
  1661                          cannotOverride(m, other),
  1662                          unhandledUnerased.head);
  1663             return;
  1666         // Optional warning if varargs don't agree
  1667         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1668             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1669             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1670                         ((m.flags() & Flags.VARARGS) != 0)
  1671                         ? "override.varargs.missing"
  1672                         : "override.varargs.extra",
  1673                         varargsOverrides(m, other));
  1676         // Warn if instance method overrides bridge method (compiler spec ??)
  1677         if ((other.flags() & BRIDGE) != 0) {
  1678             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1679                         uncheckedOverrides(m, other));
  1682         // Warn if a deprecated method overridden by a non-deprecated one.
  1683         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1684             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1687     // where
  1688         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1689             // If the method, m, is defined in an interface, then ignore the issue if the method
  1690             // is only inherited via a supertype and also implemented in the supertype,
  1691             // because in that case, we will rediscover the issue when examining the method
  1692             // in the supertype.
  1693             // If the method, m, is not defined in an interface, then the only time we need to
  1694             // address the issue is when the method is the supertype implemementation: any other
  1695             // case, we will have dealt with when examining the supertype classes
  1696             ClassSymbol mc = m.enclClass();
  1697             Type st = types.supertype(origin.type);
  1698             if (!st.hasTag(CLASS))
  1699                 return true;
  1700             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1702             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1703                 List<Type> intfs = types.interfaces(origin.type);
  1704                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1706             else
  1707                 return (stimpl != m);
  1711     // used to check if there were any unchecked conversions
  1712     Warner overrideWarner = new Warner();
  1714     /** Check that a class does not inherit two concrete methods
  1715      *  with the same signature.
  1716      *  @param pos          Position to be used for error reporting.
  1717      *  @param site         The class type to be checked.
  1718      */
  1719     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1720         Type sup = types.supertype(site);
  1721         if (!sup.hasTag(CLASS)) return;
  1723         for (Type t1 = sup;
  1724              t1.tsym.type.isParameterized();
  1725              t1 = types.supertype(t1)) {
  1726             for (Scope.Entry e1 = t1.tsym.members().elems;
  1727                  e1 != null;
  1728                  e1 = e1.sibling) {
  1729                 Symbol s1 = e1.sym;
  1730                 if (s1.kind != MTH ||
  1731                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1732                     !s1.isInheritedIn(site.tsym, types) ||
  1733                     ((MethodSymbol)s1).implementation(site.tsym,
  1734                                                       types,
  1735                                                       true) != s1)
  1736                     continue;
  1737                 Type st1 = types.memberType(t1, s1);
  1738                 int s1ArgsLength = st1.getParameterTypes().length();
  1739                 if (st1 == s1.type) continue;
  1741                 for (Type t2 = sup;
  1742                      t2.hasTag(CLASS);
  1743                      t2 = types.supertype(t2)) {
  1744                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1745                          e2.scope != null;
  1746                          e2 = e2.next()) {
  1747                         Symbol s2 = e2.sym;
  1748                         if (s2 == s1 ||
  1749                             s2.kind != MTH ||
  1750                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1751                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1752                             !s2.isInheritedIn(site.tsym, types) ||
  1753                             ((MethodSymbol)s2).implementation(site.tsym,
  1754                                                               types,
  1755                                                               true) != s2)
  1756                             continue;
  1757                         Type st2 = types.memberType(t2, s2);
  1758                         if (types.overrideEquivalent(st1, st2))
  1759                             log.error(pos, "concrete.inheritance.conflict",
  1760                                       s1, t1, s2, t2, sup);
  1767     /** Check that classes (or interfaces) do not each define an abstract
  1768      *  method with same name and arguments but incompatible return types.
  1769      *  @param pos          Position to be used for error reporting.
  1770      *  @param t1           The first argument type.
  1771      *  @param t2           The second argument type.
  1772      */
  1773     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1774                                             Type t1,
  1775                                             Type t2) {
  1776         return checkCompatibleAbstracts(pos, t1, t2,
  1777                                         types.makeCompoundType(t1, t2));
  1780     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1781                                             Type t1,
  1782                                             Type t2,
  1783                                             Type site) {
  1784         return firstIncompatibility(pos, t1, t2, site) == null;
  1787     /** Return the first method which is defined with same args
  1788      *  but different return types in two given interfaces, or null if none
  1789      *  exists.
  1790      *  @param t1     The first type.
  1791      *  @param t2     The second type.
  1792      *  @param site   The most derived type.
  1793      *  @returns symbol from t2 that conflicts with one in t1.
  1794      */
  1795     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1796         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1797         closure(t1, interfaces1);
  1798         Map<TypeSymbol,Type> interfaces2;
  1799         if (t1 == t2)
  1800             interfaces2 = interfaces1;
  1801         else
  1802             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1804         for (Type t3 : interfaces1.values()) {
  1805             for (Type t4 : interfaces2.values()) {
  1806                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1807                 if (s != null) return s;
  1810         return null;
  1813     /** Compute all the supertypes of t, indexed by type symbol. */
  1814     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1815         if (!t.hasTag(CLASS)) return;
  1816         if (typeMap.put(t.tsym, t) == null) {
  1817             closure(types.supertype(t), typeMap);
  1818             for (Type i : types.interfaces(t))
  1819                 closure(i, typeMap);
  1823     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1824     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1825         if (!t.hasTag(CLASS)) return;
  1826         if (typesSkip.get(t.tsym) != null) return;
  1827         if (typeMap.put(t.tsym, t) == null) {
  1828             closure(types.supertype(t), typesSkip, typeMap);
  1829             for (Type i : types.interfaces(t))
  1830                 closure(i, typesSkip, typeMap);
  1834     /** Return the first method in t2 that conflicts with a method from t1. */
  1835     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1836         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1837             Symbol s1 = e1.sym;
  1838             Type st1 = null;
  1839             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1840                     (s1.flags() & SYNTHETIC) != 0) continue;
  1841             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1842             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1843             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1844                 Symbol s2 = e2.sym;
  1845                 if (s1 == s2) continue;
  1846                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1847                         (s2.flags() & SYNTHETIC) != 0) continue;
  1848                 if (st1 == null) st1 = types.memberType(t1, s1);
  1849                 Type st2 = types.memberType(t2, s2);
  1850                 if (types.overrideEquivalent(st1, st2)) {
  1851                     List<Type> tvars1 = st1.getTypeArguments();
  1852                     List<Type> tvars2 = st2.getTypeArguments();
  1853                     Type rt1 = st1.getReturnType();
  1854                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1855                     boolean compat =
  1856                         types.isSameType(rt1, rt2) ||
  1857                         !rt1.isPrimitiveOrVoid() &&
  1858                         !rt2.isPrimitiveOrVoid() &&
  1859                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1860                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1861                          checkCommonOverriderIn(s1,s2,site);
  1862                     if (!compat) {
  1863                         log.error(pos, "types.incompatible.diff.ret",
  1864                             t1, t2, s2.name +
  1865                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1866                         return s2;
  1868                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1869                         !checkCommonOverriderIn(s1, s2, site)) {
  1870                     log.error(pos,
  1871                             "name.clash.same.erasure.no.override",
  1872                             s1, s1.location(),
  1873                             s2, s2.location());
  1874                     return s2;
  1878         return null;
  1880     //WHERE
  1881     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1882         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1883         Type st1 = types.memberType(site, s1);
  1884         Type st2 = types.memberType(site, s2);
  1885         closure(site, supertypes);
  1886         for (Type t : supertypes.values()) {
  1887             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1888                 Symbol s3 = e.sym;
  1889                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1890                 Type st3 = types.memberType(site,s3);
  1891                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1892                     if (s3.owner == site.tsym) {
  1893                         return true;
  1895                     List<Type> tvars1 = st1.getTypeArguments();
  1896                     List<Type> tvars2 = st2.getTypeArguments();
  1897                     List<Type> tvars3 = st3.getTypeArguments();
  1898                     Type rt1 = st1.getReturnType();
  1899                     Type rt2 = st2.getReturnType();
  1900                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1901                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1902                     boolean compat =
  1903                         !rt13.isPrimitiveOrVoid() &&
  1904                         !rt23.isPrimitiveOrVoid() &&
  1905                         (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
  1906                          types.covariantReturnType(rt23, rt2, types.noWarnings));
  1907                     if (compat)
  1908                         return true;
  1912         return false;
  1915     /** Check that a given method conforms with any method it overrides.
  1916      *  @param tree         The tree from which positions are extracted
  1917      *                      for errors.
  1918      *  @param m            The overriding method.
  1919      */
  1920     void checkOverride(JCTree tree, MethodSymbol m) {
  1921         ClassSymbol origin = (ClassSymbol)m.owner;
  1922         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1923             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1924                 log.error(tree.pos(), "enum.no.finalize");
  1925                 return;
  1927         for (Type t = origin.type; t.hasTag(CLASS);
  1928              t = types.supertype(t)) {
  1929             if (t != origin.type) {
  1930                 checkOverride(tree, t, origin, m);
  1932             for (Type t2 : types.interfaces(t)) {
  1933                 checkOverride(tree, t2, origin, m);
  1938     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1939         TypeSymbol c = site.tsym;
  1940         Scope.Entry e = c.members().lookup(m.name);
  1941         while (e.scope != null) {
  1942             if (m.overrides(e.sym, origin, types, false)) {
  1943                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1944                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1947             e = e.next();
  1951     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1952         ClashFilter cf = new ClashFilter(origin.type);
  1953         return (cf.accepts(s1) &&
  1954                 cf.accepts(s2) &&
  1955                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1959     /** Check that all abstract members of given class have definitions.
  1960      *  @param pos          Position to be used for error reporting.
  1961      *  @param c            The class.
  1962      */
  1963     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1964         try {
  1965             MethodSymbol undef = firstUndef(c, c);
  1966             if (undef != null) {
  1967                 if ((c.flags() & ENUM) != 0 &&
  1968                     types.supertype(c.type).tsym == syms.enumSym &&
  1969                     (c.flags() & FINAL) == 0) {
  1970                     // add the ABSTRACT flag to an enum
  1971                     c.flags_field |= ABSTRACT;
  1972                 } else {
  1973                     MethodSymbol undef1 =
  1974                         new MethodSymbol(undef.flags(), undef.name,
  1975                                          types.memberType(c.type, undef), undef.owner);
  1976                     log.error(pos, "does.not.override.abstract",
  1977                               c, undef1, undef1.location());
  1980         } catch (CompletionFailure ex) {
  1981             completionError(pos, ex);
  1984 //where
  1985         /** Return first abstract member of class `c' that is not defined
  1986          *  in `impl', null if there is none.
  1987          */
  1988         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1989             MethodSymbol undef = null;
  1990             // Do not bother to search in classes that are not abstract,
  1991             // since they cannot have abstract members.
  1992             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1993                 Scope s = c.members();
  1994                 for (Scope.Entry e = s.elems;
  1995                      undef == null && e != null;
  1996                      e = e.sibling) {
  1997                     if (e.sym.kind == MTH &&
  1998                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  1999                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2000                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2001                         if (implmeth == null || implmeth == absmeth) {
  2002                             //look for default implementations
  2003                             if (allowDefaultMethods) {
  2004                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2005                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2006                                     implmeth = prov;
  2010                         if (implmeth == null || implmeth == absmeth) {
  2011                             undef = absmeth;
  2015                 if (undef == null) {
  2016                     Type st = types.supertype(c.type);
  2017                     if (st.hasTag(CLASS))
  2018                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2020                 for (List<Type> l = types.interfaces(c.type);
  2021                      undef == null && l.nonEmpty();
  2022                      l = l.tail) {
  2023                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2026             return undef;
  2029     void checkNonCyclicDecl(JCClassDecl tree) {
  2030         CycleChecker cc = new CycleChecker();
  2031         cc.scan(tree);
  2032         if (!cc.errorFound && !cc.partialCheck) {
  2033             tree.sym.flags_field |= ACYCLIC;
  2037     class CycleChecker extends TreeScanner {
  2039         List<Symbol> seenClasses = List.nil();
  2040         boolean errorFound = false;
  2041         boolean partialCheck = false;
  2043         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2044             if (sym != null && sym.kind == TYP) {
  2045                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2046                 if (classEnv != null) {
  2047                     DiagnosticSource prevSource = log.currentSource();
  2048                     try {
  2049                         log.useSource(classEnv.toplevel.sourcefile);
  2050                         scan(classEnv.tree);
  2052                     finally {
  2053                         log.useSource(prevSource.getFile());
  2055                 } else if (sym.kind == TYP) {
  2056                     checkClass(pos, sym, List.<JCTree>nil());
  2058             } else {
  2059                 //not completed yet
  2060                 partialCheck = true;
  2064         @Override
  2065         public void visitSelect(JCFieldAccess tree) {
  2066             super.visitSelect(tree);
  2067             checkSymbol(tree.pos(), tree.sym);
  2070         @Override
  2071         public void visitIdent(JCIdent tree) {
  2072             checkSymbol(tree.pos(), tree.sym);
  2075         @Override
  2076         public void visitTypeApply(JCTypeApply tree) {
  2077             scan(tree.clazz);
  2080         @Override
  2081         public void visitTypeArray(JCArrayTypeTree tree) {
  2082             scan(tree.elemtype);
  2085         @Override
  2086         public void visitClassDef(JCClassDecl tree) {
  2087             List<JCTree> supertypes = List.nil();
  2088             if (tree.getExtendsClause() != null) {
  2089                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2091             if (tree.getImplementsClause() != null) {
  2092                 for (JCTree intf : tree.getImplementsClause()) {
  2093                     supertypes = supertypes.prepend(intf);
  2096             checkClass(tree.pos(), tree.sym, supertypes);
  2099         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2100             if ((c.flags_field & ACYCLIC) != 0)
  2101                 return;
  2102             if (seenClasses.contains(c)) {
  2103                 errorFound = true;
  2104                 noteCyclic(pos, (ClassSymbol)c);
  2105             } else if (!c.type.isErroneous()) {
  2106                 try {
  2107                     seenClasses = seenClasses.prepend(c);
  2108                     if (c.type.hasTag(CLASS)) {
  2109                         if (supertypes.nonEmpty()) {
  2110                             scan(supertypes);
  2112                         else {
  2113                             ClassType ct = (ClassType)c.type;
  2114                             if (ct.supertype_field == null ||
  2115                                     ct.interfaces_field == null) {
  2116                                 //not completed yet
  2117                                 partialCheck = true;
  2118                                 return;
  2120                             checkSymbol(pos, ct.supertype_field.tsym);
  2121                             for (Type intf : ct.interfaces_field) {
  2122                                 checkSymbol(pos, intf.tsym);
  2125                         if (c.owner.kind == TYP) {
  2126                             checkSymbol(pos, c.owner);
  2129                 } finally {
  2130                     seenClasses = seenClasses.tail;
  2136     /** Check for cyclic references. Issue an error if the
  2137      *  symbol of the type referred to has a LOCKED flag set.
  2139      *  @param pos      Position to be used for error reporting.
  2140      *  @param t        The type referred to.
  2141      */
  2142     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2143         checkNonCyclicInternal(pos, t);
  2147     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2148         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2151     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2152         final TypeVar tv;
  2153         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2154             return;
  2155         if (seen.contains(t)) {
  2156             tv = (TypeVar)t;
  2157             tv.bound = types.createErrorType(t);
  2158             log.error(pos, "cyclic.inheritance", t);
  2159         } else if (t.hasTag(TYPEVAR)) {
  2160             tv = (TypeVar)t;
  2161             seen = seen.prepend(tv);
  2162             for (Type b : types.getBounds(tv))
  2163                 checkNonCyclic1(pos, b, seen);
  2167     /** Check for cyclic references. Issue an error if the
  2168      *  symbol of the type referred to has a LOCKED flag set.
  2170      *  @param pos      Position to be used for error reporting.
  2171      *  @param t        The type referred to.
  2172      *  @returns        True if the check completed on all attributed classes
  2173      */
  2174     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2175         boolean complete = true; // was the check complete?
  2176         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2177         Symbol c = t.tsym;
  2178         if ((c.flags_field & ACYCLIC) != 0) return true;
  2180         if ((c.flags_field & LOCKED) != 0) {
  2181             noteCyclic(pos, (ClassSymbol)c);
  2182         } else if (!c.type.isErroneous()) {
  2183             try {
  2184                 c.flags_field |= LOCKED;
  2185                 if (c.type.hasTag(CLASS)) {
  2186                     ClassType clazz = (ClassType)c.type;
  2187                     if (clazz.interfaces_field != null)
  2188                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2189                             complete &= checkNonCyclicInternal(pos, l.head);
  2190                     if (clazz.supertype_field != null) {
  2191                         Type st = clazz.supertype_field;
  2192                         if (st != null && st.hasTag(CLASS))
  2193                             complete &= checkNonCyclicInternal(pos, st);
  2195                     if (c.owner.kind == TYP)
  2196                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2198             } finally {
  2199                 c.flags_field &= ~LOCKED;
  2202         if (complete)
  2203             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2204         if (complete) c.flags_field |= ACYCLIC;
  2205         return complete;
  2208     /** Note that we found an inheritance cycle. */
  2209     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2210         log.error(pos, "cyclic.inheritance", c);
  2211         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2212             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2213         Type st = types.supertype(c.type);
  2214         if (st.hasTag(CLASS))
  2215             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2216         c.type = types.createErrorType(c, c.type);
  2217         c.flags_field |= ACYCLIC;
  2220     /**
  2221      * Check that functional interface methods would make sense when seen
  2222      * from the perspective of the implementing class
  2223      */
  2224     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2225         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2226         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2227         c.interfaces_field = List.of(funcInterface);
  2228         c.supertype_field = syms.objectType;
  2229         c.tsym = csym;
  2230         csym.members_field = new Scope(csym);
  2231         csym.completer = null;
  2232         checkImplementations(tree, csym, csym);
  2235     /** Check that all methods which implement some
  2236      *  method conform to the method they implement.
  2237      *  @param tree         The class definition whose members are checked.
  2238      */
  2239     void checkImplementations(JCClassDecl tree) {
  2240         checkImplementations(tree, tree.sym, tree.sym);
  2242 //where
  2243         /** Check that all methods which implement some
  2244          *  method in `ic' conform to the method they implement.
  2245          */
  2246         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2247             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2248                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2249                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2250                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2251                         if (e.sym.kind == MTH &&
  2252                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2253                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2254                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2255                             if (implmeth != null && implmeth != absmeth &&
  2256                                 (implmeth.owner.flags() & INTERFACE) ==
  2257                                 (origin.flags() & INTERFACE)) {
  2258                                 // don't check if implmeth is in a class, yet
  2259                                 // origin is an interface. This case arises only
  2260                                 // if implmeth is declared in Object. The reason is
  2261                                 // that interfaces really don't inherit from
  2262                                 // Object it's just that the compiler represents
  2263                                 // things that way.
  2264                                 checkOverride(tree, implmeth, absmeth, origin);
  2272     /** Check that all abstract methods implemented by a class are
  2273      *  mutually compatible.
  2274      *  @param pos          Position to be used for error reporting.
  2275      *  @param c            The class whose interfaces are checked.
  2276      */
  2277     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2278         List<Type> supertypes = types.interfaces(c);
  2279         Type supertype = types.supertype(c);
  2280         if (supertype.hasTag(CLASS) &&
  2281             (supertype.tsym.flags() & ABSTRACT) != 0)
  2282             supertypes = supertypes.prepend(supertype);
  2283         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2284             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2285                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2286                 return;
  2287             for (List<Type> m = supertypes; m != l; m = m.tail)
  2288                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2289                     return;
  2291         checkCompatibleConcretes(pos, c);
  2294     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2295         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2296             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2297                 // VM allows methods and variables with differing types
  2298                 if (sym.kind == e.sym.kind &&
  2299                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2300                     sym != e.sym &&
  2301                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2302                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2303                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2304                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2305                     return;
  2311     /** Check that all non-override equivalent methods accessible from 'site'
  2312      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2314      *  @param pos  Position to be used for error reporting.
  2315      *  @param site The class whose methods are checked.
  2316      *  @param sym  The method symbol to be checked.
  2317      */
  2318     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2319          ClashFilter cf = new ClashFilter(site);
  2320         //for each method m1 that is overridden (directly or indirectly)
  2321         //by method 'sym' in 'site'...
  2322         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2323             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2324              //...check each method m2 that is a member of 'site'
  2325              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2326                 if (m2 == m1) continue;
  2327                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2328                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2329                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2330                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2331                     sym.flags_field |= CLASH;
  2332                     String key = m1 == sym ?
  2333                             "name.clash.same.erasure.no.override" :
  2334                             "name.clash.same.erasure.no.override.1";
  2335                     log.error(pos,
  2336                             key,
  2337                             sym, sym.location(),
  2338                             m2, m2.location(),
  2339                             m1, m1.location());
  2340                     return;
  2348     /** Check that all static methods accessible from 'site' are
  2349      *  mutually compatible (JLS 8.4.8).
  2351      *  @param pos  Position to be used for error reporting.
  2352      *  @param site The class whose methods are checked.
  2353      *  @param sym  The method symbol to be checked.
  2354      */
  2355     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2356         ClashFilter cf = new ClashFilter(site);
  2357         //for each method m1 that is a member of 'site'...
  2358         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2359             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2360             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2361             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2362                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2363                 log.error(pos,
  2364                         "name.clash.same.erasure.no.hide",
  2365                         sym, sym.location(),
  2366                         s, s.location());
  2367                 return;
  2372      //where
  2373      private class ClashFilter implements Filter<Symbol> {
  2375          Type site;
  2377          ClashFilter(Type site) {
  2378              this.site = site;
  2381          boolean shouldSkip(Symbol s) {
  2382              return (s.flags() & CLASH) != 0 &&
  2383                 s.owner == site.tsym;
  2386          public boolean accepts(Symbol s) {
  2387              return s.kind == MTH &&
  2388                      (s.flags() & SYNTHETIC) == 0 &&
  2389                      !shouldSkip(s) &&
  2390                      s.isInheritedIn(site.tsym, types) &&
  2391                      !s.isConstructor();
  2395     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2396         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2397         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2398             Assert.check(m.kind == MTH);
  2399             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2400             if (prov.size() > 1) {
  2401                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2402                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2403                 for (MethodSymbol provSym : prov) {
  2404                     if ((provSym.flags() & DEFAULT) != 0) {
  2405                         defaults = defaults.append(provSym);
  2406                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2407                         abstracts = abstracts.append(provSym);
  2409                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2410                         //strong semantics - issue an error if two sibling interfaces
  2411                         //have two override-equivalent defaults - or if one is abstract
  2412                         //and the other is default
  2413                         String errKey;
  2414                         Symbol s1 = defaults.first();
  2415                         Symbol s2;
  2416                         if (defaults.size() > 1) {
  2417                             errKey = "types.incompatible.unrelated.defaults";
  2418                             s2 = defaults.toList().tail.head;
  2419                         } else {
  2420                             errKey = "types.incompatible.abstract.default";
  2421                             s2 = abstracts.first();
  2423                         log.error(pos, errKey,
  2424                                 Kinds.kindName(site.tsym), site,
  2425                                 m.name, types.memberType(site, m).getParameterTypes(),
  2426                                 s1.location(), s2.location());
  2427                         break;
  2434     //where
  2435      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2437          Type site;
  2439          DefaultMethodClashFilter(Type site) {
  2440              this.site = site;
  2443          public boolean accepts(Symbol s) {
  2444              return s.kind == MTH &&
  2445                      (s.flags() & DEFAULT) != 0 &&
  2446                      s.isInheritedIn(site.tsym, types) &&
  2447                      !s.isConstructor();
  2451     /** Report a conflict between a user symbol and a synthetic symbol.
  2452      */
  2453     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2454         if (!sym.type.isErroneous()) {
  2455             if (warnOnSyntheticConflicts) {
  2456                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2458             else {
  2459                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2464     /** Check that class c does not implement directly or indirectly
  2465      *  the same parameterized interface with two different argument lists.
  2466      *  @param pos          Position to be used for error reporting.
  2467      *  @param type         The type whose interfaces are checked.
  2468      */
  2469     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2470         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2472 //where
  2473         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2474          *  with their class symbol as key and their type as value. Make
  2475          *  sure no class is entered with two different types.
  2476          */
  2477         void checkClassBounds(DiagnosticPosition pos,
  2478                               Map<TypeSymbol,Type> seensofar,
  2479                               Type type) {
  2480             if (type.isErroneous()) return;
  2481             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2482                 Type it = l.head;
  2483                 Type oldit = seensofar.put(it.tsym, it);
  2484                 if (oldit != null) {
  2485                     List<Type> oldparams = oldit.allparams();
  2486                     List<Type> newparams = it.allparams();
  2487                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2488                         log.error(pos, "cant.inherit.diff.arg",
  2489                                   it.tsym, Type.toString(oldparams),
  2490                                   Type.toString(newparams));
  2492                 checkClassBounds(pos, seensofar, it);
  2494             Type st = types.supertype(type);
  2495             if (st != null) checkClassBounds(pos, seensofar, st);
  2498     /** Enter interface into into set.
  2499      *  If it existed already, issue a "repeated interface" error.
  2500      */
  2501     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2502         if (its.contains(it))
  2503             log.error(pos, "repeated.interface");
  2504         else {
  2505             its.add(it);
  2509 /* *************************************************************************
  2510  * Check annotations
  2511  **************************************************************************/
  2513     /**
  2514      * Recursively validate annotations values
  2515      */
  2516     void validateAnnotationTree(JCTree tree) {
  2517         class AnnotationValidator extends TreeScanner {
  2518             @Override
  2519             public void visitAnnotation(JCAnnotation tree) {
  2520                 if (!tree.type.isErroneous()) {
  2521                     super.visitAnnotation(tree);
  2522                     validateAnnotation(tree);
  2526         tree.accept(new AnnotationValidator());
  2529     /**
  2530      *  {@literal
  2531      *  Annotation types are restricted to primitives, String, an
  2532      *  enum, an annotation, Class, Class<?>, Class<? extends
  2533      *  Anything>, arrays of the preceding.
  2534      *  }
  2535      */
  2536     void validateAnnotationType(JCTree restype) {
  2537         // restype may be null if an error occurred, so don't bother validating it
  2538         if (restype != null) {
  2539             validateAnnotationType(restype.pos(), restype.type);
  2543     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2544         if (type.isPrimitive()) return;
  2545         if (types.isSameType(type, syms.stringType)) return;
  2546         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2547         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2548         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2549         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2550             validateAnnotationType(pos, types.elemtype(type));
  2551             return;
  2553         log.error(pos, "invalid.annotation.member.type");
  2556     /**
  2557      * "It is also a compile-time error if any method declared in an
  2558      * annotation type has a signature that is override-equivalent to
  2559      * that of any public or protected method declared in class Object
  2560      * or in the interface annotation.Annotation."
  2562      * @jls 9.6 Annotation Types
  2563      */
  2564     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2565         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2566             Scope s = sup.tsym.members();
  2567             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2568                 if (e.sym.kind == MTH &&
  2569                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2570                     types.overrideEquivalent(m.type, e.sym.type))
  2571                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2576     /** Check the annotations of a symbol.
  2577      */
  2578     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2579         for (JCAnnotation a : annotations)
  2580             validateAnnotation(a, s);
  2583     /** Check an annotation of a symbol.
  2584      */
  2585     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2586         validateAnnotationTree(a);
  2588         if (!annotationApplicable(a, s))
  2589             log.error(a.pos(), "annotation.type.not.applicable");
  2591         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2592             if (!isOverrider(s))
  2593                 log.error(a.pos(), "method.does.not.override.superclass");
  2596         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2597             if (s.kind != TYP) {
  2598                 log.error(a.pos(), "bad.functional.intf.anno");
  2599             } else {
  2600                 try {
  2601                     types.findDescriptorSymbol((TypeSymbol)s);
  2602                 } catch (Types.FunctionDescriptorLookupError ex) {
  2603                     log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
  2609     /**
  2610      * Validate the proposed container 'repeatable' on the
  2611      * annotation type symbol 's'. Report errors at position
  2612      * 'pos'.
  2614      * @param s The (annotation)type declaration annotated with a @Repeatable
  2615      * @param repeatable the @Repeatable on 's'
  2616      * @param pos where to report errors
  2617      */
  2618     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2619         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2621         Type t = null;
  2622         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2623         if (!l.isEmpty()) {
  2624             Assert.check(l.head.fst.name == names.value);
  2625             t = ((Attribute.Class)l.head.snd).getValue();
  2628         if (t == null) {
  2629             // errors should already have been reported during Annotate
  2630             return;
  2633         validateValue(t.tsym, s, pos);
  2634         validateRetention(t.tsym, s, pos);
  2635         validateDocumented(t.tsym, s, pos);
  2636         validateInherited(t.tsym, s, pos);
  2637         validateTarget(t.tsym, s, pos);
  2638         validateDefault(t.tsym, s, pos);
  2641     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2642         Scope.Entry e = container.members().lookup(names.value);
  2643         if (e.scope != null && e.sym.kind == MTH) {
  2644             MethodSymbol m = (MethodSymbol) e.sym;
  2645             Type ret = m.getReturnType();
  2646             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2647                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2648                         container, ret, types.makeArrayType(contained.type));
  2650         } else {
  2651             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2655     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2656         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2657         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2659         boolean error = false;
  2660         switch (containedRetention) {
  2661         case RUNTIME:
  2662             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2663                 error = true;
  2665             break;
  2666         case CLASS:
  2667             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2668                 error = true;
  2671         if (error ) {
  2672             log.error(pos, "invalid.repeatable.annotation.retention",
  2673                       container, containerRetention,
  2674                       contained, containedRetention);
  2678     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2679         if (contained.attribute(syms.documentedType.tsym) != null) {
  2680             if (container.attribute(syms.documentedType.tsym) == null) {
  2681                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2686     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2687         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2688             if (container.attribute(syms.inheritedType.tsym) == null) {
  2689                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2694     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2695         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2697         // If contained has no Target, we are done
  2698         if (containedTarget == null) {
  2699             return;
  2702         // If contained has Target m1, container must have a Target
  2703         // annotation, m2, and m2 must be a subset of m1. (This is
  2704         // trivially true if contained has no target as per above).
  2706         // contained has target, but container has not, error
  2707         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2708         if (containerTarget == null) {
  2709             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2710             return;
  2713         Set<Name> containerTargets = new HashSet<Name>();
  2714         for (Attribute app : containerTarget.values) {
  2715             if (!(app instanceof Attribute.Enum)) {
  2716                 continue; // recovery
  2718             Attribute.Enum e = (Attribute.Enum)app;
  2719             containerTargets.add(e.value.name);
  2722         Set<Name> containedTargets = new HashSet<Name>();
  2723         for (Attribute app : containedTarget.values) {
  2724             if (!(app instanceof Attribute.Enum)) {
  2725                 continue; // recovery
  2727             Attribute.Enum e = (Attribute.Enum)app;
  2728             containedTargets.add(e.value.name);
  2731         if (!isTargetSubset(containedTargets, containerTargets)) {
  2732             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2736     /** Checks that t is a subset of s, with respect to ElementType
  2737      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2738      */
  2739     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2740         // Check that all elements in t are present in s
  2741         for (Name n2 : t) {
  2742             boolean currentElementOk = false;
  2743             for (Name n1 : s) {
  2744                 if (n1 == n2) {
  2745                     currentElementOk = true;
  2746                     break;
  2747                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2748                     currentElementOk = true;
  2749                     break;
  2752             if (!currentElementOk)
  2753                 return false;
  2755         return true;
  2758     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2759         // validate that all other elements of containing type has defaults
  2760         Scope scope = container.members();
  2761         for(Symbol elm : scope.getElements()) {
  2762             if (elm.name != names.value &&
  2763                 elm.kind == Kinds.MTH &&
  2764                 ((MethodSymbol)elm).defaultValue == null) {
  2765                 log.error(pos,
  2766                           "invalid.repeatable.annotation.elem.nondefault",
  2767                           container,
  2768                           elm);
  2773     /** Is s a method symbol that overrides a method in a superclass? */
  2774     boolean isOverrider(Symbol s) {
  2775         if (s.kind != MTH || s.isStatic())
  2776             return false;
  2777         MethodSymbol m = (MethodSymbol)s;
  2778         TypeSymbol owner = (TypeSymbol)m.owner;
  2779         for (Type sup : types.closure(owner.type)) {
  2780             if (sup == owner.type)
  2781                 continue; // skip "this"
  2782             Scope scope = sup.tsym.members();
  2783             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2784                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2785                     return true;
  2788         return false;
  2791     /** Is the annotation applicable to the symbol? */
  2792     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2793         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2794         if (arr == null) {
  2795             return true;
  2797         for (Attribute app : arr.values) {
  2798             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2799             Attribute.Enum e = (Attribute.Enum) app;
  2800             if (e.value.name == names.TYPE)
  2801                 { if (s.kind == TYP) return true; }
  2802             else if (e.value.name == names.FIELD)
  2803                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2804             else if (e.value.name == names.METHOD)
  2805                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2806             else if (e.value.name == names.PARAMETER)
  2807                 { if (s.kind == VAR &&
  2808                       s.owner.kind == MTH &&
  2809                       (s.flags() & PARAMETER) != 0)
  2810                     return true;
  2812             else if (e.value.name == names.CONSTRUCTOR)
  2813                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2814             else if (e.value.name == names.LOCAL_VARIABLE)
  2815                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2816                       (s.flags() & PARAMETER) == 0)
  2817                     return true;
  2819             else if (e.value.name == names.ANNOTATION_TYPE)
  2820                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2821                     return true;
  2823             else if (e.value.name == names.PACKAGE)
  2824                 { if (s.kind == PCK) return true; }
  2825             else if (e.value.name == names.TYPE_USE)
  2826                 { if (s.kind == TYP ||
  2827                       s.kind == VAR ||
  2828                       (s.kind == MTH && !s.isConstructor() &&
  2829                        !s.type.getReturnType().hasTag(VOID)))
  2830                     return true;
  2832             else
  2833                 return true; // recovery
  2835         return false;
  2839     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2840         Attribute.Compound atTarget =
  2841             s.attribute(syms.annotationTargetType.tsym);
  2842         if (atTarget == null) return null; // ok, is applicable
  2843         Attribute atValue = atTarget.member(names.value);
  2844         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2845         return (Attribute.Array) atValue;
  2848     /** Check an annotation value.
  2850      * @param a The annotation tree to check
  2851      * @return true if this annotation tree is valid, otherwise false
  2852      */
  2853     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  2854         boolean res = false;
  2855         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  2856         try {
  2857             res = validateAnnotation(a);
  2858         } finally {
  2859             log.popDiagnosticHandler(diagHandler);
  2861         return res;
  2864     private boolean validateAnnotation(JCAnnotation a) {
  2865         boolean isValid = true;
  2866         // collect an inventory of the annotation elements
  2867         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  2868         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2869              e != null;
  2870              e = e.sibling)
  2871             if (e.sym.kind == MTH)
  2872                 members.add((MethodSymbol) e.sym);
  2874         // remove the ones that are assigned values
  2875         for (JCTree arg : a.args) {
  2876             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2877             JCAssign assign = (JCAssign) arg;
  2878             Symbol m = TreeInfo.symbol(assign.lhs);
  2879             if (m == null || m.type.isErroneous()) continue;
  2880             if (!members.remove(m)) {
  2881                 isValid = false;
  2882                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2883                           m.name, a.type);
  2887         // all the remaining ones better have default values
  2888         List<Name> missingDefaults = List.nil();
  2889         for (MethodSymbol m : members) {
  2890             if (m.defaultValue == null && !m.type.isErroneous()) {
  2891                 missingDefaults = missingDefaults.append(m.name);
  2894         missingDefaults = missingDefaults.reverse();
  2895         if (missingDefaults.nonEmpty()) {
  2896             isValid = false;
  2897             String key = (missingDefaults.size() > 1)
  2898                     ? "annotation.missing.default.value.1"
  2899                     : "annotation.missing.default.value";
  2900             log.error(a.pos(), key, a.type, missingDefaults);
  2903         // special case: java.lang.annotation.Target must not have
  2904         // repeated values in its value member
  2905         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2906             a.args.tail == null)
  2907             return isValid;
  2909         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  2910         JCAssign assign = (JCAssign) a.args.head;
  2911         Symbol m = TreeInfo.symbol(assign.lhs);
  2912         if (m.name != names.value) return false;
  2913         JCTree rhs = assign.rhs;
  2914         if (!rhs.hasTag(NEWARRAY)) return false;
  2915         JCNewArray na = (JCNewArray) rhs;
  2916         Set<Symbol> targets = new HashSet<Symbol>();
  2917         for (JCTree elem : na.elems) {
  2918             if (!targets.add(TreeInfo.symbol(elem))) {
  2919                 isValid = false;
  2920                 log.error(elem.pos(), "repeated.annotation.target");
  2923         return isValid;
  2926     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2927         if (allowAnnotations &&
  2928             lint.isEnabled(LintCategory.DEP_ANN) &&
  2929             (s.flags() & DEPRECATED) != 0 &&
  2930             !syms.deprecatedType.isErroneous() &&
  2931             s.attribute(syms.deprecatedType.tsym) == null) {
  2932             log.warning(LintCategory.DEP_ANN,
  2933                     pos, "missing.deprecated.annotation");
  2937     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2938         if ((s.flags() & DEPRECATED) != 0 &&
  2939                 (other.flags() & DEPRECATED) == 0 &&
  2940                 s.outermostClass() != other.outermostClass()) {
  2941             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2942                 @Override
  2943                 public void report() {
  2944                     warnDeprecated(pos, s);
  2946             });
  2950     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2951         if ((s.flags() & PROPRIETARY) != 0) {
  2952             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2953                 public void report() {
  2954                     if (enableSunApiLintControl)
  2955                       warnSunApi(pos, "sun.proprietary", s);
  2956                     else
  2957                       log.mandatoryWarning(pos, "sun.proprietary", s);
  2959             });
  2963 /* *************************************************************************
  2964  * Check for recursive annotation elements.
  2965  **************************************************************************/
  2967     /** Check for cycles in the graph of annotation elements.
  2968      */
  2969     void checkNonCyclicElements(JCClassDecl tree) {
  2970         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2971         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2972         try {
  2973             tree.sym.flags_field |= LOCKED;
  2974             for (JCTree def : tree.defs) {
  2975                 if (!def.hasTag(METHODDEF)) continue;
  2976                 JCMethodDecl meth = (JCMethodDecl)def;
  2977                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2979         } finally {
  2980             tree.sym.flags_field &= ~LOCKED;
  2981             tree.sym.flags_field |= ACYCLIC_ANN;
  2985     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2986         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2987             return;
  2988         if ((tsym.flags_field & LOCKED) != 0) {
  2989             log.error(pos, "cyclic.annotation.element");
  2990             return;
  2992         try {
  2993             tsym.flags_field |= LOCKED;
  2994             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2995                 Symbol s = e.sym;
  2996                 if (s.kind != Kinds.MTH)
  2997                     continue;
  2998                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3000         } finally {
  3001             tsym.flags_field &= ~LOCKED;
  3002             tsym.flags_field |= ACYCLIC_ANN;
  3006     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3007         switch (type.getTag()) {
  3008         case CLASS:
  3009             if ((type.tsym.flags() & ANNOTATION) != 0)
  3010                 checkNonCyclicElementsInternal(pos, type.tsym);
  3011             break;
  3012         case ARRAY:
  3013             checkAnnotationResType(pos, types.elemtype(type));
  3014             break;
  3015         default:
  3016             break; // int etc
  3020 /* *************************************************************************
  3021  * Check for cycles in the constructor call graph.
  3022  **************************************************************************/
  3024     /** Check for cycles in the graph of constructors calling other
  3025      *  constructors.
  3026      */
  3027     void checkCyclicConstructors(JCClassDecl tree) {
  3028         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3030         // enter each constructor this-call into the map
  3031         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3032             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3033             if (app == null) continue;
  3034             JCMethodDecl meth = (JCMethodDecl) l.head;
  3035             if (TreeInfo.name(app.meth) == names._this) {
  3036                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3037             } else {
  3038                 meth.sym.flags_field |= ACYCLIC;
  3042         // Check for cycles in the map
  3043         Symbol[] ctors = new Symbol[0];
  3044         ctors = callMap.keySet().toArray(ctors);
  3045         for (Symbol caller : ctors) {
  3046             checkCyclicConstructor(tree, caller, callMap);
  3050     /** Look in the map to see if the given constructor is part of a
  3051      *  call cycle.
  3052      */
  3053     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3054                                         Map<Symbol,Symbol> callMap) {
  3055         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3056             if ((ctor.flags_field & LOCKED) != 0) {
  3057                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3058                           "recursive.ctor.invocation");
  3059             } else {
  3060                 ctor.flags_field |= LOCKED;
  3061                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3062                 ctor.flags_field &= ~LOCKED;
  3064             ctor.flags_field |= ACYCLIC;
  3068 /* *************************************************************************
  3069  * Miscellaneous
  3070  **************************************************************************/
  3072     /**
  3073      * Return the opcode of the operator but emit an error if it is an
  3074      * error.
  3075      * @param pos        position for error reporting.
  3076      * @param operator   an operator
  3077      * @param tag        a tree tag
  3078      * @param left       type of left hand side
  3079      * @param right      type of right hand side
  3080      */
  3081     int checkOperator(DiagnosticPosition pos,
  3082                        OperatorSymbol operator,
  3083                        JCTree.Tag tag,
  3084                        Type left,
  3085                        Type right) {
  3086         if (operator.opcode == ByteCodes.error) {
  3087             log.error(pos,
  3088                       "operator.cant.be.applied.1",
  3089                       treeinfo.operatorName(tag),
  3090                       left, right);
  3092         return operator.opcode;
  3096     /**
  3097      *  Check for division by integer constant zero
  3098      *  @param pos           Position for error reporting.
  3099      *  @param operator      The operator for the expression
  3100      *  @param operand       The right hand operand for the expression
  3101      */
  3102     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3103         if (operand.constValue() != null
  3104             && lint.isEnabled(LintCategory.DIVZERO)
  3105             && (operand.getTag().isSubRangeOf(LONG))
  3106             && ((Number) (operand.constValue())).longValue() == 0) {
  3107             int opc = ((OperatorSymbol)operator).opcode;
  3108             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3109                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3110                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3115     /**
  3116      * Check for empty statements after if
  3117      */
  3118     void checkEmptyIf(JCIf tree) {
  3119         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3120                 lint.isEnabled(LintCategory.EMPTY))
  3121             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3124     /** Check that symbol is unique in given scope.
  3125      *  @param pos           Position for error reporting.
  3126      *  @param sym           The symbol.
  3127      *  @param s             The scope.
  3128      */
  3129     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3130         if (sym.type.isErroneous())
  3131             return true;
  3132         if (sym.owner.name == names.any) return false;
  3133         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3134             if (sym != e.sym &&
  3135                     (e.sym.flags() & CLASH) == 0 &&
  3136                     sym.kind == e.sym.kind &&
  3137                     sym.name != names.error &&
  3138                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3139                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3140                     varargsDuplicateError(pos, sym, e.sym);
  3141                     return true;
  3142                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3143                     duplicateErasureError(pos, sym, e.sym);
  3144                     sym.flags_field |= CLASH;
  3145                     return true;
  3146                 } else {
  3147                     duplicateError(pos, e.sym);
  3148                     return false;
  3152         return true;
  3155     /** Report duplicate declaration error.
  3156      */
  3157     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3158         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3159             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3163     /** Check that single-type import is not already imported or top-level defined,
  3164      *  but make an exception for two single-type imports which denote the same type.
  3165      *  @param pos           Position for error reporting.
  3166      *  @param sym           The symbol.
  3167      *  @param s             The scope
  3168      */
  3169     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3170         return checkUniqueImport(pos, sym, s, false);
  3173     /** Check that static single-type import is not already imported or top-level defined,
  3174      *  but make an exception for two single-type imports which denote the same type.
  3175      *  @param pos           Position for error reporting.
  3176      *  @param sym           The symbol.
  3177      *  @param s             The scope
  3178      */
  3179     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3180         return checkUniqueImport(pos, sym, s, true);
  3183     /** Check that single-type import is not already imported or top-level defined,
  3184      *  but make an exception for two single-type imports which denote the same type.
  3185      *  @param pos           Position for error reporting.
  3186      *  @param sym           The symbol.
  3187      *  @param s             The scope.
  3188      *  @param staticImport  Whether or not this was a static import
  3189      */
  3190     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3191         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3192             // is encountered class entered via a class declaration?
  3193             boolean isClassDecl = e.scope == s;
  3194             if ((isClassDecl || sym != e.sym) &&
  3195                 sym.kind == e.sym.kind &&
  3196                 sym.name != names.error) {
  3197                 if (!e.sym.type.isErroneous()) {
  3198                     String what = e.sym.toString();
  3199                     if (!isClassDecl) {
  3200                         if (staticImport)
  3201                             log.error(pos, "already.defined.static.single.import", what);
  3202                         else
  3203                             log.error(pos, "already.defined.single.import", what);
  3205                     else if (sym != e.sym)
  3206                         log.error(pos, "already.defined.this.unit", what);
  3208                 return false;
  3211         return true;
  3214     /** Check that a qualified name is in canonical form (for import decls).
  3215      */
  3216     public void checkCanonical(JCTree tree) {
  3217         if (!isCanonical(tree))
  3218             log.error(tree.pos(), "import.requires.canonical",
  3219                       TreeInfo.symbol(tree));
  3221         // where
  3222         private boolean isCanonical(JCTree tree) {
  3223             while (tree.hasTag(SELECT)) {
  3224                 JCFieldAccess s = (JCFieldAccess) tree;
  3225                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3226                     return false;
  3227                 tree = s.selected;
  3229             return true;
  3232     /** Check that an auxiliary class is not accessed from any other file than its own.
  3233      */
  3234     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3235         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3236             (c.flags() & AUXILIARY) != 0 &&
  3237             rs.isAccessible(env, c) &&
  3238             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3240             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3241                         c, c.sourcefile);
  3245     private class ConversionWarner extends Warner {
  3246         final String uncheckedKey;
  3247         final Type found;
  3248         final Type expected;
  3249         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3250             super(pos);
  3251             this.uncheckedKey = uncheckedKey;
  3252             this.found = found;
  3253             this.expected = expected;
  3256         @Override
  3257         public void warn(LintCategory lint) {
  3258             boolean warned = this.warned;
  3259             super.warn(lint);
  3260             if (warned) return; // suppress redundant diagnostics
  3261             switch (lint) {
  3262                 case UNCHECKED:
  3263                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3264                     break;
  3265                 case VARARGS:
  3266                     if (method != null &&
  3267                             method.attribute(syms.trustMeType.tsym) != null &&
  3268                             isTrustMeAllowedOnMethod(method) &&
  3269                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3270                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3272                     break;
  3273                 default:
  3274                     throw new AssertionError("Unexpected lint: " + lint);
  3279     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3280         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3283     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3284         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial