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

Wed, 06 Feb 2013 14:03:39 +0000

author
mcimadamore
date
Wed, 06 Feb 2013 14:03:39 +0000
changeset 1550
1df20330f6bd
parent 1521
71f35e4b93a5
child 1555
762d0af062f5
permissions
-rw-r--r--

8007463: Cleanup inference related classes
Summary: Make Infer.InferenceContext an inner class; adjust bound replacement logic in Type.UndetVar
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    30 import javax.tools.JavaFileManager;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.jvm.*;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.util.*;
    36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    37 import com.sun.tools.javac.util.List;
    39 import com.sun.tools.javac.code.Lint;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    44 import com.sun.tools.javac.comp.Infer.InferenceContext;
    45 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    46 import com.sun.tools.javac.tree.JCTree.*;
    47 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    49 import static com.sun.tools.javac.code.Flags.*;
    50 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    51 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    52 import static com.sun.tools.javac.code.Kinds.*;
    53 import static com.sun.tools.javac.code.TypeTag.*;
    54 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    56 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    58 /** Type checking helper class for the attribution phase.
    59  *
    60  *  <p><b>This is NOT part of any supported API.
    61  *  If you write code that depends on this, you do so at your own risk.
    62  *  This code and its internal interfaces are subject to change or
    63  *  deletion without notice.</b>
    64  */
    65 public class Check {
    66     protected static final Context.Key<Check> checkKey =
    67         new Context.Key<Check>();
    69     private final Names names;
    70     private final Log log;
    71     private final Resolve rs;
    72     private final Symtab syms;
    73     private final Enter enter;
    74     private final DeferredAttr deferredAttr;
    75     private final Infer infer;
    76     private final Types types;
    77     private final JCDiagnostic.Factory diags;
    78     private boolean warnOnSyntheticConflicts;
    79     private boolean suppressAbortOnBadClassFile;
    80     private boolean enableSunApiLintControl;
    81     private final TreeInfo treeinfo;
    82     private final JavaFileManager fileManager;
    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         dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE,
   105             names.FIELD, names.METHOD, names.CONSTRUCTOR,
   106             names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER};
   107         log = Log.instance(context);
   108         rs = Resolve.instance(context);
   109         syms = Symtab.instance(context);
   110         enter = Enter.instance(context);
   111         deferredAttr = DeferredAttr.instance(context);
   112         infer = Infer.instance(context);
   113         this.types = Types.instance(context);
   114         diags = JCDiagnostic.Factory.instance(context);
   115         Options options = Options.instance(context);
   116         lint = Lint.instance(context);
   117         treeinfo = TreeInfo.instance(context);
   118         fileManager = context.get(JavaFileManager.class);
   120         Source source = Source.instance(context);
   121         allowGenerics = source.allowGenerics();
   122         allowVarargs = source.allowVarargs();
   123         allowAnnotations = source.allowAnnotations();
   124         allowCovariantReturns = source.allowCovariantReturns();
   125         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   126         allowDefaultMethods = source.allowDefaultMethods();
   127         allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
   128         complexInference = options.isSet("complexinference");
   129         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   130         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   131         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   133         Target target = Target.instance(context);
   134         syntheticNameChar = target.syntheticNameChar();
   136         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   137         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   138         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   139         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   141         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   142                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   143         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   144                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   145         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   146                 enforceMandatoryWarnings, "sunapi", null);
   148         deferredLintHandler = DeferredLintHandler.immediateHandler;
   149     }
   151     /** Switch: generics enabled?
   152      */
   153     boolean allowGenerics;
   155     /** Switch: varargs enabled?
   156      */
   157     boolean allowVarargs;
   159     /** Switch: annotations enabled?
   160      */
   161     boolean allowAnnotations;
   163     /** Switch: covariant returns enabled?
   164      */
   165     boolean allowCovariantReturns;
   167     /** Switch: simplified varargs enabled?
   168      */
   169     boolean allowSimplifiedVarargs;
   171     /** Switch: default methods enabled?
   172      */
   173     boolean allowDefaultMethods;
   175     /** Switch: should unrelated return types trigger a method clash?
   176      */
   177     boolean allowStrictMethodClashCheck;
   179     /** Switch: -complexinference option set?
   180      */
   181     boolean complexInference;
   183     /** Character for synthetic names
   184      */
   185     char syntheticNameChar;
   187     /** A table mapping flat names of all compiled classes in this run to their
   188      *  symbols; maintained from outside.
   189      */
   190     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   192     /** A handler for messages about deprecated usage.
   193      */
   194     private MandatoryWarningHandler deprecationHandler;
   196     /** A handler for messages about unchecked or unsafe usage.
   197      */
   198     private MandatoryWarningHandler uncheckedHandler;
   200     /** A handler for messages about using proprietary API.
   201      */
   202     private MandatoryWarningHandler sunApiHandler;
   204     /** A handler for deferred lint warnings.
   205      */
   206     private DeferredLintHandler deferredLintHandler;
   208 /* *************************************************************************
   209  * Errors and Warnings
   210  **************************************************************************/
   212     Lint setLint(Lint newLint) {
   213         Lint prev = lint;
   214         lint = newLint;
   215         return prev;
   216     }
   218     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   219         DeferredLintHandler prev = deferredLintHandler;
   220         deferredLintHandler = newDeferredLintHandler;
   221         return prev;
   222     }
   224     MethodSymbol setMethod(MethodSymbol newMethod) {
   225         MethodSymbol prev = method;
   226         method = newMethod;
   227         return prev;
   228     }
   230     /** Warn about deprecated symbol.
   231      *  @param pos        Position to be used for error reporting.
   232      *  @param sym        The deprecated symbol.
   233      */
   234     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   235         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   236             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   237     }
   239     /** Warn about unchecked operation.
   240      *  @param pos        Position to be used for error reporting.
   241      *  @param msg        A string describing the problem.
   242      */
   243     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   244         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   245             uncheckedHandler.report(pos, msg, args);
   246     }
   248     /** Warn about unsafe vararg method decl.
   249      *  @param pos        Position to be used for error reporting.
   250      */
   251     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   252         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   253             log.warning(LintCategory.VARARGS, pos, key, args);
   254     }
   256     /** Warn about using proprietary API.
   257      *  @param pos        Position to be used for error reporting.
   258      *  @param msg        A string describing the problem.
   259      */
   260     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   261         if (!lint.isSuppressed(LintCategory.SUNAPI))
   262             sunApiHandler.report(pos, msg, args);
   263     }
   265     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   266         if (lint.isEnabled(LintCategory.STATIC))
   267             log.warning(LintCategory.STATIC, pos, msg, args);
   268     }
   270     /**
   271      * Report any deferred diagnostics.
   272      */
   273     public void reportDeferredDiagnostics() {
   274         deprecationHandler.reportDeferredDiagnostic();
   275         uncheckedHandler.reportDeferredDiagnostic();
   276         sunApiHandler.reportDeferredDiagnostic();
   277     }
   280     /** Report a failure to complete a class.
   281      *  @param pos        Position to be used for error reporting.
   282      *  @param ex         The failure to report.
   283      */
   284     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   285         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   286         if (ex instanceof ClassReader.BadClassFile
   287                 && !suppressAbortOnBadClassFile) throw new Abort();
   288         else return syms.errType;
   289     }
   291     /** Report an error that wrong type tag was found.
   292      *  @param pos        Position to be used for error reporting.
   293      *  @param required   An internationalized string describing the type tag
   294      *                    required.
   295      *  @param found      The type that was found.
   296      */
   297     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   298         // this error used to be raised by the parser,
   299         // but has been delayed to this point:
   300         if (found instanceof Type && ((Type)found).hasTag(VOID)) {
   301             log.error(pos, "illegal.start.of.type");
   302             return syms.errType;
   303         }
   304         log.error(pos, "type.found.req", found, required);
   305         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   306     }
   308     /** Report an error that symbol cannot be referenced before super
   309      *  has been called.
   310      *  @param pos        Position to be used for error reporting.
   311      *  @param sym        The referenced symbol.
   312      */
   313     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   314         log.error(pos, "cant.ref.before.ctor.called", sym);
   315     }
   317     /** Report duplicate declaration error.
   318      */
   319     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   320         if (!sym.type.isErroneous()) {
   321             Symbol location = sym.location();
   322             if (location.kind == MTH &&
   323                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   324                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   325                         kindName(sym.location()), kindName(sym.location().enclClass()),
   326                         sym.location().enclClass());
   327             } else {
   328                 log.error(pos, "already.defined", kindName(sym), sym,
   329                         kindName(sym.location()), sym.location());
   330             }
   331         }
   332     }
   334     /** Report array/varargs duplicate declaration
   335      */
   336     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   337         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   338             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   339         }
   340     }
   342 /* ************************************************************************
   343  * duplicate declaration checking
   344  *************************************************************************/
   346     /** Check that variable does not hide variable with same name in
   347      *  immediately enclosing local scope.
   348      *  @param pos           Position for error reporting.
   349      *  @param v             The symbol.
   350      *  @param s             The scope.
   351      */
   352     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   353         if (s.next != null) {
   354             for (Scope.Entry e = s.next.lookup(v.name);
   355                  e.scope != null && e.sym.owner == v.owner;
   356                  e = e.next()) {
   357                 if (e.sym.kind == VAR &&
   358                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   359                     v.name != names.error) {
   360                     duplicateError(pos, e.sym);
   361                     return;
   362                 }
   363             }
   364         }
   365     }
   367     /** Check that a class or interface does not hide a class or
   368      *  interface with same name in immediately enclosing local scope.
   369      *  @param pos           Position for error reporting.
   370      *  @param c             The symbol.
   371      *  @param s             The scope.
   372      */
   373     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   374         if (s.next != null) {
   375             for (Scope.Entry e = s.next.lookup(c.name);
   376                  e.scope != null && e.sym.owner == c.owner;
   377                  e = e.next()) {
   378                 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
   379                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   380                     c.name != names.error) {
   381                     duplicateError(pos, e.sym);
   382                     return;
   383                 }
   384             }
   385         }
   386     }
   388     /** Check that class does not have the same name as one of
   389      *  its enclosing classes, or as a class defined in its enclosing scope.
   390      *  return true if class is unique in its enclosing scope.
   391      *  @param pos           Position for error reporting.
   392      *  @param name          The class name.
   393      *  @param s             The enclosing scope.
   394      */
   395     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   396         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   397             if (e.sym.kind == TYP && e.sym.name != names.error) {
   398                 duplicateError(pos, e.sym);
   399                 return false;
   400             }
   401         }
   402         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   403             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   404                 duplicateError(pos, sym);
   405                 return true;
   406             }
   407         }
   408         return true;
   409     }
   411 /* *************************************************************************
   412  * Class name generation
   413  **************************************************************************/
   415     /** Return name of local class.
   416      *  This is of the form   {@code <enclClass> $ n <classname> }
   417      *  where
   418      *    enclClass is the flat name of the enclosing class,
   419      *    classname is the simple name of the local class
   420      */
   421     Name localClassName(ClassSymbol c) {
   422         for (int i=1; ; i++) {
   423             Name flatname = names.
   424                 fromString("" + c.owner.enclClass().flatname +
   425                            syntheticNameChar + i +
   426                            c.name);
   427             if (compiled.get(flatname) == null) return flatname;
   428         }
   429     }
   431 /* *************************************************************************
   432  * Type Checking
   433  **************************************************************************/
   435     /**
   436      * A check context is an object that can be used to perform compatibility
   437      * checks - depending on the check context, meaning of 'compatibility' might
   438      * vary significantly.
   439      */
   440     public interface CheckContext {
   441         /**
   442          * Is type 'found' compatible with type 'req' in given context
   443          */
   444         boolean compatible(Type found, Type req, Warner warn);
   445         /**
   446          * Report a check error
   447          */
   448         void report(DiagnosticPosition pos, JCDiagnostic details);
   449         /**
   450          * Obtain a warner for this check context
   451          */
   452         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   454         public Infer.InferenceContext inferenceContext();
   456         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   457     }
   459     /**
   460      * This class represent a check context that is nested within another check
   461      * context - useful to check sub-expressions. The default behavior simply
   462      * redirects all method calls to the enclosing check context leveraging
   463      * the forwarding pattern.
   464      */
   465     static class NestedCheckContext implements CheckContext {
   466         CheckContext enclosingContext;
   468         NestedCheckContext(CheckContext enclosingContext) {
   469             this.enclosingContext = enclosingContext;
   470         }
   472         public boolean compatible(Type found, Type req, Warner warn) {
   473             return enclosingContext.compatible(found, req, warn);
   474         }
   476         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   477             enclosingContext.report(pos, details);
   478         }
   480         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   481             return enclosingContext.checkWarner(pos, found, req);
   482         }
   484         public Infer.InferenceContext inferenceContext() {
   485             return enclosingContext.inferenceContext();
   486         }
   488         public DeferredAttrContext deferredAttrContext() {
   489             return enclosingContext.deferredAttrContext();
   490         }
   491     }
   493     /**
   494      * Check context to be used when evaluating assignment/return statements
   495      */
   496     CheckContext basicHandler = new CheckContext() {
   497         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   498             log.error(pos, "prob.found.req", details);
   499         }
   500         public boolean compatible(Type found, Type req, Warner warn) {
   501             return types.isAssignable(found, req, warn);
   502         }
   504         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   505             return convertWarner(pos, found, req);
   506         }
   508         public InferenceContext inferenceContext() {
   509             return infer.emptyContext;
   510         }
   512         public DeferredAttrContext deferredAttrContext() {
   513             return deferredAttr.emptyDeferredAttrContext;
   514         }
   515     };
   517     /** Check that a given type is assignable to a given proto-type.
   518      *  If it is, return the type, otherwise return errType.
   519      *  @param pos        Position to be used for error reporting.
   520      *  @param found      The type that was found.
   521      *  @param req        The type that was required.
   522      */
   523     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   524         return checkType(pos, found, req, basicHandler);
   525     }
   527     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   528         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   529         if (inferenceContext.free(req)) {
   530             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   531                 @Override
   532                 public void typesInferred(InferenceContext inferenceContext) {
   533                     checkType(pos, found, inferenceContext.asInstType(req), checkContext);
   534                 }
   535             });
   536         }
   537         if (req.hasTag(ERROR))
   538             return req;
   539         if (req.hasTag(NONE))
   540             return found;
   541         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   542             return found;
   543         } else {
   544             if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
   545                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   546                 return types.createErrorType(found);
   547             }
   548             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   549             return types.createErrorType(found);
   550         }
   551     }
   553     /** Check that a given type can be cast to a given target type.
   554      *  Return the result of the cast.
   555      *  @param pos        Position to be used for error reporting.
   556      *  @param found      The type that is being cast.
   557      *  @param req        The target type of the cast.
   558      */
   559     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   560         return checkCastable(pos, found, req, basicHandler);
   561     }
   562     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   563         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   564             return req;
   565         } else {
   566             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   567             return types.createErrorType(found);
   568         }
   569     }
   571     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   572      * The problem should only be reported for non-292 cast
   573      */
   574     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   575         if (!tree.type.isErroneous() &&
   576                 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   577                 && types.isSameType(tree.expr.type, tree.clazz.type)
   578                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
   579                 && !is292targetTypeCast(tree)) {
   580             log.warning(Lint.LintCategory.CAST,
   581                     tree.pos(), "redundant.cast", tree.expr.type);
   582         }
   583     }
   584     //where
   585         private boolean is292targetTypeCast(JCTypeCast tree) {
   586             boolean is292targetTypeCast = false;
   587             JCExpression expr = TreeInfo.skipParens(tree.expr);
   588             if (expr.hasTag(APPLY)) {
   589                 JCMethodInvocation apply = (JCMethodInvocation)expr;
   590                 Symbol sym = TreeInfo.symbol(apply.meth);
   591                 is292targetTypeCast = sym != null &&
   592                     sym.kind == MTH &&
   593                     (sym.flags() & HYPOTHETICAL) != 0;
   594             }
   595             return is292targetTypeCast;
   596         }
   598         private static final boolean ignoreAnnotatedCasts = true;
   600     /** Check that a type is within some bounds.
   601      *
   602      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
   603      *  type argument.
   604      *  @param a             The type that should be bounded by bs.
   605      *  @param bound         The bound.
   606      */
   607     private boolean checkExtends(Type a, Type bound) {
   608          if (a.isUnbound()) {
   609              return true;
   610          } else if (!a.hasTag(WILDCARD)) {
   611              a = types.upperBound(a);
   612              return types.isSubtype(a, bound);
   613          } else if (a.isExtendsBound()) {
   614              return types.isCastable(bound, types.upperBound(a), types.noWarnings);
   615          } else if (a.isSuperBound()) {
   616              return !types.notSoftSubtype(types.lowerBound(a), bound);
   617          }
   618          return true;
   619      }
   621     /** Check that type is different from 'void'.
   622      *  @param pos           Position to be used for error reporting.
   623      *  @param t             The type to be checked.
   624      */
   625     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   626         if (t.hasTag(VOID)) {
   627             log.error(pos, "void.not.allowed.here");
   628             return types.createErrorType(t);
   629         } else {
   630             return t;
   631         }
   632     }
   634     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
   635         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
   636             return typeTagError(pos,
   637                                 diags.fragment("type.req.class.array"),
   638                                 asTypeParam(t));
   639         } else {
   640             return t;
   641         }
   642     }
   644     /** Check that type is a class or interface type.
   645      *  @param pos           Position to be used for error reporting.
   646      *  @param t             The type to be checked.
   647      */
   648     Type checkClassType(DiagnosticPosition pos, Type t) {
   649         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
   650             return typeTagError(pos,
   651                                 diags.fragment("type.req.class"),
   652                                 asTypeParam(t));
   653         } else {
   654             return t;
   655         }
   656     }
   657     //where
   658         private Object asTypeParam(Type t) {
   659             return (t.hasTag(TYPEVAR))
   660                                     ? diags.fragment("type.parameter", t)
   661                                     : t;
   662         }
   664     /** Check that type is a valid qualifier for a constructor reference expression
   665      */
   666     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
   667         t = checkClassOrArrayType(pos, t);
   668         if (t.hasTag(CLASS)) {
   669             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
   670                 log.error(pos, "abstract.cant.be.instantiated");
   671                 t = types.createErrorType(t);
   672             } else if ((t.tsym.flags() & ENUM) != 0) {
   673                 log.error(pos, "enum.cant.be.instantiated");
   674                 t = types.createErrorType(t);
   675             }
   676         }
   677         return t;
   678     }
   680     /** Check that type is a class or interface type.
   681      *  @param pos           Position to be used for error reporting.
   682      *  @param t             The type to be checked.
   683      *  @param noBounds    True if type bounds are illegal here.
   684      */
   685     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   686         t = checkClassType(pos, t);
   687         if (noBounds && t.isParameterized()) {
   688             List<Type> args = t.getTypeArguments();
   689             while (args.nonEmpty()) {
   690                 if (args.head.hasTag(WILDCARD))
   691                     return typeTagError(pos,
   692                                         diags.fragment("type.req.exact"),
   693                                         args.head);
   694                 args = args.tail;
   695             }
   696         }
   697         return t;
   698     }
   700     /** Check that type is a reifiable class, interface or array type.
   701      *  @param pos           Position to be used for error reporting.
   702      *  @param t             The type to be checked.
   703      */
   704     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   705         t = checkClassOrArrayType(pos, t);
   706         if (!t.isErroneous() && !types.isReifiable(t)) {
   707             log.error(pos, "illegal.generic.type.for.instof");
   708             return types.createErrorType(t);
   709         } else {
   710             return t;
   711         }
   712     }
   714     /** Check that type is a reference type, i.e. a class, interface or array type
   715      *  or a type variable.
   716      *  @param pos           Position to be used for error reporting.
   717      *  @param t             The type to be checked.
   718      */
   719     Type checkRefType(DiagnosticPosition pos, Type t) {
   720         if (t.isReference())
   721             return t;
   722         else
   723             return typeTagError(pos,
   724                                 diags.fragment("type.req.ref"),
   725                                 t);
   726     }
   728     /** Check that each type is a reference type, i.e. a class, interface or array type
   729      *  or a type variable.
   730      *  @param trees         Original trees, used for error reporting.
   731      *  @param types         The types to be checked.
   732      */
   733     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   734         List<JCExpression> tl = trees;
   735         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   736             l.head = checkRefType(tl.head.pos(), l.head);
   737             tl = tl.tail;
   738         }
   739         return types;
   740     }
   742     /** Check that type is a null or reference type.
   743      *  @param pos           Position to be used for error reporting.
   744      *  @param t             The type to be checked.
   745      */
   746     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   747         if (t.isNullOrReference())
   748             return t;
   749         else
   750             return typeTagError(pos,
   751                                 diags.fragment("type.req.ref"),
   752                                 t);
   753     }
   755     /** Check that flag set does not contain elements of two conflicting sets. s
   756      *  Return true if it doesn't.
   757      *  @param pos           Position to be used for error reporting.
   758      *  @param flags         The set of flags to be checked.
   759      *  @param set1          Conflicting flags set #1.
   760      *  @param set2          Conflicting flags set #2.
   761      */
   762     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   763         if ((flags & set1) != 0 && (flags & set2) != 0) {
   764             log.error(pos,
   765                       "illegal.combination.of.modifiers",
   766                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   767                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   768             return false;
   769         } else
   770             return true;
   771     }
   773     /** Check that usage of diamond operator is correct (i.e. diamond should not
   774      * be used with non-generic classes or in anonymous class creation expressions)
   775      */
   776     Type checkDiamond(JCNewClass tree, Type t) {
   777         if (!TreeInfo.isDiamond(tree) ||
   778                 t.isErroneous()) {
   779             return checkClassType(tree.clazz.pos(), t, true);
   780         } else if (tree.def != null) {
   781             log.error(tree.clazz.pos(),
   782                     "cant.apply.diamond.1",
   783                     t, diags.fragment("diamond.and.anon.class", t));
   784             return types.createErrorType(t);
   785         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   786             log.error(tree.clazz.pos(),
   787                 "cant.apply.diamond.1",
   788                 t, diags.fragment("diamond.non.generic", t));
   789             return types.createErrorType(t);
   790         } else if (tree.typeargs != null &&
   791                 tree.typeargs.nonEmpty()) {
   792             log.error(tree.clazz.pos(),
   793                 "cant.apply.diamond.1",
   794                 t, diags.fragment("diamond.and.explicit.params", t));
   795             return types.createErrorType(t);
   796         } else {
   797             return t;
   798         }
   799     }
   801     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   802         MethodSymbol m = tree.sym;
   803         if (!allowSimplifiedVarargs) return;
   804         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   805         Type varargElemType = null;
   806         if (m.isVarArgs()) {
   807             varargElemType = types.elemtype(tree.params.last().type);
   808         }
   809         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   810             if (varargElemType != null) {
   811                 log.error(tree,
   812                         "varargs.invalid.trustme.anno",
   813                         syms.trustMeType.tsym,
   814                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   815             } else {
   816                 log.error(tree,
   817                             "varargs.invalid.trustme.anno",
   818                             syms.trustMeType.tsym,
   819                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   820             }
   821         } else if (hasTrustMeAnno && varargElemType != null &&
   822                             types.isReifiable(varargElemType)) {
   823             warnUnsafeVararg(tree,
   824                             "varargs.redundant.trustme.anno",
   825                             syms.trustMeType.tsym,
   826                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   827         }
   828         else if (!hasTrustMeAnno && varargElemType != null &&
   829                 !types.isReifiable(varargElemType)) {
   830             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   831         }
   832     }
   833     //where
   834         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   835             return (s.flags() & VARARGS) != 0 &&
   836                 (s.isConstructor() ||
   837                     (s.flags() & (STATIC | FINAL)) != 0);
   838         }
   840     Type checkMethod(Type owntype,
   841                             Symbol sym,
   842                             Env<AttrContext> env,
   843                             final List<JCExpression> argtrees,
   844                             List<Type> argtypes,
   845                             boolean useVarargs,
   846                             boolean unchecked) {
   847         // System.out.println("call   : " + env.tree);
   848         // System.out.println("method : " + owntype);
   849         // System.out.println("actuals: " + argtypes);
   850         List<Type> formals = owntype.getParameterTypes();
   851         Type last = useVarargs ? formals.last() : null;
   852         if (sym.name == names.init &&
   853                 sym.owner == syms.enumSym)
   854                 formals = formals.tail.tail;
   855         List<JCExpression> args = argtrees;
   856         DeferredAttr.DeferredTypeMap checkDeferredMap =
   857                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   858         if (args != null) {
   859             //this is null when type-checking a method reference
   860             while (formals.head != last) {
   861                 JCTree arg = args.head;
   862                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   863                 assertConvertible(arg, arg.type, formals.head, warn);
   864                 args = args.tail;
   865                 formals = formals.tail;
   866             }
   867             if (useVarargs) {
   868                 Type varArg = types.elemtype(last);
   869                 while (args.tail != null) {
   870                     JCTree arg = args.head;
   871                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   872                     assertConvertible(arg, arg.type, varArg, warn);
   873                     args = args.tail;
   874                 }
   875             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   876                 // non-varargs call to varargs method
   877                 Type varParam = owntype.getParameterTypes().last();
   878                 Type lastArg = checkDeferredMap.apply(argtypes.last());
   879                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   880                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   881                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   882                             types.elemtype(varParam), varParam);
   883             }
   884         }
   885         if (unchecked) {
   886             warnUnchecked(env.tree.pos(),
   887                     "unchecked.meth.invocation.applied",
   888                     kindName(sym),
   889                     sym.name,
   890                     rs.methodArguments(sym.type.getParameterTypes()),
   891                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   892                     kindName(sym.location()),
   893                     sym.location());
   894            owntype = new MethodType(owntype.getParameterTypes(),
   895                    types.erasure(owntype.getReturnType()),
   896                    types.erasure(owntype.getThrownTypes()),
   897                    syms.methodClass);
   898         }
   899         if (useVarargs) {
   900             Type argtype = owntype.getParameterTypes().last();
   901             if (!types.isReifiable(argtype) &&
   902                     (!allowSimplifiedVarargs ||
   903                     sym.attribute(syms.trustMeType.tsym) == null ||
   904                     !isTrustMeAllowedOnMethod(sym))) {
   905                 warnUnchecked(env.tree.pos(),
   906                                   "unchecked.generic.array.creation",
   907                                   argtype);
   908             }
   909             if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
   910                 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
   911             }
   912          }
   913          PolyKind pkind = (sym.type.hasTag(FORALL) &&
   914                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
   915                  PolyKind.POLY : PolyKind.STANDALONE;
   916          TreeInfo.setPolyKind(env.tree, pkind);
   917          return owntype;
   918     }
   919     //where
   920         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   921             if (types.isConvertible(actual, formal, warn))
   922                 return;
   924             if (formal.isCompound()
   925                 && types.isSubtype(actual, types.supertype(formal))
   926                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   927                 return;
   928         }
   930     /**
   931      * Check that type 't' is a valid instantiation of a generic class
   932      * (see JLS 4.5)
   933      *
   934      * @param t class type to be checked
   935      * @return true if 't' is well-formed
   936      */
   937     public boolean checkValidGenericType(Type t) {
   938         return firstIncompatibleTypeArg(t) == null;
   939     }
   940     //WHERE
   941         private Type firstIncompatibleTypeArg(Type type) {
   942             List<Type> formals = type.tsym.type.allparams();
   943             List<Type> actuals = type.allparams();
   944             List<Type> args = type.getTypeArguments();
   945             List<Type> forms = type.tsym.type.getTypeArguments();
   946             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   948             // For matching pairs of actual argument types `a' and
   949             // formal type parameters with declared bound `b' ...
   950             while (args.nonEmpty() && forms.nonEmpty()) {
   951                 // exact type arguments needs to know their
   952                 // bounds (for upper and lower bound
   953                 // calculations).  So we create new bounds where
   954                 // type-parameters are replaced with actuals argument types.
   955                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   956                 args = args.tail;
   957                 forms = forms.tail;
   958             }
   960             args = type.getTypeArguments();
   961             List<Type> tvars_cap = types.substBounds(formals,
   962                                       formals,
   963                                       types.capture(type).allparams());
   964             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   965                 // Let the actual arguments know their bound
   966                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   967                 args = args.tail;
   968                 tvars_cap = tvars_cap.tail;
   969             }
   971             args = type.getTypeArguments();
   972             List<Type> bounds = bounds_buf.toList();
   974             while (args.nonEmpty() && bounds.nonEmpty()) {
   975                 Type actual = args.head;
   976                 if (!isTypeArgErroneous(actual) &&
   977                         !bounds.head.isErroneous() &&
   978                         !checkExtends(actual, bounds.head)) {
   979                     return args.head;
   980                 }
   981                 args = args.tail;
   982                 bounds = bounds.tail;
   983             }
   985             args = type.getTypeArguments();
   986             bounds = bounds_buf.toList();
   988             for (Type arg : types.capture(type).getTypeArguments()) {
   989                 if (arg.hasTag(TYPEVAR) &&
   990                         arg.getUpperBound().isErroneous() &&
   991                         !bounds.head.isErroneous() &&
   992                         !isTypeArgErroneous(args.head)) {
   993                     return args.head;
   994                 }
   995                 bounds = bounds.tail;
   996                 args = args.tail;
   997             }
   999             return null;
  1001         //where
  1002         boolean isTypeArgErroneous(Type t) {
  1003             return isTypeArgErroneous.visit(t);
  1006         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1007             public Boolean visitType(Type t, Void s) {
  1008                 return t.isErroneous();
  1010             @Override
  1011             public Boolean visitTypeVar(TypeVar t, Void s) {
  1012                 return visit(t.getUpperBound());
  1014             @Override
  1015             public Boolean visitCapturedType(CapturedType t, Void s) {
  1016                 return visit(t.getUpperBound()) ||
  1017                         visit(t.getLowerBound());
  1019             @Override
  1020             public Boolean visitWildcardType(WildcardType t, Void s) {
  1021                 return visit(t.type);
  1023         };
  1025     /** Check that given modifiers are legal for given symbol and
  1026      *  return modifiers together with any implicit modififiers for that symbol.
  1027      *  Warning: we can't use flags() here since this method
  1028      *  is called during class enter, when flags() would cause a premature
  1029      *  completion.
  1030      *  @param pos           Position to be used for error reporting.
  1031      *  @param flags         The set of modifiers given in a definition.
  1032      *  @param sym           The defined symbol.
  1033      */
  1034     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1035         long mask;
  1036         long implicit = 0;
  1037         switch (sym.kind) {
  1038         case VAR:
  1039             if (sym.owner.kind != TYP)
  1040                 mask = LocalVarFlags;
  1041             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1042                 mask = implicit = InterfaceVarFlags;
  1043             else
  1044                 mask = VarFlags;
  1045             break;
  1046         case MTH:
  1047             if (sym.name == names.init) {
  1048                 if ((sym.owner.flags_field & ENUM) != 0) {
  1049                     // enum constructors cannot be declared public or
  1050                     // protected and must be implicitly or explicitly
  1051                     // private
  1052                     implicit = PRIVATE;
  1053                     mask = PRIVATE;
  1054                 } else
  1055                     mask = ConstructorFlags;
  1056             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1057                 if ((flags & (DEFAULT | STATIC)) != 0) {
  1058                     mask = InterfaceMethodMask;
  1059                     implicit = PUBLIC;
  1060                     if ((flags & DEFAULT) != 0) {
  1061                         implicit |= ABSTRACT;
  1063                 } else {
  1064                     mask = implicit = InterfaceMethodFlags;
  1067             else {
  1068                 mask = MethodFlags;
  1070             // Imply STRICTFP if owner has STRICTFP set.
  1071             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1072               implicit |= sym.owner.flags_field & STRICTFP;
  1073             break;
  1074         case TYP:
  1075             if (sym.isLocal()) {
  1076                 mask = LocalClassFlags;
  1077                 if (sym.name.isEmpty()) { // Anonymous class
  1078                     // Anonymous classes in static methods are themselves static;
  1079                     // that's why we admit STATIC here.
  1080                     mask |= STATIC;
  1081                     // JLS: Anonymous classes are final.
  1082                     implicit |= FINAL;
  1084                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1085                     (flags & ENUM) != 0)
  1086                     log.error(pos, "enums.must.be.static");
  1087             } else if (sym.owner.kind == TYP) {
  1088                 mask = MemberClassFlags;
  1089                 if (sym.owner.owner.kind == PCK ||
  1090                     (sym.owner.flags_field & STATIC) != 0)
  1091                     mask |= STATIC;
  1092                 else if ((flags & ENUM) != 0)
  1093                     log.error(pos, "enums.must.be.static");
  1094                 // Nested interfaces and enums are always STATIC (Spec ???)
  1095                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1096             } else {
  1097                 mask = ClassFlags;
  1099             // Interfaces are always ABSTRACT
  1100             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1102             if ((flags & ENUM) != 0) {
  1103                 // enums can't be declared abstract or final
  1104                 mask &= ~(ABSTRACT | FINAL);
  1105                 implicit |= implicitEnumFinalFlag(tree);
  1107             // Imply STRICTFP if owner has STRICTFP set.
  1108             implicit |= sym.owner.flags_field & STRICTFP;
  1109             break;
  1110         default:
  1111             throw new AssertionError();
  1113         long illegal = flags & ExtendedStandardFlags & ~mask;
  1114         if (illegal != 0) {
  1115             if ((illegal & INTERFACE) != 0) {
  1116                 log.error(pos, "intf.not.allowed.here");
  1117                 mask |= INTERFACE;
  1119             else {
  1120                 log.error(pos,
  1121                           "mod.not.allowed.here", asFlagSet(illegal));
  1124         else if ((sym.kind == TYP ||
  1125                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1126                   // in the presence of inner classes. Should it be deleted here?
  1127                   checkDisjoint(pos, flags,
  1128                                 ABSTRACT,
  1129                                 PRIVATE | STATIC | DEFAULT))
  1130                  &&
  1131                  checkDisjoint(pos, flags,
  1132                                 STATIC,
  1133                                 DEFAULT)
  1134                  &&
  1135                  checkDisjoint(pos, flags,
  1136                                ABSTRACT | INTERFACE,
  1137                                FINAL | NATIVE | SYNCHRONIZED)
  1138                  &&
  1139                  checkDisjoint(pos, flags,
  1140                                PUBLIC,
  1141                                PRIVATE | PROTECTED)
  1142                  &&
  1143                  checkDisjoint(pos, flags,
  1144                                PRIVATE,
  1145                                PUBLIC | PROTECTED)
  1146                  &&
  1147                  checkDisjoint(pos, flags,
  1148                                FINAL,
  1149                                VOLATILE)
  1150                  &&
  1151                  (sym.kind == TYP ||
  1152                   checkDisjoint(pos, flags,
  1153                                 ABSTRACT | NATIVE,
  1154                                 STRICTFP))) {
  1155             // skip
  1157         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1161     /** Determine if this enum should be implicitly final.
  1163      *  If the enum has no specialized enum contants, it is final.
  1165      *  If the enum does have specialized enum contants, it is
  1166      *  <i>not</i> final.
  1167      */
  1168     private long implicitEnumFinalFlag(JCTree tree) {
  1169         if (!tree.hasTag(CLASSDEF)) return 0;
  1170         class SpecialTreeVisitor extends JCTree.Visitor {
  1171             boolean specialized;
  1172             SpecialTreeVisitor() {
  1173                 this.specialized = false;
  1174             };
  1176             @Override
  1177             public void visitTree(JCTree tree) { /* no-op */ }
  1179             @Override
  1180             public void visitVarDef(JCVariableDecl tree) {
  1181                 if ((tree.mods.flags & ENUM) != 0) {
  1182                     if (tree.init instanceof JCNewClass &&
  1183                         ((JCNewClass) tree.init).def != null) {
  1184                         specialized = true;
  1190         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1191         JCClassDecl cdef = (JCClassDecl) tree;
  1192         for (JCTree defs: cdef.defs) {
  1193             defs.accept(sts);
  1194             if (sts.specialized) return 0;
  1196         return FINAL;
  1199 /* *************************************************************************
  1200  * Type Validation
  1201  **************************************************************************/
  1203     /** Validate a type expression. That is,
  1204      *  check that all type arguments of a parametric type are within
  1205      *  their bounds. This must be done in a second phase after type attributon
  1206      *  since a class might have a subclass as type parameter bound. E.g:
  1208      *  <pre>{@code
  1209      *  class B<A extends C> { ... }
  1210      *  class C extends B<C> { ... }
  1211      *  }</pre>
  1213      *  and we can't make sure that the bound is already attributed because
  1214      *  of possible cycles.
  1216      * Visitor method: Validate a type expression, if it is not null, catching
  1217      *  and reporting any completion failures.
  1218      */
  1219     void validate(JCTree tree, Env<AttrContext> env) {
  1220         validate(tree, env, true);
  1222     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1223         new Validator(env).validateTree(tree, checkRaw, true);
  1226     /** Visitor method: Validate a list of type expressions.
  1227      */
  1228     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1229         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1230             validate(l.head, env);
  1233     /** A visitor class for type validation.
  1234      */
  1235     class Validator extends JCTree.Visitor {
  1237         boolean isOuter;
  1238         Env<AttrContext> env;
  1240         Validator(Env<AttrContext> env) {
  1241             this.env = env;
  1244         @Override
  1245         public void visitTypeArray(JCArrayTypeTree tree) {
  1246             tree.elemtype.accept(this);
  1249         @Override
  1250         public void visitTypeApply(JCTypeApply tree) {
  1251             if (tree.type.hasTag(CLASS)) {
  1252                 List<JCExpression> args = tree.arguments;
  1253                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1255                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1256                 if (incompatibleArg != null) {
  1257                     for (JCTree arg : tree.arguments) {
  1258                         if (arg.type == incompatibleArg) {
  1259                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1261                         forms = forms.tail;
  1265                 forms = tree.type.tsym.type.getTypeArguments();
  1267                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1269                 // For matching pairs of actual argument types `a' and
  1270                 // formal type parameters with declared bound `b' ...
  1271                 while (args.nonEmpty() && forms.nonEmpty()) {
  1272                     validateTree(args.head,
  1273                             !(isOuter && is_java_lang_Class),
  1274                             false);
  1275                     args = args.tail;
  1276                     forms = forms.tail;
  1279                 // Check that this type is either fully parameterized, or
  1280                 // not parameterized at all.
  1281                 if (tree.type.getEnclosingType().isRaw())
  1282                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1283                 if (tree.clazz.hasTag(SELECT))
  1284                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1288         @Override
  1289         public void visitTypeParameter(JCTypeParameter tree) {
  1290             validateTrees(tree.bounds, true, isOuter);
  1291             checkClassBounds(tree.pos(), tree.type);
  1294         @Override
  1295         public void visitWildcard(JCWildcard tree) {
  1296             if (tree.inner != null)
  1297                 validateTree(tree.inner, true, isOuter);
  1300         @Override
  1301         public void visitSelect(JCFieldAccess tree) {
  1302             if (tree.type.hasTag(CLASS)) {
  1303                 visitSelectInternal(tree);
  1305                 // Check that this type is either fully parameterized, or
  1306                 // not parameterized at all.
  1307                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1308                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1312         public void visitSelectInternal(JCFieldAccess tree) {
  1313             if (tree.type.tsym.isStatic() &&
  1314                 tree.selected.type.isParameterized()) {
  1315                 // The enclosing type is not a class, so we are
  1316                 // looking at a static member type.  However, the
  1317                 // qualifying expression is parameterized.
  1318                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1319             } else {
  1320                 // otherwise validate the rest of the expression
  1321                 tree.selected.accept(this);
  1325         @Override
  1326         public void visitAnnotatedType(JCAnnotatedType tree) {
  1327             tree.underlyingType.accept(this);
  1330         /** Default visitor method: do nothing.
  1331          */
  1332         @Override
  1333         public void visitTree(JCTree tree) {
  1336         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1337             try {
  1338                 if (tree != null) {
  1339                     this.isOuter = isOuter;
  1340                     tree.accept(this);
  1341                     if (checkRaw)
  1342                         checkRaw(tree, env);
  1344             } catch (CompletionFailure ex) {
  1345                 completionError(tree.pos(), ex);
  1349         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1350             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1351                 validateTree(l.head, checkRaw, isOuter);
  1354         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1355             if (lint.isEnabled(LintCategory.RAW) &&
  1356                 tree.type.hasTag(CLASS) &&
  1357                 !TreeInfo.isDiamond(tree) &&
  1358                 !withinAnonConstr(env) &&
  1359                 tree.type.isRaw()) {
  1360                 log.warning(LintCategory.RAW,
  1361                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1365         boolean withinAnonConstr(Env<AttrContext> env) {
  1366             return env.enclClass.name.isEmpty() &&
  1367                     env.enclMethod != null && env.enclMethod.name == names.init;
  1371 /* *************************************************************************
  1372  * Exception checking
  1373  **************************************************************************/
  1375     /* The following methods treat classes as sets that contain
  1376      * the class itself and all their subclasses
  1377      */
  1379     /** Is given type a subtype of some of the types in given list?
  1380      */
  1381     boolean subset(Type t, List<Type> ts) {
  1382         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1383             if (types.isSubtype(t, l.head)) return true;
  1384         return false;
  1387     /** Is given type a subtype or supertype of
  1388      *  some of the types in given list?
  1389      */
  1390     boolean intersects(Type t, List<Type> ts) {
  1391         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1392             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1393         return false;
  1396     /** Add type set to given type list, unless it is a subclass of some class
  1397      *  in the list.
  1398      */
  1399     List<Type> incl(Type t, List<Type> ts) {
  1400         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1403     /** Remove type set from type set list.
  1404      */
  1405     List<Type> excl(Type t, List<Type> ts) {
  1406         if (ts.isEmpty()) {
  1407             return ts;
  1408         } else {
  1409             List<Type> ts1 = excl(t, ts.tail);
  1410             if (types.isSubtype(ts.head, t)) return ts1;
  1411             else if (ts1 == ts.tail) return ts;
  1412             else return ts1.prepend(ts.head);
  1416     /** Form the union of two type set lists.
  1417      */
  1418     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1419         List<Type> ts = ts1;
  1420         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1421             ts = incl(l.head, ts);
  1422         return ts;
  1425     /** Form the difference of two type lists.
  1426      */
  1427     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1428         List<Type> ts = ts1;
  1429         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1430             ts = excl(l.head, ts);
  1431         return ts;
  1434     /** Form the intersection of two type lists.
  1435      */
  1436     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1437         List<Type> ts = List.nil();
  1438         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1439             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1440         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1441             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1442         return ts;
  1445     /** Is exc an exception symbol that need not be declared?
  1446      */
  1447     boolean isUnchecked(ClassSymbol exc) {
  1448         return
  1449             exc.kind == ERR ||
  1450             exc.isSubClass(syms.errorType.tsym, types) ||
  1451             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1454     /** Is exc an exception type that need not be declared?
  1455      */
  1456     boolean isUnchecked(Type exc) {
  1457         return
  1458             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1459             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1460             exc.hasTag(BOT);
  1463     /** Same, but handling completion failures.
  1464      */
  1465     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1466         try {
  1467             return isUnchecked(exc);
  1468         } catch (CompletionFailure ex) {
  1469             completionError(pos, ex);
  1470             return true;
  1474     /** Is exc handled by given exception list?
  1475      */
  1476     boolean isHandled(Type exc, List<Type> handled) {
  1477         return isUnchecked(exc) || subset(exc, handled);
  1480     /** Return all exceptions in thrown list that are not in handled list.
  1481      *  @param thrown     The list of thrown exceptions.
  1482      *  @param handled    The list of handled exceptions.
  1483      */
  1484     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1485         List<Type> unhandled = List.nil();
  1486         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1487             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1488         return unhandled;
  1491 /* *************************************************************************
  1492  * Overriding/Implementation checking
  1493  **************************************************************************/
  1495     /** The level of access protection given by a flag set,
  1496      *  where PRIVATE is highest and PUBLIC is lowest.
  1497      */
  1498     static int protection(long flags) {
  1499         switch ((short)(flags & AccessFlags)) {
  1500         case PRIVATE: return 3;
  1501         case PROTECTED: return 1;
  1502         default:
  1503         case PUBLIC: return 0;
  1504         case 0: return 2;
  1508     /** A customized "cannot override" error message.
  1509      *  @param m      The overriding method.
  1510      *  @param other  The overridden method.
  1511      *  @return       An internationalized string.
  1512      */
  1513     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1514         String key;
  1515         if ((other.owner.flags() & INTERFACE) == 0)
  1516             key = "cant.override";
  1517         else if ((m.owner.flags() & INTERFACE) == 0)
  1518             key = "cant.implement";
  1519         else
  1520             key = "clashes.with";
  1521         return diags.fragment(key, m, m.location(), other, other.location());
  1524     /** A customized "override" warning message.
  1525      *  @param m      The overriding method.
  1526      *  @param other  The overridden method.
  1527      *  @return       An internationalized string.
  1528      */
  1529     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1530         String key;
  1531         if ((other.owner.flags() & INTERFACE) == 0)
  1532             key = "unchecked.override";
  1533         else if ((m.owner.flags() & INTERFACE) == 0)
  1534             key = "unchecked.implement";
  1535         else
  1536             key = "unchecked.clash.with";
  1537         return diags.fragment(key, m, m.location(), other, other.location());
  1540     /** A customized "override" warning message.
  1541      *  @param m      The overriding method.
  1542      *  @param other  The overridden method.
  1543      *  @return       An internationalized string.
  1544      */
  1545     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1546         String key;
  1547         if ((other.owner.flags() & INTERFACE) == 0)
  1548             key = "varargs.override";
  1549         else  if ((m.owner.flags() & INTERFACE) == 0)
  1550             key = "varargs.implement";
  1551         else
  1552             key = "varargs.clash.with";
  1553         return diags.fragment(key, m, m.location(), other, other.location());
  1556     /** Check that this method conforms with overridden method 'other'.
  1557      *  where `origin' is the class where checking started.
  1558      *  Complications:
  1559      *  (1) Do not check overriding of synthetic methods
  1560      *      (reason: they might be final).
  1561      *      todo: check whether this is still necessary.
  1562      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1563      *      than the method it implements. Augment the proxy methods with the
  1564      *      undeclared exceptions in this case.
  1565      *  (3) When generics are enabled, admit the case where an interface proxy
  1566      *      has a result type
  1567      *      extended by the result type of the method it implements.
  1568      *      Change the proxies result type to the smaller type in this case.
  1570      *  @param tree         The tree from which positions
  1571      *                      are extracted for errors.
  1572      *  @param m            The overriding method.
  1573      *  @param other        The overridden method.
  1574      *  @param origin       The class of which the overriding method
  1575      *                      is a member.
  1576      */
  1577     void checkOverride(JCTree tree,
  1578                        MethodSymbol m,
  1579                        MethodSymbol other,
  1580                        ClassSymbol origin) {
  1581         // Don't check overriding of synthetic methods or by bridge methods.
  1582         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1583             return;
  1586         // Error if static method overrides instance method (JLS 8.4.6.2).
  1587         if ((m.flags() & STATIC) != 0 &&
  1588                    (other.flags() & STATIC) == 0) {
  1589             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1590                       cannotOverride(m, other));
  1591             return;
  1594         // Error if instance method overrides static or final
  1595         // method (JLS 8.4.6.1).
  1596         if ((other.flags() & FINAL) != 0 ||
  1597                  (m.flags() & STATIC) == 0 &&
  1598                  (other.flags() & STATIC) != 0) {
  1599             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1600                       cannotOverride(m, other),
  1601                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1602             return;
  1605         if ((m.owner.flags() & ANNOTATION) != 0) {
  1606             // handled in validateAnnotationMethod
  1607             return;
  1610         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1611         if ((origin.flags() & INTERFACE) == 0 &&
  1612                  protection(m.flags()) > protection(other.flags())) {
  1613             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1614                       cannotOverride(m, other),
  1615                       other.flags() == 0 ?
  1616                           Flag.PACKAGE :
  1617                           asFlagSet(other.flags() & AccessFlags));
  1618             return;
  1621         Type mt = types.memberType(origin.type, m);
  1622         Type ot = types.memberType(origin.type, other);
  1623         // Error if overriding result type is different
  1624         // (or, in the case of generics mode, not a subtype) of
  1625         // overridden result type. We have to rename any type parameters
  1626         // before comparing types.
  1627         List<Type> mtvars = mt.getTypeArguments();
  1628         List<Type> otvars = ot.getTypeArguments();
  1629         Type mtres = mt.getReturnType();
  1630         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1632         overrideWarner.clear();
  1633         boolean resultTypesOK =
  1634             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1635         if (!resultTypesOK) {
  1636             if (!allowCovariantReturns &&
  1637                 m.owner != origin &&
  1638                 m.owner.isSubClass(other.owner, types)) {
  1639                 // allow limited interoperability with covariant returns
  1640             } else {
  1641                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1642                           "override.incompatible.ret",
  1643                           cannotOverride(m, other),
  1644                           mtres, otres);
  1645                 return;
  1647         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1648             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1649                     "override.unchecked.ret",
  1650                     uncheckedOverrides(m, other),
  1651                     mtres, otres);
  1654         // Error if overriding method throws an exception not reported
  1655         // by overridden method.
  1656         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1657         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1658         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1659         if (unhandledErased.nonEmpty()) {
  1660             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1661                       "override.meth.doesnt.throw",
  1662                       cannotOverride(m, other),
  1663                       unhandledUnerased.head);
  1664             return;
  1666         else if (unhandledUnerased.nonEmpty()) {
  1667             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1668                           "override.unchecked.thrown",
  1669                          cannotOverride(m, other),
  1670                          unhandledUnerased.head);
  1671             return;
  1674         // Optional warning if varargs don't agree
  1675         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1676             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1677             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1678                         ((m.flags() & Flags.VARARGS) != 0)
  1679                         ? "override.varargs.missing"
  1680                         : "override.varargs.extra",
  1681                         varargsOverrides(m, other));
  1684         // Warn if instance method overrides bridge method (compiler spec ??)
  1685         if ((other.flags() & BRIDGE) != 0) {
  1686             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1687                         uncheckedOverrides(m, other));
  1690         // Warn if a deprecated method overridden by a non-deprecated one.
  1691         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1692             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1695     // where
  1696         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1697             // If the method, m, is defined in an interface, then ignore the issue if the method
  1698             // is only inherited via a supertype and also implemented in the supertype,
  1699             // because in that case, we will rediscover the issue when examining the method
  1700             // in the supertype.
  1701             // If the method, m, is not defined in an interface, then the only time we need to
  1702             // address the issue is when the method is the supertype implemementation: any other
  1703             // case, we will have dealt with when examining the supertype classes
  1704             ClassSymbol mc = m.enclClass();
  1705             Type st = types.supertype(origin.type);
  1706             if (!st.hasTag(CLASS))
  1707                 return true;
  1708             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1710             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1711                 List<Type> intfs = types.interfaces(origin.type);
  1712                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1714             else
  1715                 return (stimpl != m);
  1719     // used to check if there were any unchecked conversions
  1720     Warner overrideWarner = new Warner();
  1722     /** Check that a class does not inherit two concrete methods
  1723      *  with the same signature.
  1724      *  @param pos          Position to be used for error reporting.
  1725      *  @param site         The class type to be checked.
  1726      */
  1727     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1728         Type sup = types.supertype(site);
  1729         if (!sup.hasTag(CLASS)) return;
  1731         for (Type t1 = sup;
  1732              t1.tsym.type.isParameterized();
  1733              t1 = types.supertype(t1)) {
  1734             for (Scope.Entry e1 = t1.tsym.members().elems;
  1735                  e1 != null;
  1736                  e1 = e1.sibling) {
  1737                 Symbol s1 = e1.sym;
  1738                 if (s1.kind != MTH ||
  1739                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1740                     !s1.isInheritedIn(site.tsym, types) ||
  1741                     ((MethodSymbol)s1).implementation(site.tsym,
  1742                                                       types,
  1743                                                       true) != s1)
  1744                     continue;
  1745                 Type st1 = types.memberType(t1, s1);
  1746                 int s1ArgsLength = st1.getParameterTypes().length();
  1747                 if (st1 == s1.type) continue;
  1749                 for (Type t2 = sup;
  1750                      t2.hasTag(CLASS);
  1751                      t2 = types.supertype(t2)) {
  1752                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1753                          e2.scope != null;
  1754                          e2 = e2.next()) {
  1755                         Symbol s2 = e2.sym;
  1756                         if (s2 == s1 ||
  1757                             s2.kind != MTH ||
  1758                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1759                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1760                             !s2.isInheritedIn(site.tsym, types) ||
  1761                             ((MethodSymbol)s2).implementation(site.tsym,
  1762                                                               types,
  1763                                                               true) != s2)
  1764                             continue;
  1765                         Type st2 = types.memberType(t2, s2);
  1766                         if (types.overrideEquivalent(st1, st2))
  1767                             log.error(pos, "concrete.inheritance.conflict",
  1768                                       s1, t1, s2, t2, sup);
  1775     /** Check that classes (or interfaces) do not each define an abstract
  1776      *  method with same name and arguments but incompatible return types.
  1777      *  @param pos          Position to be used for error reporting.
  1778      *  @param t1           The first argument type.
  1779      *  @param t2           The second argument type.
  1780      */
  1781     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1782                                             Type t1,
  1783                                             Type t2) {
  1784         return checkCompatibleAbstracts(pos, t1, t2,
  1785                                         types.makeCompoundType(t1, t2));
  1788     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1789                                             Type t1,
  1790                                             Type t2,
  1791                                             Type site) {
  1792         return firstIncompatibility(pos, t1, t2, site) == null;
  1795     /** Return the first method which is defined with same args
  1796      *  but different return types in two given interfaces, or null if none
  1797      *  exists.
  1798      *  @param t1     The first type.
  1799      *  @param t2     The second type.
  1800      *  @param site   The most derived type.
  1801      *  @returns symbol from t2 that conflicts with one in t1.
  1802      */
  1803     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1804         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1805         closure(t1, interfaces1);
  1806         Map<TypeSymbol,Type> interfaces2;
  1807         if (t1 == t2)
  1808             interfaces2 = interfaces1;
  1809         else
  1810             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1812         for (Type t3 : interfaces1.values()) {
  1813             for (Type t4 : interfaces2.values()) {
  1814                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1815                 if (s != null) return s;
  1818         return null;
  1821     /** Compute all the supertypes of t, indexed by type symbol. */
  1822     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1823         if (!t.hasTag(CLASS)) return;
  1824         if (typeMap.put(t.tsym, t) == null) {
  1825             closure(types.supertype(t), typeMap);
  1826             for (Type i : types.interfaces(t))
  1827                 closure(i, typeMap);
  1831     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1832     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1833         if (!t.hasTag(CLASS)) return;
  1834         if (typesSkip.get(t.tsym) != null) return;
  1835         if (typeMap.put(t.tsym, t) == null) {
  1836             closure(types.supertype(t), typesSkip, typeMap);
  1837             for (Type i : types.interfaces(t))
  1838                 closure(i, typesSkip, typeMap);
  1842     /** Return the first method in t2 that conflicts with a method from t1. */
  1843     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1844         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1845             Symbol s1 = e1.sym;
  1846             Type st1 = null;
  1847             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1848                     (s1.flags() & SYNTHETIC) != 0) continue;
  1849             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1850             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1851             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1852                 Symbol s2 = e2.sym;
  1853                 if (s1 == s2) continue;
  1854                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1855                         (s2.flags() & SYNTHETIC) != 0) continue;
  1856                 if (st1 == null) st1 = types.memberType(t1, s1);
  1857                 Type st2 = types.memberType(t2, s2);
  1858                 if (types.overrideEquivalent(st1, st2)) {
  1859                     List<Type> tvars1 = st1.getTypeArguments();
  1860                     List<Type> tvars2 = st2.getTypeArguments();
  1861                     Type rt1 = st1.getReturnType();
  1862                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1863                     boolean compat =
  1864                         types.isSameType(rt1, rt2) ||
  1865                         !rt1.isPrimitiveOrVoid() &&
  1866                         !rt2.isPrimitiveOrVoid() &&
  1867                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1868                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1869                          checkCommonOverriderIn(s1,s2,site);
  1870                     if (!compat) {
  1871                         log.error(pos, "types.incompatible.diff.ret",
  1872                             t1, t2, s2.name +
  1873                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1874                         return s2;
  1876                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1877                         !checkCommonOverriderIn(s1, s2, site)) {
  1878                     log.error(pos,
  1879                             "name.clash.same.erasure.no.override",
  1880                             s1, s1.location(),
  1881                             s2, s2.location());
  1882                     return s2;
  1886         return null;
  1888     //WHERE
  1889     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1890         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1891         Type st1 = types.memberType(site, s1);
  1892         Type st2 = types.memberType(site, s2);
  1893         closure(site, supertypes);
  1894         for (Type t : supertypes.values()) {
  1895             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1896                 Symbol s3 = e.sym;
  1897                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1898                 Type st3 = types.memberType(site,s3);
  1899                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1900                     if (s3.owner == site.tsym) {
  1901                         return true;
  1903                     List<Type> tvars1 = st1.getTypeArguments();
  1904                     List<Type> tvars2 = st2.getTypeArguments();
  1905                     List<Type> tvars3 = st3.getTypeArguments();
  1906                     Type rt1 = st1.getReturnType();
  1907                     Type rt2 = st2.getReturnType();
  1908                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1909                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1910                     boolean compat =
  1911                         !rt13.isPrimitiveOrVoid() &&
  1912                         !rt23.isPrimitiveOrVoid() &&
  1913                         (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
  1914                          types.covariantReturnType(rt23, rt2, types.noWarnings));
  1915                     if (compat)
  1916                         return true;
  1920         return false;
  1923     /** Check that a given method conforms with any method it overrides.
  1924      *  @param tree         The tree from which positions are extracted
  1925      *                      for errors.
  1926      *  @param m            The overriding method.
  1927      */
  1928     void checkOverride(JCTree tree, MethodSymbol m) {
  1929         ClassSymbol origin = (ClassSymbol)m.owner;
  1930         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1931             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1932                 log.error(tree.pos(), "enum.no.finalize");
  1933                 return;
  1935         for (Type t = origin.type; t.hasTag(CLASS);
  1936              t = types.supertype(t)) {
  1937             if (t != origin.type) {
  1938                 checkOverride(tree, t, origin, m);
  1940             for (Type t2 : types.interfaces(t)) {
  1941                 checkOverride(tree, t2, origin, m);
  1946     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1947         TypeSymbol c = site.tsym;
  1948         Scope.Entry e = c.members().lookup(m.name);
  1949         while (e.scope != null) {
  1950             if (m.overrides(e.sym, origin, types, false)) {
  1951                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1952                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1955             e = e.next();
  1959     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1960         ClashFilter cf = new ClashFilter(origin.type);
  1961         return (cf.accepts(s1) &&
  1962                 cf.accepts(s2) &&
  1963                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1967     /** Check that all abstract members of given class have definitions.
  1968      *  @param pos          Position to be used for error reporting.
  1969      *  @param c            The class.
  1970      */
  1971     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1972         try {
  1973             MethodSymbol undef = firstUndef(c, c);
  1974             if (undef != null) {
  1975                 if ((c.flags() & ENUM) != 0 &&
  1976                     types.supertype(c.type).tsym == syms.enumSym &&
  1977                     (c.flags() & FINAL) == 0) {
  1978                     // add the ABSTRACT flag to an enum
  1979                     c.flags_field |= ABSTRACT;
  1980                 } else {
  1981                     MethodSymbol undef1 =
  1982                         new MethodSymbol(undef.flags(), undef.name,
  1983                                          types.memberType(c.type, undef), undef.owner);
  1984                     log.error(pos, "does.not.override.abstract",
  1985                               c, undef1, undef1.location());
  1988         } catch (CompletionFailure ex) {
  1989             completionError(pos, ex);
  1992 //where
  1993         /** Return first abstract member of class `c' that is not defined
  1994          *  in `impl', null if there is none.
  1995          */
  1996         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1997             MethodSymbol undef = null;
  1998             // Do not bother to search in classes that are not abstract,
  1999             // since they cannot have abstract members.
  2000             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2001                 Scope s = c.members();
  2002                 for (Scope.Entry e = s.elems;
  2003                      undef == null && e != null;
  2004                      e = e.sibling) {
  2005                     if (e.sym.kind == MTH &&
  2006                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2007                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2008                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2009                         if (implmeth == null || implmeth == absmeth) {
  2010                             //look for default implementations
  2011                             if (allowDefaultMethods) {
  2012                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2013                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2014                                     implmeth = prov;
  2018                         if (implmeth == null || implmeth == absmeth) {
  2019                             undef = absmeth;
  2023                 if (undef == null) {
  2024                     Type st = types.supertype(c.type);
  2025                     if (st.hasTag(CLASS))
  2026                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2028                 for (List<Type> l = types.interfaces(c.type);
  2029                      undef == null && l.nonEmpty();
  2030                      l = l.tail) {
  2031                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2034             return undef;
  2037     void checkNonCyclicDecl(JCClassDecl tree) {
  2038         CycleChecker cc = new CycleChecker();
  2039         cc.scan(tree);
  2040         if (!cc.errorFound && !cc.partialCheck) {
  2041             tree.sym.flags_field |= ACYCLIC;
  2045     class CycleChecker extends TreeScanner {
  2047         List<Symbol> seenClasses = List.nil();
  2048         boolean errorFound = false;
  2049         boolean partialCheck = false;
  2051         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2052             if (sym != null && sym.kind == TYP) {
  2053                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2054                 if (classEnv != null) {
  2055                     DiagnosticSource prevSource = log.currentSource();
  2056                     try {
  2057                         log.useSource(classEnv.toplevel.sourcefile);
  2058                         scan(classEnv.tree);
  2060                     finally {
  2061                         log.useSource(prevSource.getFile());
  2063                 } else if (sym.kind == TYP) {
  2064                     checkClass(pos, sym, List.<JCTree>nil());
  2066             } else {
  2067                 //not completed yet
  2068                 partialCheck = true;
  2072         @Override
  2073         public void visitSelect(JCFieldAccess tree) {
  2074             super.visitSelect(tree);
  2075             checkSymbol(tree.pos(), tree.sym);
  2078         @Override
  2079         public void visitIdent(JCIdent tree) {
  2080             checkSymbol(tree.pos(), tree.sym);
  2083         @Override
  2084         public void visitTypeApply(JCTypeApply tree) {
  2085             scan(tree.clazz);
  2088         @Override
  2089         public void visitTypeArray(JCArrayTypeTree tree) {
  2090             scan(tree.elemtype);
  2093         @Override
  2094         public void visitClassDef(JCClassDecl tree) {
  2095             List<JCTree> supertypes = List.nil();
  2096             if (tree.getExtendsClause() != null) {
  2097                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2099             if (tree.getImplementsClause() != null) {
  2100                 for (JCTree intf : tree.getImplementsClause()) {
  2101                     supertypes = supertypes.prepend(intf);
  2104             checkClass(tree.pos(), tree.sym, supertypes);
  2107         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2108             if ((c.flags_field & ACYCLIC) != 0)
  2109                 return;
  2110             if (seenClasses.contains(c)) {
  2111                 errorFound = true;
  2112                 noteCyclic(pos, (ClassSymbol)c);
  2113             } else if (!c.type.isErroneous()) {
  2114                 try {
  2115                     seenClasses = seenClasses.prepend(c);
  2116                     if (c.type.hasTag(CLASS)) {
  2117                         if (supertypes.nonEmpty()) {
  2118                             scan(supertypes);
  2120                         else {
  2121                             ClassType ct = (ClassType)c.type;
  2122                             if (ct.supertype_field == null ||
  2123                                     ct.interfaces_field == null) {
  2124                                 //not completed yet
  2125                                 partialCheck = true;
  2126                                 return;
  2128                             checkSymbol(pos, ct.supertype_field.tsym);
  2129                             for (Type intf : ct.interfaces_field) {
  2130                                 checkSymbol(pos, intf.tsym);
  2133                         if (c.owner.kind == TYP) {
  2134                             checkSymbol(pos, c.owner);
  2137                 } finally {
  2138                     seenClasses = seenClasses.tail;
  2144     /** Check for cyclic references. Issue an error if the
  2145      *  symbol of the type referred to has a LOCKED flag set.
  2147      *  @param pos      Position to be used for error reporting.
  2148      *  @param t        The type referred to.
  2149      */
  2150     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2151         checkNonCyclicInternal(pos, t);
  2155     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2156         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2159     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2160         final TypeVar tv;
  2161         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2162             return;
  2163         if (seen.contains(t)) {
  2164             tv = (TypeVar)t;
  2165             tv.bound = types.createErrorType(t);
  2166             log.error(pos, "cyclic.inheritance", t);
  2167         } else if (t.hasTag(TYPEVAR)) {
  2168             tv = (TypeVar)t;
  2169             seen = seen.prepend(tv);
  2170             for (Type b : types.getBounds(tv))
  2171                 checkNonCyclic1(pos, b, seen);
  2175     /** Check for cyclic references. Issue an error if the
  2176      *  symbol of the type referred to has a LOCKED flag set.
  2178      *  @param pos      Position to be used for error reporting.
  2179      *  @param t        The type referred to.
  2180      *  @returns        True if the check completed on all attributed classes
  2181      */
  2182     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2183         boolean complete = true; // was the check complete?
  2184         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2185         Symbol c = t.tsym;
  2186         if ((c.flags_field & ACYCLIC) != 0) return true;
  2188         if ((c.flags_field & LOCKED) != 0) {
  2189             noteCyclic(pos, (ClassSymbol)c);
  2190         } else if (!c.type.isErroneous()) {
  2191             try {
  2192                 c.flags_field |= LOCKED;
  2193                 if (c.type.hasTag(CLASS)) {
  2194                     ClassType clazz = (ClassType)c.type;
  2195                     if (clazz.interfaces_field != null)
  2196                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2197                             complete &= checkNonCyclicInternal(pos, l.head);
  2198                     if (clazz.supertype_field != null) {
  2199                         Type st = clazz.supertype_field;
  2200                         if (st != null && st.hasTag(CLASS))
  2201                             complete &= checkNonCyclicInternal(pos, st);
  2203                     if (c.owner.kind == TYP)
  2204                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2206             } finally {
  2207                 c.flags_field &= ~LOCKED;
  2210         if (complete)
  2211             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2212         if (complete) c.flags_field |= ACYCLIC;
  2213         return complete;
  2216     /** Note that we found an inheritance cycle. */
  2217     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2218         log.error(pos, "cyclic.inheritance", c);
  2219         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2220             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2221         Type st = types.supertype(c.type);
  2222         if (st.hasTag(CLASS))
  2223             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2224         c.type = types.createErrorType(c, c.type);
  2225         c.flags_field |= ACYCLIC;
  2228     /**
  2229      * Check that functional interface methods would make sense when seen
  2230      * from the perspective of the implementing class
  2231      */
  2232     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2233         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2234         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2235         c.interfaces_field = List.of(funcInterface);
  2236         c.supertype_field = syms.objectType;
  2237         c.tsym = csym;
  2238         csym.members_field = new Scope(csym);
  2239         csym.completer = null;
  2240         checkImplementations(tree, csym, csym);
  2243     /** Check that all methods which implement some
  2244      *  method conform to the method they implement.
  2245      *  @param tree         The class definition whose members are checked.
  2246      */
  2247     void checkImplementations(JCClassDecl tree) {
  2248         checkImplementations(tree, tree.sym, tree.sym);
  2250     //where
  2251         /** Check that all methods which implement some
  2252          *  method in `ic' conform to the method they implement.
  2253          */
  2254         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2255             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2256                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2257                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2258                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2259                         if (e.sym.kind == MTH &&
  2260                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2261                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2262                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2263                             if (implmeth != null && implmeth != absmeth &&
  2264                                 (implmeth.owner.flags() & INTERFACE) ==
  2265                                 (origin.flags() & INTERFACE)) {
  2266                                 // don't check if implmeth is in a class, yet
  2267                                 // origin is an interface. This case arises only
  2268                                 // if implmeth is declared in Object. The reason is
  2269                                 // that interfaces really don't inherit from
  2270                                 // Object it's just that the compiler represents
  2271                                 // things that way.
  2272                                 checkOverride(tree, implmeth, absmeth, origin);
  2280     /** Check that all abstract methods implemented by a class are
  2281      *  mutually compatible.
  2282      *  @param pos          Position to be used for error reporting.
  2283      *  @param c            The class whose interfaces are checked.
  2284      */
  2285     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2286         List<Type> supertypes = types.interfaces(c);
  2287         Type supertype = types.supertype(c);
  2288         if (supertype.hasTag(CLASS) &&
  2289             (supertype.tsym.flags() & ABSTRACT) != 0)
  2290             supertypes = supertypes.prepend(supertype);
  2291         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2292             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2293                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2294                 return;
  2295             for (List<Type> m = supertypes; m != l; m = m.tail)
  2296                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2297                     return;
  2299         checkCompatibleConcretes(pos, c);
  2302     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2303         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2304             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2305                 // VM allows methods and variables with differing types
  2306                 if (sym.kind == e.sym.kind &&
  2307                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2308                     sym != e.sym &&
  2309                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2310                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2311                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2312                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2313                     return;
  2319     /** Check that all non-override equivalent methods accessible from 'site'
  2320      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2322      *  @param pos  Position to be used for error reporting.
  2323      *  @param site The class whose methods are checked.
  2324      *  @param sym  The method symbol to be checked.
  2325      */
  2326     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2327          ClashFilter cf = new ClashFilter(site);
  2328         //for each method m1 that is overridden (directly or indirectly)
  2329         //by method 'sym' in 'site'...
  2330         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2331             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2332              //...check each method m2 that is a member of 'site'
  2333              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2334                 if (m2 == m1) continue;
  2335                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2336                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2337                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2338                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2339                     sym.flags_field |= CLASH;
  2340                     String key = m1 == sym ?
  2341                             "name.clash.same.erasure.no.override" :
  2342                             "name.clash.same.erasure.no.override.1";
  2343                     log.error(pos,
  2344                             key,
  2345                             sym, sym.location(),
  2346                             m2, m2.location(),
  2347                             m1, m1.location());
  2348                     return;
  2356     /** Check that all static methods accessible from 'site' are
  2357      *  mutually compatible (JLS 8.4.8).
  2359      *  @param pos  Position to be used for error reporting.
  2360      *  @param site The class whose methods are checked.
  2361      *  @param sym  The method symbol to be checked.
  2362      */
  2363     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2364         ClashFilter cf = new ClashFilter(site);
  2365         //for each method m1 that is a member of 'site'...
  2366         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2367             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2368             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2369             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2370                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2371                 log.error(pos,
  2372                         "name.clash.same.erasure.no.hide",
  2373                         sym, sym.location(),
  2374                         s, s.location());
  2375                 return;
  2380      //where
  2381      private class ClashFilter implements Filter<Symbol> {
  2383          Type site;
  2385          ClashFilter(Type site) {
  2386              this.site = site;
  2389          boolean shouldSkip(Symbol s) {
  2390              return (s.flags() & CLASH) != 0 &&
  2391                 s.owner == site.tsym;
  2394          public boolean accepts(Symbol s) {
  2395              return s.kind == MTH &&
  2396                      (s.flags() & SYNTHETIC) == 0 &&
  2397                      !shouldSkip(s) &&
  2398                      s.isInheritedIn(site.tsym, types) &&
  2399                      !s.isConstructor();
  2403     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2404         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2405         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2406             Assert.check(m.kind == MTH);
  2407             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2408             if (prov.size() > 1) {
  2409                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2410                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2411                 for (MethodSymbol provSym : prov) {
  2412                     if ((provSym.flags() & DEFAULT) != 0) {
  2413                         defaults = defaults.append(provSym);
  2414                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2415                         abstracts = abstracts.append(provSym);
  2417                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2418                         //strong semantics - issue an error if two sibling interfaces
  2419                         //have two override-equivalent defaults - or if one is abstract
  2420                         //and the other is default
  2421                         String errKey;
  2422                         Symbol s1 = defaults.first();
  2423                         Symbol s2;
  2424                         if (defaults.size() > 1) {
  2425                             errKey = "types.incompatible.unrelated.defaults";
  2426                             s2 = defaults.toList().tail.head;
  2427                         } else {
  2428                             errKey = "types.incompatible.abstract.default";
  2429                             s2 = abstracts.first();
  2431                         log.error(pos, errKey,
  2432                                 Kinds.kindName(site.tsym), site,
  2433                                 m.name, types.memberType(site, m).getParameterTypes(),
  2434                                 s1.location(), s2.location());
  2435                         break;
  2442     //where
  2443      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2445          Type site;
  2447          DefaultMethodClashFilter(Type site) {
  2448              this.site = site;
  2451          public boolean accepts(Symbol s) {
  2452              return s.kind == MTH &&
  2453                      (s.flags() & DEFAULT) != 0 &&
  2454                      s.isInheritedIn(site.tsym, types) &&
  2455                      !s.isConstructor();
  2459     /** Report a conflict between a user symbol and a synthetic symbol.
  2460      */
  2461     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2462         if (!sym.type.isErroneous()) {
  2463             if (warnOnSyntheticConflicts) {
  2464                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2466             else {
  2467                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2472     /** Check that class c does not implement directly or indirectly
  2473      *  the same parameterized interface with two different argument lists.
  2474      *  @param pos          Position to be used for error reporting.
  2475      *  @param type         The type whose interfaces are checked.
  2476      */
  2477     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2478         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2480 //where
  2481         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2482          *  with their class symbol as key and their type as value. Make
  2483          *  sure no class is entered with two different types.
  2484          */
  2485         void checkClassBounds(DiagnosticPosition pos,
  2486                               Map<TypeSymbol,Type> seensofar,
  2487                               Type type) {
  2488             if (type.isErroneous()) return;
  2489             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2490                 Type it = l.head;
  2491                 Type oldit = seensofar.put(it.tsym, it);
  2492                 if (oldit != null) {
  2493                     List<Type> oldparams = oldit.allparams();
  2494                     List<Type> newparams = it.allparams();
  2495                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2496                         log.error(pos, "cant.inherit.diff.arg",
  2497                                   it.tsym, Type.toString(oldparams),
  2498                                   Type.toString(newparams));
  2500                 checkClassBounds(pos, seensofar, it);
  2502             Type st = types.supertype(type);
  2503             if (st != null) checkClassBounds(pos, seensofar, st);
  2506     /** Enter interface into into set.
  2507      *  If it existed already, issue a "repeated interface" error.
  2508      */
  2509     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2510         if (its.contains(it))
  2511             log.error(pos, "repeated.interface");
  2512         else {
  2513             its.add(it);
  2517 /* *************************************************************************
  2518  * Check annotations
  2519  **************************************************************************/
  2521     /**
  2522      * Recursively validate annotations values
  2523      */
  2524     void validateAnnotationTree(JCTree tree) {
  2525         class AnnotationValidator extends TreeScanner {
  2526             @Override
  2527             public void visitAnnotation(JCAnnotation tree) {
  2528                 if (!tree.type.isErroneous()) {
  2529                     super.visitAnnotation(tree);
  2530                     validateAnnotation(tree);
  2534         tree.accept(new AnnotationValidator());
  2537     /**
  2538      *  {@literal
  2539      *  Annotation types are restricted to primitives, String, an
  2540      *  enum, an annotation, Class, Class<?>, Class<? extends
  2541      *  Anything>, arrays of the preceding.
  2542      *  }
  2543      */
  2544     void validateAnnotationType(JCTree restype) {
  2545         // restype may be null if an error occurred, so don't bother validating it
  2546         if (restype != null) {
  2547             validateAnnotationType(restype.pos(), restype.type);
  2551     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2552         if (type.isPrimitive()) return;
  2553         if (types.isSameType(type, syms.stringType)) return;
  2554         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2555         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2556         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2557         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2558             validateAnnotationType(pos, types.elemtype(type));
  2559             return;
  2561         log.error(pos, "invalid.annotation.member.type");
  2564     /**
  2565      * "It is also a compile-time error if any method declared in an
  2566      * annotation type has a signature that is override-equivalent to
  2567      * that of any public or protected method declared in class Object
  2568      * or in the interface annotation.Annotation."
  2570      * @jls 9.6 Annotation Types
  2571      */
  2572     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2573         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2574             Scope s = sup.tsym.members();
  2575             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2576                 if (e.sym.kind == MTH &&
  2577                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2578                     types.overrideEquivalent(m.type, e.sym.type))
  2579                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2584     /** Check the annotations of a symbol.
  2585      */
  2586     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2587         for (JCAnnotation a : annotations)
  2588             validateAnnotation(a, s);
  2591     /** Check the type annotations.
  2592      */
  2593     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
  2594         for (JCAnnotation a : annotations)
  2595             validateTypeAnnotation(a, isTypeParameter);
  2598     /** Check an annotation of a symbol.
  2599      */
  2600     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2601         validateAnnotationTree(a);
  2603         if (!annotationApplicable(a, s))
  2604             log.error(a.pos(), "annotation.type.not.applicable");
  2606         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2607             if (!isOverrider(s))
  2608                 log.error(a.pos(), "method.does.not.override.superclass");
  2611         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2612             if (s.kind != TYP) {
  2613                 log.error(a.pos(), "bad.functional.intf.anno");
  2614             } else {
  2615                 try {
  2616                     types.findDescriptorSymbol((TypeSymbol)s);
  2617                 } catch (Types.FunctionDescriptorLookupError ex) {
  2618                     log.error(a.pos(), "bad.functional.intf.anno.1", ex.getDiagnostic());
  2624     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2625         Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
  2626         validateAnnotationTree(a);
  2628         if (!isTypeAnnotation(a, isTypeParameter))
  2629             log.error(a.pos(), "annotation.type.not.applicable");
  2632     /**
  2633      * Validate the proposed container 'repeatable' on the
  2634      * annotation type symbol 's'. Report errors at position
  2635      * 'pos'.
  2637      * @param s The (annotation)type declaration annotated with a @Repeatable
  2638      * @param repeatable the @Repeatable on 's'
  2639      * @param pos where to report errors
  2640      */
  2641     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2642         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2644         Type t = null;
  2645         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2646         if (!l.isEmpty()) {
  2647             Assert.check(l.head.fst.name == names.value);
  2648             t = ((Attribute.Class)l.head.snd).getValue();
  2651         if (t == null) {
  2652             // errors should already have been reported during Annotate
  2653             return;
  2656         validateValue(t.tsym, s, pos);
  2657         validateRetention(t.tsym, s, pos);
  2658         validateDocumented(t.tsym, s, pos);
  2659         validateInherited(t.tsym, s, pos);
  2660         validateTarget(t.tsym, s, pos);
  2661         validateDefault(t.tsym, s, pos);
  2664     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2665         Scope.Entry e = container.members().lookup(names.value);
  2666         if (e.scope != null && e.sym.kind == MTH) {
  2667             MethodSymbol m = (MethodSymbol) e.sym;
  2668             Type ret = m.getReturnType();
  2669             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2670                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2671                         container, ret, types.makeArrayType(contained.type));
  2673         } else {
  2674             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2678     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2679         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2680         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2682         boolean error = false;
  2683         switch (containedRetention) {
  2684         case RUNTIME:
  2685             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2686                 error = true;
  2688             break;
  2689         case CLASS:
  2690             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2691                 error = true;
  2694         if (error ) {
  2695             log.error(pos, "invalid.repeatable.annotation.retention",
  2696                       container, containerRetention,
  2697                       contained, containedRetention);
  2701     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2702         if (contained.attribute(syms.documentedType.tsym) != null) {
  2703             if (container.attribute(syms.documentedType.tsym) == null) {
  2704                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2709     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2710         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2711             if (container.attribute(syms.inheritedType.tsym) == null) {
  2712                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2717     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2718         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2720         // If contained has no Target, we are done
  2721         if (containedTarget == null) {
  2722             return;
  2725         // If contained has Target m1, container must have a Target
  2726         // annotation, m2, and m2 must be a subset of m1. (This is
  2727         // trivially true if contained has no target as per above).
  2729         // contained has target, but container has not, error
  2730         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2731         if (containerTarget == null) {
  2732             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2733             return;
  2736         Set<Name> containerTargets = new HashSet<Name>();
  2737         for (Attribute app : containerTarget.values) {
  2738             if (!(app instanceof Attribute.Enum)) {
  2739                 continue; // recovery
  2741             Attribute.Enum e = (Attribute.Enum)app;
  2742             containerTargets.add(e.value.name);
  2745         Set<Name> containedTargets = new HashSet<Name>();
  2746         for (Attribute app : containedTarget.values) {
  2747             if (!(app instanceof Attribute.Enum)) {
  2748                 continue; // recovery
  2750             Attribute.Enum e = (Attribute.Enum)app;
  2751             containedTargets.add(e.value.name);
  2754         if (!isTargetSubset(containedTargets, containerTargets)) {
  2755             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2759     /** Checks that t is a subset of s, with respect to ElementType
  2760      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2761      */
  2762     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2763         // Check that all elements in t are present in s
  2764         for (Name n2 : t) {
  2765             boolean currentElementOk = false;
  2766             for (Name n1 : s) {
  2767                 if (n1 == n2) {
  2768                     currentElementOk = true;
  2769                     break;
  2770                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2771                     currentElementOk = true;
  2772                     break;
  2775             if (!currentElementOk)
  2776                 return false;
  2778         return true;
  2781     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2782         // validate that all other elements of containing type has defaults
  2783         Scope scope = container.members();
  2784         for(Symbol elm : scope.getElements()) {
  2785             if (elm.name != names.value &&
  2786                 elm.kind == Kinds.MTH &&
  2787                 ((MethodSymbol)elm).defaultValue == null) {
  2788                 log.error(pos,
  2789                           "invalid.repeatable.annotation.elem.nondefault",
  2790                           container,
  2791                           elm);
  2796     /** Is s a method symbol that overrides a method in a superclass? */
  2797     boolean isOverrider(Symbol s) {
  2798         if (s.kind != MTH || s.isStatic())
  2799             return false;
  2800         MethodSymbol m = (MethodSymbol)s;
  2801         TypeSymbol owner = (TypeSymbol)m.owner;
  2802         for (Type sup : types.closure(owner.type)) {
  2803             if (sup == owner.type)
  2804                 continue; // skip "this"
  2805             Scope scope = sup.tsym.members();
  2806             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2807                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2808                     return true;
  2811         return false;
  2814     /** Is the annotation applicable to type annotations? */
  2815     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2816         Attribute.Compound atTarget =
  2817             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2818         if (atTarget == null) {
  2819             // An annotation without @Target is not a type annotation.
  2820             return false;
  2823         Attribute atValue = atTarget.member(names.value);
  2824         if (!(atValue instanceof Attribute.Array)) {
  2825             return false; // error recovery
  2828         Attribute.Array arr = (Attribute.Array) atValue;
  2829         for (Attribute app : arr.values) {
  2830             if (!(app instanceof Attribute.Enum)) {
  2831                 return false; // recovery
  2833             Attribute.Enum e = (Attribute.Enum) app;
  2835             if (e.value.name == names.TYPE_USE)
  2836                 return true;
  2837             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  2838                 return true;
  2840         return false;
  2843     /** Is the annotation applicable to the symbol? */
  2844     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2845         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2846         Name[] targets;
  2848         if (arr == null) {
  2849             targets = defaultTargetMetaInfo(a, s);
  2850         } else {
  2851             // TODO: can we optimize this?
  2852             targets = new Name[arr.values.length];
  2853             for (int i=0; i<arr.values.length; ++i) {
  2854                 Attribute app = arr.values[i];
  2855                 if (!(app instanceof Attribute.Enum)) {
  2856                     return true; // recovery
  2858                 Attribute.Enum e = (Attribute.Enum) app;
  2859                 targets[i] = e.value.name;
  2862         for (Name target : targets) {
  2863             if (target == names.TYPE)
  2864                 { if (s.kind == TYP) return true; }
  2865             else if (target == names.FIELD)
  2866                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2867             else if (target == names.METHOD)
  2868                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2869             else if (target == names.PARAMETER)
  2870                 { if (s.kind == VAR &&
  2871                       s.owner.kind == MTH &&
  2872                       (s.flags() & PARAMETER) != 0)
  2873                     return true;
  2875             else if (target == names.CONSTRUCTOR)
  2876                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2877             else if (target == names.LOCAL_VARIABLE)
  2878                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2879                       (s.flags() & PARAMETER) == 0)
  2880                     return true;
  2882             else if (target == names.ANNOTATION_TYPE)
  2883                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2884                     return true;
  2886             else if (target == names.PACKAGE)
  2887                 { if (s.kind == PCK) return true; }
  2888             else if (target == names.TYPE_USE)
  2889                 { if (s.kind == TYP ||
  2890                       s.kind == VAR ||
  2891                       (s.kind == MTH && !s.isConstructor() &&
  2892                       !s.type.getReturnType().hasTag(VOID)) ||
  2893                       (s.kind == MTH && s.isConstructor()))
  2894                     return true;
  2896             else if (target == names.TYPE_PARAMETER)
  2897                 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
  2898                     return true;
  2900             else
  2901                 return true; // recovery
  2903         return false;
  2907     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2908         Attribute.Compound atTarget =
  2909             s.attribute(syms.annotationTargetType.tsym);
  2910         if (atTarget == null) return null; // ok, is applicable
  2911         Attribute atValue = atTarget.member(names.value);
  2912         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2913         return (Attribute.Array) atValue;
  2916     private final Name[] dfltTargetMeta;
  2917     private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
  2918         return dfltTargetMeta;
  2921     /** Check an annotation value.
  2923      * @param a The annotation tree to check
  2924      * @return true if this annotation tree is valid, otherwise false
  2925      */
  2926     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  2927         boolean res = false;
  2928         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  2929         try {
  2930             res = validateAnnotation(a);
  2931         } finally {
  2932             log.popDiagnosticHandler(diagHandler);
  2934         return res;
  2937     private boolean validateAnnotation(JCAnnotation a) {
  2938         boolean isValid = true;
  2939         // collect an inventory of the annotation elements
  2940         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  2941         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2942              e != null;
  2943              e = e.sibling)
  2944             if (e.sym.kind == MTH)
  2945                 members.add((MethodSymbol) e.sym);
  2947         // remove the ones that are assigned values
  2948         for (JCTree arg : a.args) {
  2949             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2950             JCAssign assign = (JCAssign) arg;
  2951             Symbol m = TreeInfo.symbol(assign.lhs);
  2952             if (m == null || m.type.isErroneous()) continue;
  2953             if (!members.remove(m)) {
  2954                 isValid = false;
  2955                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2956                           m.name, a.type);
  2960         // all the remaining ones better have default values
  2961         List<Name> missingDefaults = List.nil();
  2962         for (MethodSymbol m : members) {
  2963             if (m.defaultValue == null && !m.type.isErroneous()) {
  2964                 missingDefaults = missingDefaults.append(m.name);
  2967         missingDefaults = missingDefaults.reverse();
  2968         if (missingDefaults.nonEmpty()) {
  2969             isValid = false;
  2970             String key = (missingDefaults.size() > 1)
  2971                     ? "annotation.missing.default.value.1"
  2972                     : "annotation.missing.default.value";
  2973             log.error(a.pos(), key, a.type, missingDefaults);
  2976         // special case: java.lang.annotation.Target must not have
  2977         // repeated values in its value member
  2978         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2979             a.args.tail == null)
  2980             return isValid;
  2982         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  2983         JCAssign assign = (JCAssign) a.args.head;
  2984         Symbol m = TreeInfo.symbol(assign.lhs);
  2985         if (m.name != names.value) return false;
  2986         JCTree rhs = assign.rhs;
  2987         if (!rhs.hasTag(NEWARRAY)) return false;
  2988         JCNewArray na = (JCNewArray) rhs;
  2989         Set<Symbol> targets = new HashSet<Symbol>();
  2990         for (JCTree elem : na.elems) {
  2991             if (!targets.add(TreeInfo.symbol(elem))) {
  2992                 isValid = false;
  2993                 log.error(elem.pos(), "repeated.annotation.target");
  2996         return isValid;
  2999     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  3000         if (allowAnnotations &&
  3001             lint.isEnabled(LintCategory.DEP_ANN) &&
  3002             (s.flags() & DEPRECATED) != 0 &&
  3003             !syms.deprecatedType.isErroneous() &&
  3004             s.attribute(syms.deprecatedType.tsym) == null) {
  3005             log.warning(LintCategory.DEP_ANN,
  3006                     pos, "missing.deprecated.annotation");
  3010     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  3011         if ((s.flags() & DEPRECATED) != 0 &&
  3012                 (other.flags() & DEPRECATED) == 0 &&
  3013                 s.outermostClass() != other.outermostClass()) {
  3014             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3015                 @Override
  3016                 public void report() {
  3017                     warnDeprecated(pos, s);
  3019             });
  3023     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  3024         if ((s.flags() & PROPRIETARY) != 0) {
  3025             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3026                 public void report() {
  3027                     if (enableSunApiLintControl)
  3028                       warnSunApi(pos, "sun.proprietary", s);
  3029                     else
  3030                       log.mandatoryWarning(pos, "sun.proprietary", s);
  3032             });
  3036 /* *************************************************************************
  3037  * Check for recursive annotation elements.
  3038  **************************************************************************/
  3040     /** Check for cycles in the graph of annotation elements.
  3041      */
  3042     void checkNonCyclicElements(JCClassDecl tree) {
  3043         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  3044         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  3045         try {
  3046             tree.sym.flags_field |= LOCKED;
  3047             for (JCTree def : tree.defs) {
  3048                 if (!def.hasTag(METHODDEF)) continue;
  3049                 JCMethodDecl meth = (JCMethodDecl)def;
  3050                 checkAnnotationResType(meth.pos(), meth.restype.type);
  3052         } finally {
  3053             tree.sym.flags_field &= ~LOCKED;
  3054             tree.sym.flags_field |= ACYCLIC_ANN;
  3058     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  3059         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  3060             return;
  3061         if ((tsym.flags_field & LOCKED) != 0) {
  3062             log.error(pos, "cyclic.annotation.element");
  3063             return;
  3065         try {
  3066             tsym.flags_field |= LOCKED;
  3067             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3068                 Symbol s = e.sym;
  3069                 if (s.kind != Kinds.MTH)
  3070                     continue;
  3071                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3073         } finally {
  3074             tsym.flags_field &= ~LOCKED;
  3075             tsym.flags_field |= ACYCLIC_ANN;
  3079     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3080         switch (type.getTag()) {
  3081         case CLASS:
  3082             if ((type.tsym.flags() & ANNOTATION) != 0)
  3083                 checkNonCyclicElementsInternal(pos, type.tsym);
  3084             break;
  3085         case ARRAY:
  3086             checkAnnotationResType(pos, types.elemtype(type));
  3087             break;
  3088         default:
  3089             break; // int etc
  3093 /* *************************************************************************
  3094  * Check for cycles in the constructor call graph.
  3095  **************************************************************************/
  3097     /** Check for cycles in the graph of constructors calling other
  3098      *  constructors.
  3099      */
  3100     void checkCyclicConstructors(JCClassDecl tree) {
  3101         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3103         // enter each constructor this-call into the map
  3104         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3105             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3106             if (app == null) continue;
  3107             JCMethodDecl meth = (JCMethodDecl) l.head;
  3108             if (TreeInfo.name(app.meth) == names._this) {
  3109                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3110             } else {
  3111                 meth.sym.flags_field |= ACYCLIC;
  3115         // Check for cycles in the map
  3116         Symbol[] ctors = new Symbol[0];
  3117         ctors = callMap.keySet().toArray(ctors);
  3118         for (Symbol caller : ctors) {
  3119             checkCyclicConstructor(tree, caller, callMap);
  3123     /** Look in the map to see if the given constructor is part of a
  3124      *  call cycle.
  3125      */
  3126     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3127                                         Map<Symbol,Symbol> callMap) {
  3128         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3129             if ((ctor.flags_field & LOCKED) != 0) {
  3130                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3131                           "recursive.ctor.invocation");
  3132             } else {
  3133                 ctor.flags_field |= LOCKED;
  3134                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3135                 ctor.flags_field &= ~LOCKED;
  3137             ctor.flags_field |= ACYCLIC;
  3141 /* *************************************************************************
  3142  * Miscellaneous
  3143  **************************************************************************/
  3145     /**
  3146      * Return the opcode of the operator but emit an error if it is an
  3147      * error.
  3148      * @param pos        position for error reporting.
  3149      * @param operator   an operator
  3150      * @param tag        a tree tag
  3151      * @param left       type of left hand side
  3152      * @param right      type of right hand side
  3153      */
  3154     int checkOperator(DiagnosticPosition pos,
  3155                        OperatorSymbol operator,
  3156                        JCTree.Tag tag,
  3157                        Type left,
  3158                        Type right) {
  3159         if (operator.opcode == ByteCodes.error) {
  3160             log.error(pos,
  3161                       "operator.cant.be.applied.1",
  3162                       treeinfo.operatorName(tag),
  3163                       left, right);
  3165         return operator.opcode;
  3169     /**
  3170      *  Check for division by integer constant zero
  3171      *  @param pos           Position for error reporting.
  3172      *  @param operator      The operator for the expression
  3173      *  @param operand       The right hand operand for the expression
  3174      */
  3175     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3176         if (operand.constValue() != null
  3177             && lint.isEnabled(LintCategory.DIVZERO)
  3178             && (operand.getTag().isSubRangeOf(LONG))
  3179             && ((Number) (operand.constValue())).longValue() == 0) {
  3180             int opc = ((OperatorSymbol)operator).opcode;
  3181             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3182                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3183                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3188     /**
  3189      * Check for empty statements after if
  3190      */
  3191     void checkEmptyIf(JCIf tree) {
  3192         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3193                 lint.isEnabled(LintCategory.EMPTY))
  3194             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3197     /** Check that symbol is unique in given scope.
  3198      *  @param pos           Position for error reporting.
  3199      *  @param sym           The symbol.
  3200      *  @param s             The scope.
  3201      */
  3202     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3203         if (sym.type.isErroneous())
  3204             return true;
  3205         if (sym.owner.name == names.any) return false;
  3206         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3207             if (sym != e.sym &&
  3208                     (e.sym.flags() & CLASH) == 0 &&
  3209                     sym.kind == e.sym.kind &&
  3210                     sym.name != names.error &&
  3211                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3212                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3213                     varargsDuplicateError(pos, sym, e.sym);
  3214                     return true;
  3215                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3216                     duplicateErasureError(pos, sym, e.sym);
  3217                     sym.flags_field |= CLASH;
  3218                     return true;
  3219                 } else {
  3220                     duplicateError(pos, e.sym);
  3221                     return false;
  3225         return true;
  3228     /** Report duplicate declaration error.
  3229      */
  3230     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3231         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3232             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3236     /** Check that single-type import is not already imported or top-level defined,
  3237      *  but make an exception for two single-type imports which denote the same type.
  3238      *  @param pos           Position for error reporting.
  3239      *  @param sym           The symbol.
  3240      *  @param s             The scope
  3241      */
  3242     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3243         return checkUniqueImport(pos, sym, s, false);
  3246     /** Check that static single-type import is not already imported or top-level defined,
  3247      *  but make an exception for two single-type imports which denote the same type.
  3248      *  @param pos           Position for error reporting.
  3249      *  @param sym           The symbol.
  3250      *  @param s             The scope
  3251      */
  3252     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3253         return checkUniqueImport(pos, sym, s, true);
  3256     /** Check that single-type import is not already imported or top-level defined,
  3257      *  but make an exception for two single-type imports which denote the same type.
  3258      *  @param pos           Position for error reporting.
  3259      *  @param sym           The symbol.
  3260      *  @param s             The scope.
  3261      *  @param staticImport  Whether or not this was a static import
  3262      */
  3263     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3264         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3265             // is encountered class entered via a class declaration?
  3266             boolean isClassDecl = e.scope == s;
  3267             if ((isClassDecl || sym != e.sym) &&
  3268                 sym.kind == e.sym.kind &&
  3269                 sym.name != names.error) {
  3270                 if (!e.sym.type.isErroneous()) {
  3271                     String what = e.sym.toString();
  3272                     if (!isClassDecl) {
  3273                         if (staticImport)
  3274                             log.error(pos, "already.defined.static.single.import", what);
  3275                         else
  3276                             log.error(pos, "already.defined.single.import", what);
  3278                     else if (sym != e.sym)
  3279                         log.error(pos, "already.defined.this.unit", what);
  3281                 return false;
  3284         return true;
  3287     /** Check that a qualified name is in canonical form (for import decls).
  3288      */
  3289     public void checkCanonical(JCTree tree) {
  3290         if (!isCanonical(tree))
  3291             log.error(tree.pos(), "import.requires.canonical",
  3292                       TreeInfo.symbol(tree));
  3294         // where
  3295         private boolean isCanonical(JCTree tree) {
  3296             while (tree.hasTag(SELECT)) {
  3297                 JCFieldAccess s = (JCFieldAccess) tree;
  3298                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3299                     return false;
  3300                 tree = s.selected;
  3302             return true;
  3305     /** Check that an auxiliary class is not accessed from any other file than its own.
  3306      */
  3307     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3308         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3309             (c.flags() & AUXILIARY) != 0 &&
  3310             rs.isAccessible(env, c) &&
  3311             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3313             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3314                         c, c.sourcefile);
  3318     private class ConversionWarner extends Warner {
  3319         final String uncheckedKey;
  3320         final Type found;
  3321         final Type expected;
  3322         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3323             super(pos);
  3324             this.uncheckedKey = uncheckedKey;
  3325             this.found = found;
  3326             this.expected = expected;
  3329         @Override
  3330         public void warn(LintCategory lint) {
  3331             boolean warned = this.warned;
  3332             super.warn(lint);
  3333             if (warned) return; // suppress redundant diagnostics
  3334             switch (lint) {
  3335                 case UNCHECKED:
  3336                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3337                     break;
  3338                 case VARARGS:
  3339                     if (method != null &&
  3340                             method.attribute(syms.trustMeType.tsym) != null &&
  3341                             isTrustMeAllowedOnMethod(method) &&
  3342                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3343                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3345                     break;
  3346                 default:
  3347                     throw new AssertionError("Unexpected lint: " + lint);
  3352     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3353         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3356     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3357         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial