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

Mon, 14 Oct 2013 22:11:09 +0200

author
jlahoda
date
Mon, 14 Oct 2013 22:11:09 +0200
changeset 2111
87b5bfef7edb
parent 2102
6dcf94e32a3a
child 2118
d8d6b58f1ebf
permissions
-rw-r--r--

8014016: javac is too late detecting invalid annotation usage
Summary: Adding new queue to Annotate for validation tasks, performing annotation validation during enter
Reviewed-by: jjg, emc, jfranck

     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.code.Attribute.Compound;
    34 import com.sun.tools.javac.jvm.*;
    35 import com.sun.tools.javac.tree.*;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    38 import com.sun.tools.javac.util.List;
    40 import com.sun.tools.javac.code.Lint;
    41 import com.sun.tools.javac.code.Lint.LintCategory;
    42 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.code.Symbol.*;
    44 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    45 import com.sun.tools.javac.comp.Infer.InferenceContext;
    46 import com.sun.tools.javac.comp.Infer.FreeTypeListener;
    47 import com.sun.tools.javac.tree.JCTree.*;
    48 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
    50 import static com.sun.tools.javac.code.Flags.*;
    51 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    52 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    53 import static com.sun.tools.javac.code.Kinds.*;
    54 import static com.sun.tools.javac.code.TypeTag.*;
    55 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    57 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    59 /** Type checking helper class for the attribution phase.
    60  *
    61  *  <p><b>This is NOT part of any supported API.
    62  *  If you write code that depends on this, you do so at your own risk.
    63  *  This code and its internal interfaces are subject to change or
    64  *  deletion without notice.</b>
    65  */
    66 public class Check {
    67     protected static final Context.Key<Check> checkKey =
    68         new Context.Key<Check>();
    70     private final Names names;
    71     private final Log log;
    72     private final Resolve rs;
    73     private final Symtab syms;
    74     private final Enter enter;
    75     private final DeferredAttr deferredAttr;
    76     private final Infer infer;
    77     private final Types types;
    78     private final JCDiagnostic.Factory diags;
    79     private boolean warnOnSyntheticConflicts;
    80     private boolean suppressAbortOnBadClassFile;
    81     private boolean enableSunApiLintControl;
    82     private final TreeInfo treeinfo;
    83     private final JavaFileManager fileManager;
    84     private final Profile profile;
    86     // The set of lint options currently in effect. It is initialized
    87     // from the context, and then is set/reset as needed by Attr as it
    88     // visits all the various parts of the trees during attribution.
    89     private Lint lint;
    91     // The method being analyzed in Attr - it is set/reset as needed by
    92     // Attr as it visits new method declarations.
    93     private MethodSymbol method;
    95     public static Check instance(Context context) {
    96         Check instance = context.get(checkKey);
    97         if (instance == null)
    98             instance = new Check(context);
    99         return instance;
   100     }
   102     protected Check(Context context) {
   103         context.put(checkKey, this);
   105         names = Names.instance(context);
   106         dfltTargetMeta = new Name[] { names.PACKAGE, names.TYPE,
   107             names.FIELD, names.METHOD, names.CONSTRUCTOR,
   108             names.ANNOTATION_TYPE, names.LOCAL_VARIABLE, names.PARAMETER};
   109         log = Log.instance(context);
   110         rs = Resolve.instance(context);
   111         syms = Symtab.instance(context);
   112         enter = Enter.instance(context);
   113         deferredAttr = DeferredAttr.instance(context);
   114         infer = Infer.instance(context);
   115         types = Types.instance(context);
   116         diags = JCDiagnostic.Factory.instance(context);
   117         Options options = Options.instance(context);
   118         lint = Lint.instance(context);
   119         treeinfo = TreeInfo.instance(context);
   120         fileManager = context.get(JavaFileManager.class);
   122         Source source = Source.instance(context);
   123         allowGenerics = source.allowGenerics();
   124         allowVarargs = source.allowVarargs();
   125         allowAnnotations = source.allowAnnotations();
   126         allowCovariantReturns = source.allowCovariantReturns();
   127         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   128         allowDefaultMethods = source.allowDefaultMethods();
   129         allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
   130         complexInference = options.isSet("complexinference");
   131         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   132         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   133         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   135         Target target = Target.instance(context);
   136         syntheticNameChar = target.syntheticNameChar();
   138         profile = Profile.instance(context);
   140         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   141         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   142         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   143         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   145         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   146                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   147         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   148                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   149         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   150                 enforceMandatoryWarnings, "sunapi", null);
   152         deferredLintHandler = DeferredLintHandler.instance(context);
   153     }
   155     /** Switch: generics enabled?
   156      */
   157     boolean allowGenerics;
   159     /** Switch: varargs enabled?
   160      */
   161     boolean allowVarargs;
   163     /** Switch: annotations enabled?
   164      */
   165     boolean allowAnnotations;
   167     /** Switch: covariant returns enabled?
   168      */
   169     boolean allowCovariantReturns;
   171     /** Switch: simplified varargs enabled?
   172      */
   173     boolean allowSimplifiedVarargs;
   175     /** Switch: default methods enabled?
   176      */
   177     boolean allowDefaultMethods;
   179     /** Switch: should unrelated return types trigger a method clash?
   180      */
   181     boolean allowStrictMethodClashCheck;
   183     /** Switch: -complexinference option set?
   184      */
   185     boolean complexInference;
   187     /** Character for synthetic names
   188      */
   189     char syntheticNameChar;
   191     /** A table mapping flat names of all compiled classes in this run to their
   192      *  symbols; maintained from outside.
   193      */
   194     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   196     /** A handler for messages about deprecated usage.
   197      */
   198     private MandatoryWarningHandler deprecationHandler;
   200     /** A handler for messages about unchecked or unsafe usage.
   201      */
   202     private MandatoryWarningHandler uncheckedHandler;
   204     /** A handler for messages about using proprietary API.
   205      */
   206     private MandatoryWarningHandler sunApiHandler;
   208     /** A handler for deferred lint warnings.
   209      */
   210     private DeferredLintHandler deferredLintHandler;
   212 /* *************************************************************************
   213  * Errors and Warnings
   214  **************************************************************************/
   216     Lint setLint(Lint newLint) {
   217         Lint prev = lint;
   218         lint = newLint;
   219         return prev;
   220     }
   222     MethodSymbol setMethod(MethodSymbol newMethod) {
   223         MethodSymbol prev = method;
   224         method = newMethod;
   225         return prev;
   226     }
   228     /** Warn about deprecated symbol.
   229      *  @param pos        Position to be used for error reporting.
   230      *  @param sym        The deprecated symbol.
   231      */
   232     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   233         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   234             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   235     }
   237     /** Warn about unchecked operation.
   238      *  @param pos        Position to be used for error reporting.
   239      *  @param msg        A string describing the problem.
   240      */
   241     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   242         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   243             uncheckedHandler.report(pos, msg, args);
   244     }
   246     /** Warn about unsafe vararg method decl.
   247      *  @param pos        Position to be used for error reporting.
   248      */
   249     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   250         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   251             log.warning(LintCategory.VARARGS, pos, key, args);
   252     }
   254     /** Warn about using proprietary API.
   255      *  @param pos        Position to be used for error reporting.
   256      *  @param msg        A string describing the problem.
   257      */
   258     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   259         if (!lint.isSuppressed(LintCategory.SUNAPI))
   260             sunApiHandler.report(pos, msg, args);
   261     }
   263     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   264         if (lint.isEnabled(LintCategory.STATIC))
   265             log.warning(LintCategory.STATIC, pos, msg, args);
   266     }
   268     /**
   269      * Report any deferred diagnostics.
   270      */
   271     public void reportDeferredDiagnostics() {
   272         deprecationHandler.reportDeferredDiagnostic();
   273         uncheckedHandler.reportDeferredDiagnostic();
   274         sunApiHandler.reportDeferredDiagnostic();
   275     }
   278     /** Report a failure to complete a class.
   279      *  @param pos        Position to be used for error reporting.
   280      *  @param ex         The failure to report.
   281      */
   282     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   283         log.error(JCDiagnostic.DiagnosticFlag.NON_DEFERRABLE, pos, "cant.access", ex.sym, ex.getDetailValue());
   284         if (ex instanceof ClassReader.BadClassFile
   285                 && !suppressAbortOnBadClassFile) throw new Abort();
   286         else return syms.errType;
   287     }
   289     /** Report an error that wrong type tag was found.
   290      *  @param pos        Position to be used for error reporting.
   291      *  @param required   An internationalized string describing the type tag
   292      *                    required.
   293      *  @param found      The type that was found.
   294      */
   295     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   296         // this error used to be raised by the parser,
   297         // but has been delayed to this point:
   298         if (found instanceof Type && ((Type)found).hasTag(VOID)) {
   299             log.error(pos, "illegal.start.of.type");
   300             return syms.errType;
   301         }
   302         log.error(pos, "type.found.req", found, required);
   303         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   304     }
   306     /** Report an error that symbol cannot be referenced before super
   307      *  has been called.
   308      *  @param pos        Position to be used for error reporting.
   309      *  @param sym        The referenced symbol.
   310      */
   311     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   312         log.error(pos, "cant.ref.before.ctor.called", sym);
   313     }
   315     /** Report duplicate declaration error.
   316      */
   317     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   318         if (!sym.type.isErroneous()) {
   319             Symbol location = sym.location();
   320             if (location.kind == MTH &&
   321                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   322                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   323                         kindName(sym.location()), kindName(sym.location().enclClass()),
   324                         sym.location().enclClass());
   325             } else {
   326                 log.error(pos, "already.defined", kindName(sym), sym,
   327                         kindName(sym.location()), sym.location());
   328             }
   329         }
   330     }
   332     /** Report array/varargs duplicate declaration
   333      */
   334     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   335         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   336             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   337         }
   338     }
   340 /* ************************************************************************
   341  * duplicate declaration checking
   342  *************************************************************************/
   344     /** Check that variable does not hide variable with same name in
   345      *  immediately enclosing local scope.
   346      *  @param pos           Position for error reporting.
   347      *  @param v             The symbol.
   348      *  @param s             The scope.
   349      */
   350     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   351         if (s.next != null) {
   352             for (Scope.Entry e = s.next.lookup(v.name);
   353                  e.scope != null && e.sym.owner == v.owner;
   354                  e = e.next()) {
   355                 if (e.sym.kind == VAR &&
   356                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   357                     v.name != names.error) {
   358                     duplicateError(pos, e.sym);
   359                     return;
   360                 }
   361             }
   362         }
   363     }
   365     /** Check that a class or interface does not hide a class or
   366      *  interface with same name in immediately enclosing local scope.
   367      *  @param pos           Position for error reporting.
   368      *  @param c             The symbol.
   369      *  @param s             The scope.
   370      */
   371     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   372         if (s.next != null) {
   373             for (Scope.Entry e = s.next.lookup(c.name);
   374                  e.scope != null && e.sym.owner == c.owner;
   375                  e = e.next()) {
   376                 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
   377                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   378                     c.name != names.error) {
   379                     duplicateError(pos, e.sym);
   380                     return;
   381                 }
   382             }
   383         }
   384     }
   386     /** Check that class does not have the same name as one of
   387      *  its enclosing classes, or as a class defined in its enclosing scope.
   388      *  return true if class is unique in its enclosing scope.
   389      *  @param pos           Position for error reporting.
   390      *  @param name          The class name.
   391      *  @param s             The enclosing scope.
   392      */
   393     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   394         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   395             if (e.sym.kind == TYP && e.sym.name != names.error) {
   396                 duplicateError(pos, e.sym);
   397                 return false;
   398             }
   399         }
   400         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   401             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   402                 duplicateError(pos, sym);
   403                 return true;
   404             }
   405         }
   406         return true;
   407     }
   409 /* *************************************************************************
   410  * Class name generation
   411  **************************************************************************/
   413     /** Return name of local class.
   414      *  This is of the form   {@code <enclClass> $ n <classname> }
   415      *  where
   416      *    enclClass is the flat name of the enclosing class,
   417      *    classname is the simple name of the local class
   418      */
   419     Name localClassName(ClassSymbol c) {
   420         for (int i=1; ; i++) {
   421             Name flatname = names.
   422                 fromString("" + c.owner.enclClass().flatname +
   423                            syntheticNameChar + i +
   424                            c.name);
   425             if (compiled.get(flatname) == null) return flatname;
   426         }
   427     }
   429 /* *************************************************************************
   430  * Type Checking
   431  **************************************************************************/
   433     /**
   434      * A check context is an object that can be used to perform compatibility
   435      * checks - depending on the check context, meaning of 'compatibility' might
   436      * vary significantly.
   437      */
   438     public interface CheckContext {
   439         /**
   440          * Is type 'found' compatible with type 'req' in given context
   441          */
   442         boolean compatible(Type found, Type req, Warner warn);
   443         /**
   444          * Report a check error
   445          */
   446         void report(DiagnosticPosition pos, JCDiagnostic details);
   447         /**
   448          * Obtain a warner for this check context
   449          */
   450         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   452         public Infer.InferenceContext inferenceContext();
   454         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   455     }
   457     /**
   458      * This class represent a check context that is nested within another check
   459      * context - useful to check sub-expressions. The default behavior simply
   460      * redirects all method calls to the enclosing check context leveraging
   461      * the forwarding pattern.
   462      */
   463     static class NestedCheckContext implements CheckContext {
   464         CheckContext enclosingContext;
   466         NestedCheckContext(CheckContext enclosingContext) {
   467             this.enclosingContext = enclosingContext;
   468         }
   470         public boolean compatible(Type found, Type req, Warner warn) {
   471             return enclosingContext.compatible(found, req, warn);
   472         }
   474         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   475             enclosingContext.report(pos, details);
   476         }
   478         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   479             return enclosingContext.checkWarner(pos, found, req);
   480         }
   482         public Infer.InferenceContext inferenceContext() {
   483             return enclosingContext.inferenceContext();
   484         }
   486         public DeferredAttrContext deferredAttrContext() {
   487             return enclosingContext.deferredAttrContext();
   488         }
   489     }
   491     /**
   492      * Check context to be used when evaluating assignment/return statements
   493      */
   494     CheckContext basicHandler = new CheckContext() {
   495         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   496             log.error(pos, "prob.found.req", details);
   497         }
   498         public boolean compatible(Type found, Type req, Warner warn) {
   499             return types.isAssignable(found, req, warn);
   500         }
   502         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   503             return convertWarner(pos, found, req);
   504         }
   506         public InferenceContext inferenceContext() {
   507             return infer.emptyContext;
   508         }
   510         public DeferredAttrContext deferredAttrContext() {
   511             return deferredAttr.emptyDeferredAttrContext;
   512         }
   513     };
   515     /** Check that a given type is assignable to a given proto-type.
   516      *  If it is, return the type, otherwise return errType.
   517      *  @param pos        Position to be used for error reporting.
   518      *  @param found      The type that was found.
   519      *  @param req        The type that was required.
   520      */
   521     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   522         return checkType(pos, found, req, basicHandler);
   523     }
   525     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   526         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   527         if (inferenceContext.free(req)) {
   528             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   529                 @Override
   530                 public void typesInferred(InferenceContext inferenceContext) {
   531                     checkType(pos, found, inferenceContext.asInstType(req), checkContext);
   532                 }
   533             });
   534         }
   535         if (req.hasTag(ERROR))
   536             return req;
   537         if (req.hasTag(NONE))
   538             return found;
   539         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   540             return found;
   541         } else {
   542             if (found.isNumeric() && req.isNumeric()) {
   543                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   544                 return types.createErrorType(found);
   545             }
   546             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   547             return types.createErrorType(found);
   548         }
   549     }
   551     /** Check that a given type can be cast to a given target type.
   552      *  Return the result of the cast.
   553      *  @param pos        Position to be used for error reporting.
   554      *  @param found      The type that is being cast.
   555      *  @param req        The target type of the cast.
   556      */
   557     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   558         return checkCastable(pos, found, req, basicHandler);
   559     }
   560     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   561         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   562             return req;
   563         } else {
   564             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   565             return types.createErrorType(found);
   566         }
   567     }
   569     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   570      * The problem should only be reported for non-292 cast
   571      */
   572     public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
   573         if (!tree.type.isErroneous()
   574                 && types.isSameType(tree.expr.type, tree.clazz.type)
   575                 && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
   576                 && !is292targetTypeCast(tree)) {
   577             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
   578                 @Override
   579                 public void report() {
   580                     if (lint.isEnabled(Lint.LintCategory.CAST))
   581                         log.warning(Lint.LintCategory.CAST,
   582                                 tree.pos(), "redundant.cast", tree.expr.type);
   583                 }
   584             });
   585         }
   586     }
   587     //where
   588         private boolean is292targetTypeCast(JCTypeCast tree) {
   589             boolean is292targetTypeCast = false;
   590             JCExpression expr = TreeInfo.skipParens(tree.expr);
   591             if (expr.hasTag(APPLY)) {
   592                 JCMethodInvocation apply = (JCMethodInvocation)expr;
   593                 Symbol sym = TreeInfo.symbol(apply.meth);
   594                 is292targetTypeCast = sym != null &&
   595                     sym.kind == MTH &&
   596                     (sym.flags() & HYPOTHETICAL) != 0;
   597             }
   598             return is292targetTypeCast;
   599         }
   601         private static final boolean ignoreAnnotatedCasts = true;
   603     /** Check that a type is within some bounds.
   604      *
   605      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
   606      *  type argument.
   607      *  @param a             The type that should be bounded by bs.
   608      *  @param bound         The bound.
   609      */
   610     private boolean checkExtends(Type a, Type bound) {
   611          if (a.isUnbound()) {
   612              return true;
   613          } else if (!a.hasTag(WILDCARD)) {
   614              a = types.upperBound(a);
   615              return types.isSubtype(a, bound);
   616          } else if (a.isExtendsBound()) {
   617              return types.isCastable(bound, types.upperBound(a), types.noWarnings);
   618          } else if (a.isSuperBound()) {
   619              return !types.notSoftSubtype(types.lowerBound(a), bound);
   620          }
   621          return true;
   622      }
   624     /** Check that type is different from 'void'.
   625      *  @param pos           Position to be used for error reporting.
   626      *  @param t             The type to be checked.
   627      */
   628     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   629         if (t.hasTag(VOID)) {
   630             log.error(pos, "void.not.allowed.here");
   631             return types.createErrorType(t);
   632         } else {
   633             return t;
   634         }
   635     }
   637     Type checkClassOrArrayType(DiagnosticPosition pos, Type t) {
   638         if (!t.hasTag(CLASS) && !t.hasTag(ARRAY) && !t.hasTag(ERROR)) {
   639             return typeTagError(pos,
   640                                 diags.fragment("type.req.class.array"),
   641                                 asTypeParam(t));
   642         } else {
   643             return t;
   644         }
   645     }
   647     /** Check that type is a class or interface type.
   648      *  @param pos           Position to be used for error reporting.
   649      *  @param t             The type to be checked.
   650      */
   651     Type checkClassType(DiagnosticPosition pos, Type t) {
   652         if (!t.hasTag(CLASS) && !t.hasTag(ERROR)) {
   653             return typeTagError(pos,
   654                                 diags.fragment("type.req.class"),
   655                                 asTypeParam(t));
   656         } else {
   657             return t;
   658         }
   659     }
   660     //where
   661         private Object asTypeParam(Type t) {
   662             return (t.hasTag(TYPEVAR))
   663                                     ? diags.fragment("type.parameter", t)
   664                                     : t;
   665         }
   667     /** Check that type is a valid qualifier for a constructor reference expression
   668      */
   669     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
   670         t = checkClassOrArrayType(pos, t);
   671         if (t.hasTag(CLASS)) {
   672             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
   673                 log.error(pos, "abstract.cant.be.instantiated", t.tsym);
   674                 t = types.createErrorType(t);
   675             } else if ((t.tsym.flags() & ENUM) != 0) {
   676                 log.error(pos, "enum.cant.be.instantiated");
   677                 t = types.createErrorType(t);
   678             } else {
   679                 t = checkClassType(pos, t, true);
   680             }
   681         } else if (t.hasTag(ARRAY)) {
   682             if (!types.isReifiable(((ArrayType)t).elemtype)) {
   683                 log.error(pos, "generic.array.creation");
   684                 t = types.createErrorType(t);
   685             }
   686         }
   687         return t;
   688     }
   690     /** Check that type is a class or interface type.
   691      *  @param pos           Position to be used for error reporting.
   692      *  @param t             The type to be checked.
   693      *  @param noBounds    True if type bounds are illegal here.
   694      */
   695     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   696         t = checkClassType(pos, t);
   697         if (noBounds && t.isParameterized()) {
   698             List<Type> args = t.getTypeArguments();
   699             while (args.nonEmpty()) {
   700                 if (args.head.hasTag(WILDCARD))
   701                     return typeTagError(pos,
   702                                         diags.fragment("type.req.exact"),
   703                                         args.head);
   704                 args = args.tail;
   705             }
   706         }
   707         return t;
   708     }
   710     // Analog of checkClassType that calls checkClassOrArrayType instead
   711     Type checkClassOrArrayType(DiagnosticPosition pos,
   712                                Type t, boolean noBounds) {
   713         t = checkClassOrArrayType(pos, t);
   714         if (noBounds && t.isParameterized()) {
   715             List<Type> args = t.getTypeArguments();
   716             while (args.nonEmpty()) {
   717                 if (args.head.hasTag(WILDCARD))
   718                     return typeTagError(pos,
   719                                         diags.fragment("type.req.exact"),
   720                                         args.head);
   721                 args = args.tail;
   722             }
   723         }
   724         return t;
   725     }
   727     /** Check that type is a reifiable class, interface or array type.
   728      *  @param pos           Position to be used for error reporting.
   729      *  @param t             The type to be checked.
   730      */
   731     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   732         t = checkClassOrArrayType(pos, t);
   733         if (!t.isErroneous() && !types.isReifiable(t)) {
   734             log.error(pos, "illegal.generic.type.for.instof");
   735             return types.createErrorType(t);
   736         } else {
   737             return t;
   738         }
   739     }
   741     /** Check that type is a reference type, i.e. a class, interface or array type
   742      *  or a type variable.
   743      *  @param pos           Position to be used for error reporting.
   744      *  @param t             The type to be checked.
   745      */
   746     Type checkRefType(DiagnosticPosition pos, Type t) {
   747         if (t.isReference())
   748             return t;
   749         else
   750             return typeTagError(pos,
   751                                 diags.fragment("type.req.ref"),
   752                                 t);
   753     }
   755     /** Check that each type is a reference type, i.e. a class, interface or array type
   756      *  or a type variable.
   757      *  @param trees         Original trees, used for error reporting.
   758      *  @param types         The types to be checked.
   759      */
   760     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   761         List<JCExpression> tl = trees;
   762         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   763             l.head = checkRefType(tl.head.pos(), l.head);
   764             tl = tl.tail;
   765         }
   766         return types;
   767     }
   769     /** Check that type is a null or reference type.
   770      *  @param pos           Position to be used for error reporting.
   771      *  @param t             The type to be checked.
   772      */
   773     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   774         if (t.isReference() || t.hasTag(BOT))
   775             return t;
   776         else
   777             return typeTagError(pos,
   778                                 diags.fragment("type.req.ref"),
   779                                 t);
   780     }
   782     /** Check that flag set does not contain elements of two conflicting sets. s
   783      *  Return true if it doesn't.
   784      *  @param pos           Position to be used for error reporting.
   785      *  @param flags         The set of flags to be checked.
   786      *  @param set1          Conflicting flags set #1.
   787      *  @param set2          Conflicting flags set #2.
   788      */
   789     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   790         if ((flags & set1) != 0 && (flags & set2) != 0) {
   791             log.error(pos,
   792                       "illegal.combination.of.modifiers",
   793                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   794                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   795             return false;
   796         } else
   797             return true;
   798     }
   800     /** Check that usage of diamond operator is correct (i.e. diamond should not
   801      * be used with non-generic classes or in anonymous class creation expressions)
   802      */
   803     Type checkDiamond(JCNewClass tree, Type t) {
   804         if (!TreeInfo.isDiamond(tree) ||
   805                 t.isErroneous()) {
   806             return checkClassType(tree.clazz.pos(), t, true);
   807         } else if (tree.def != null) {
   808             log.error(tree.clazz.pos(),
   809                     "cant.apply.diamond.1",
   810                     t, diags.fragment("diamond.and.anon.class", t));
   811             return types.createErrorType(t);
   812         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   813             log.error(tree.clazz.pos(),
   814                 "cant.apply.diamond.1",
   815                 t, diags.fragment("diamond.non.generic", t));
   816             return types.createErrorType(t);
   817         } else if (tree.typeargs != null &&
   818                 tree.typeargs.nonEmpty()) {
   819             log.error(tree.clazz.pos(),
   820                 "cant.apply.diamond.1",
   821                 t, diags.fragment("diamond.and.explicit.params", t));
   822             return types.createErrorType(t);
   823         } else {
   824             return t;
   825         }
   826     }
   828     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   829         MethodSymbol m = tree.sym;
   830         if (!allowSimplifiedVarargs) return;
   831         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   832         Type varargElemType = null;
   833         if (m.isVarArgs()) {
   834             varargElemType = types.elemtype(tree.params.last().type);
   835         }
   836         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   837             if (varargElemType != null) {
   838                 log.error(tree,
   839                         "varargs.invalid.trustme.anno",
   840                         syms.trustMeType.tsym,
   841                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   842             } else {
   843                 log.error(tree,
   844                             "varargs.invalid.trustme.anno",
   845                             syms.trustMeType.tsym,
   846                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   847             }
   848         } else if (hasTrustMeAnno && varargElemType != null &&
   849                             types.isReifiable(varargElemType)) {
   850             warnUnsafeVararg(tree,
   851                             "varargs.redundant.trustme.anno",
   852                             syms.trustMeType.tsym,
   853                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   854         }
   855         else if (!hasTrustMeAnno && varargElemType != null &&
   856                 !types.isReifiable(varargElemType)) {
   857             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   858         }
   859     }
   860     //where
   861         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   862             return (s.flags() & VARARGS) != 0 &&
   863                 (s.isConstructor() ||
   864                     (s.flags() & (STATIC | FINAL)) != 0);
   865         }
   867     Type checkMethod(final Type mtype,
   868             final Symbol sym,
   869             final Env<AttrContext> env,
   870             final List<JCExpression> argtrees,
   871             final List<Type> argtypes,
   872             final boolean useVarargs,
   873             InferenceContext inferenceContext) {
   874         // System.out.println("call   : " + env.tree);
   875         // System.out.println("method : " + owntype);
   876         // System.out.println("actuals: " + argtypes);
   877         if (inferenceContext.free(mtype)) {
   878             inferenceContext.addFreeTypeListener(List.of(mtype), new FreeTypeListener() {
   879                 public void typesInferred(InferenceContext inferenceContext) {
   880                     checkMethod(inferenceContext.asInstType(mtype), sym, env, argtrees, argtypes, useVarargs, inferenceContext);
   881                 }
   882             });
   883             return mtype;
   884         }
   885         Type owntype = mtype;
   886         List<Type> formals = owntype.getParameterTypes();
   887         List<Type> nonInferred = sym.type.getParameterTypes();
   888         if (nonInferred.length() != formals.length()) nonInferred = formals;
   889         Type last = useVarargs ? formals.last() : null;
   890         if (sym.name == names.init && sym.owner == syms.enumSym) {
   891             formals = formals.tail.tail;
   892             nonInferred = nonInferred.tail.tail;
   893         }
   894         List<JCExpression> args = argtrees;
   895         if (args != null) {
   896             //this is null when type-checking a method reference
   897             while (formals.head != last) {
   898                 JCTree arg = args.head;
   899                 Warner warn = convertWarner(arg.pos(), arg.type, nonInferred.head);
   900                 assertConvertible(arg, arg.type, formals.head, warn);
   901                 args = args.tail;
   902                 formals = formals.tail;
   903                 nonInferred = nonInferred.tail;
   904             }
   905             if (useVarargs) {
   906                 Type varArg = types.elemtype(last);
   907                 while (args.tail != null) {
   908                     JCTree arg = args.head;
   909                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   910                     assertConvertible(arg, arg.type, varArg, warn);
   911                     args = args.tail;
   912                 }
   913             } else if ((sym.flags() & (VARARGS | SIGNATURE_POLYMORPHIC)) == VARARGS &&
   914                     allowVarargs) {
   915                 // non-varargs call to varargs method
   916                 Type varParam = owntype.getParameterTypes().last();
   917                 Type lastArg = argtypes.last();
   918                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   919                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   920                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   921                                 types.elemtype(varParam), varParam);
   922             }
   923         }
   924         if (useVarargs) {
   925             Type argtype = owntype.getParameterTypes().last();
   926             if (!types.isReifiable(argtype) &&
   927                 (!allowSimplifiedVarargs ||
   928                  sym.attribute(syms.trustMeType.tsym) == null ||
   929                  !isTrustMeAllowedOnMethod(sym))) {
   930                 warnUnchecked(env.tree.pos(),
   931                                   "unchecked.generic.array.creation",
   932                                   argtype);
   933             }
   934             if ((sym.baseSymbol().flags() & SIGNATURE_POLYMORPHIC) == 0) {
   935                 TreeInfo.setVarargsElement(env.tree, types.elemtype(argtype));
   936             }
   937          }
   938          PolyKind pkind = (sym.type.hasTag(FORALL) &&
   939                  sym.type.getReturnType().containsAny(((ForAll)sym.type).tvars)) ?
   940                  PolyKind.POLY : PolyKind.STANDALONE;
   941          TreeInfo.setPolyKind(env.tree, pkind);
   942          return owntype;
   943     }
   944     //where
   945     private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   946         if (types.isConvertible(actual, formal, warn))
   947             return;
   949         if (formal.isCompound()
   950             && types.isSubtype(actual, types.supertype(formal))
   951             && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   952             return;
   953     }
   955     /**
   956      * Check that type 't' is a valid instantiation of a generic class
   957      * (see JLS 4.5)
   958      *
   959      * @param t class type to be checked
   960      * @return true if 't' is well-formed
   961      */
   962     public boolean checkValidGenericType(Type t) {
   963         return firstIncompatibleTypeArg(t) == null;
   964     }
   965     //WHERE
   966         private Type firstIncompatibleTypeArg(Type type) {
   967             List<Type> formals = type.tsym.type.allparams();
   968             List<Type> actuals = type.allparams();
   969             List<Type> args = type.getTypeArguments();
   970             List<Type> forms = type.tsym.type.getTypeArguments();
   971             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   973             // For matching pairs of actual argument types `a' and
   974             // formal type parameters with declared bound `b' ...
   975             while (args.nonEmpty() && forms.nonEmpty()) {
   976                 // exact type arguments needs to know their
   977                 // bounds (for upper and lower bound
   978                 // calculations).  So we create new bounds where
   979                 // type-parameters are replaced with actuals argument types.
   980                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   981                 args = args.tail;
   982                 forms = forms.tail;
   983             }
   985             args = type.getTypeArguments();
   986             List<Type> tvars_cap = types.substBounds(formals,
   987                                       formals,
   988                                       types.capture(type).allparams());
   989             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   990                 // Let the actual arguments know their bound
   991                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   992                 args = args.tail;
   993                 tvars_cap = tvars_cap.tail;
   994             }
   996             args = type.getTypeArguments();
   997             List<Type> bounds = bounds_buf.toList();
   999             while (args.nonEmpty() && bounds.nonEmpty()) {
  1000                 Type actual = args.head;
  1001                 if (!isTypeArgErroneous(actual) &&
  1002                         !bounds.head.isErroneous() &&
  1003                         !checkExtends(actual, bounds.head)) {
  1004                     return args.head;
  1006                 args = args.tail;
  1007                 bounds = bounds.tail;
  1010             args = type.getTypeArguments();
  1011             bounds = bounds_buf.toList();
  1013             for (Type arg : types.capture(type).getTypeArguments()) {
  1014                 if (arg.hasTag(TYPEVAR) &&
  1015                         arg.getUpperBound().isErroneous() &&
  1016                         !bounds.head.isErroneous() &&
  1017                         !isTypeArgErroneous(args.head)) {
  1018                     return args.head;
  1020                 bounds = bounds.tail;
  1021                 args = args.tail;
  1024             return null;
  1026         //where
  1027         boolean isTypeArgErroneous(Type t) {
  1028             return isTypeArgErroneous.visit(t);
  1031         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1032             public Boolean visitType(Type t, Void s) {
  1033                 return t.isErroneous();
  1035             @Override
  1036             public Boolean visitTypeVar(TypeVar t, Void s) {
  1037                 return visit(t.getUpperBound());
  1039             @Override
  1040             public Boolean visitCapturedType(CapturedType t, Void s) {
  1041                 return visit(t.getUpperBound()) ||
  1042                         visit(t.getLowerBound());
  1044             @Override
  1045             public Boolean visitWildcardType(WildcardType t, Void s) {
  1046                 return visit(t.type);
  1048         };
  1050     /** Check that given modifiers are legal for given symbol and
  1051      *  return modifiers together with any implicit modifiers for that symbol.
  1052      *  Warning: we can't use flags() here since this method
  1053      *  is called during class enter, when flags() would cause a premature
  1054      *  completion.
  1055      *  @param pos           Position to be used for error reporting.
  1056      *  @param flags         The set of modifiers given in a definition.
  1057      *  @param sym           The defined symbol.
  1058      */
  1059     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1060         long mask;
  1061         long implicit = 0;
  1063         switch (sym.kind) {
  1064         case VAR:
  1065             if (sym.owner.kind != TYP)
  1066                 mask = LocalVarFlags;
  1067             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1068                 mask = implicit = InterfaceVarFlags;
  1069             else
  1070                 mask = VarFlags;
  1071             break;
  1072         case MTH:
  1073             if (sym.name == names.init) {
  1074                 if ((sym.owner.flags_field & ENUM) != 0) {
  1075                     // enum constructors cannot be declared public or
  1076                     // protected and must be implicitly or explicitly
  1077                     // private
  1078                     implicit = PRIVATE;
  1079                     mask = PRIVATE;
  1080                 } else
  1081                     mask = ConstructorFlags;
  1082             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1083                 if ((sym.owner.flags_field & ANNOTATION) != 0) {
  1084                     mask = AnnotationTypeElementMask;
  1085                     implicit = PUBLIC | ABSTRACT;
  1086                 } else if ((flags & (DEFAULT | STATIC)) != 0) {
  1087                     mask = InterfaceMethodMask;
  1088                     implicit = PUBLIC;
  1089                     if ((flags & DEFAULT) != 0) {
  1090                         implicit |= ABSTRACT;
  1092                 } else {
  1093                     mask = implicit = InterfaceMethodFlags;
  1095             } else {
  1096                 mask = MethodFlags;
  1098             // Imply STRICTFP if owner has STRICTFP set.
  1099             if (((flags|implicit) & Flags.ABSTRACT) == 0 ||
  1100                 ((flags) & Flags.DEFAULT) != 0)
  1101                 implicit |= sym.owner.flags_field & STRICTFP;
  1102             break;
  1103         case TYP:
  1104             if (sym.isLocal()) {
  1105                 mask = LocalClassFlags;
  1106                 if (sym.name.isEmpty()) { // Anonymous class
  1107                     // Anonymous classes in static methods are themselves static;
  1108                     // that's why we admit STATIC here.
  1109                     mask |= STATIC;
  1110                     // JLS: Anonymous classes are final.
  1111                     implicit |= FINAL;
  1113                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1114                     (flags & ENUM) != 0)
  1115                     log.error(pos, "enums.must.be.static");
  1116             } else if (sym.owner.kind == TYP) {
  1117                 mask = MemberClassFlags;
  1118                 if (sym.owner.owner.kind == PCK ||
  1119                     (sym.owner.flags_field & STATIC) != 0)
  1120                     mask |= STATIC;
  1121                 else if ((flags & ENUM) != 0)
  1122                     log.error(pos, "enums.must.be.static");
  1123                 // Nested interfaces and enums are always STATIC (Spec ???)
  1124                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1125             } else {
  1126                 mask = ClassFlags;
  1128             // Interfaces are always ABSTRACT
  1129             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1131             if ((flags & ENUM) != 0) {
  1132                 // enums can't be declared abstract or final
  1133                 mask &= ~(ABSTRACT | FINAL);
  1134                 implicit |= implicitEnumFinalFlag(tree);
  1136             // Imply STRICTFP if owner has STRICTFP set.
  1137             implicit |= sym.owner.flags_field & STRICTFP;
  1138             break;
  1139         default:
  1140             throw new AssertionError();
  1142         long illegal = flags & ExtendedStandardFlags & ~mask;
  1143         if (illegal != 0) {
  1144             if ((illegal & INTERFACE) != 0) {
  1145                 log.error(pos, "intf.not.allowed.here");
  1146                 mask |= INTERFACE;
  1148             else {
  1149                 log.error(pos,
  1150                           "mod.not.allowed.here", asFlagSet(illegal));
  1153         else if ((sym.kind == TYP ||
  1154                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1155                   // in the presence of inner classes. Should it be deleted here?
  1156                   checkDisjoint(pos, flags,
  1157                                 ABSTRACT,
  1158                                 PRIVATE | STATIC | DEFAULT))
  1159                  &&
  1160                  checkDisjoint(pos, flags,
  1161                                 STATIC,
  1162                                 DEFAULT)
  1163                  &&
  1164                  checkDisjoint(pos, flags,
  1165                                ABSTRACT | INTERFACE,
  1166                                FINAL | NATIVE | SYNCHRONIZED)
  1167                  &&
  1168                  checkDisjoint(pos, flags,
  1169                                PUBLIC,
  1170                                PRIVATE | PROTECTED)
  1171                  &&
  1172                  checkDisjoint(pos, flags,
  1173                                PRIVATE,
  1174                                PUBLIC | PROTECTED)
  1175                  &&
  1176                  checkDisjoint(pos, flags,
  1177                                FINAL,
  1178                                VOLATILE)
  1179                  &&
  1180                  (sym.kind == TYP ||
  1181                   checkDisjoint(pos, flags,
  1182                                 ABSTRACT | NATIVE,
  1183                                 STRICTFP))) {
  1184             // skip
  1186         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1190     /** Determine if this enum should be implicitly final.
  1192      *  If the enum has no specialized enum contants, it is final.
  1194      *  If the enum does have specialized enum contants, it is
  1195      *  <i>not</i> final.
  1196      */
  1197     private long implicitEnumFinalFlag(JCTree tree) {
  1198         if (!tree.hasTag(CLASSDEF)) return 0;
  1199         class SpecialTreeVisitor extends JCTree.Visitor {
  1200             boolean specialized;
  1201             SpecialTreeVisitor() {
  1202                 this.specialized = false;
  1203             };
  1205             @Override
  1206             public void visitTree(JCTree tree) { /* no-op */ }
  1208             @Override
  1209             public void visitVarDef(JCVariableDecl tree) {
  1210                 if ((tree.mods.flags & ENUM) != 0) {
  1211                     if (tree.init instanceof JCNewClass &&
  1212                         ((JCNewClass) tree.init).def != null) {
  1213                         specialized = true;
  1219         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1220         JCClassDecl cdef = (JCClassDecl) tree;
  1221         for (JCTree defs: cdef.defs) {
  1222             defs.accept(sts);
  1223             if (sts.specialized) return 0;
  1225         return FINAL;
  1228 /* *************************************************************************
  1229  * Type Validation
  1230  **************************************************************************/
  1232     /** Validate a type expression. That is,
  1233      *  check that all type arguments of a parametric type are within
  1234      *  their bounds. This must be done in a second phase after type attribution
  1235      *  since a class might have a subclass as type parameter bound. E.g:
  1237      *  <pre>{@code
  1238      *  class B<A extends C> { ... }
  1239      *  class C extends B<C> { ... }
  1240      *  }</pre>
  1242      *  and we can't make sure that the bound is already attributed because
  1243      *  of possible cycles.
  1245      * Visitor method: Validate a type expression, if it is not null, catching
  1246      *  and reporting any completion failures.
  1247      */
  1248     void validate(JCTree tree, Env<AttrContext> env) {
  1249         validate(tree, env, true);
  1251     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1252         new Validator(env).validateTree(tree, checkRaw, true);
  1255     /** Visitor method: Validate a list of type expressions.
  1256      */
  1257     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1258         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1259             validate(l.head, env);
  1262     /** A visitor class for type validation.
  1263      */
  1264     class Validator extends JCTree.Visitor {
  1266         boolean checkRaw;
  1267         boolean isOuter;
  1268         Env<AttrContext> env;
  1270         Validator(Env<AttrContext> env) {
  1271             this.env = env;
  1274         @Override
  1275         public void visitTypeArray(JCArrayTypeTree tree) {
  1276             validateTree(tree.elemtype, checkRaw, isOuter);
  1279         @Override
  1280         public void visitTypeApply(JCTypeApply tree) {
  1281             if (tree.type.hasTag(CLASS)) {
  1282                 List<JCExpression> args = tree.arguments;
  1283                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1285                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1286                 if (incompatibleArg != null) {
  1287                     for (JCTree arg : tree.arguments) {
  1288                         if (arg.type == incompatibleArg) {
  1289                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1291                         forms = forms.tail;
  1295                 forms = tree.type.tsym.type.getTypeArguments();
  1297                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1299                 // For matching pairs of actual argument types `a' and
  1300                 // formal type parameters with declared bound `b' ...
  1301                 while (args.nonEmpty() && forms.nonEmpty()) {
  1302                     validateTree(args.head,
  1303                             !(isOuter && is_java_lang_Class),
  1304                             false);
  1305                     args = args.tail;
  1306                     forms = forms.tail;
  1309                 // Check that this type is either fully parameterized, or
  1310                 // not parameterized at all.
  1311                 if (tree.type.getEnclosingType().isRaw())
  1312                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1313                 if (tree.clazz.hasTag(SELECT))
  1314                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1318         @Override
  1319         public void visitTypeParameter(JCTypeParameter tree) {
  1320             validateTrees(tree.bounds, true, isOuter);
  1321             checkClassBounds(tree.pos(), tree.type);
  1324         @Override
  1325         public void visitWildcard(JCWildcard tree) {
  1326             if (tree.inner != null)
  1327                 validateTree(tree.inner, true, isOuter);
  1330         @Override
  1331         public void visitSelect(JCFieldAccess tree) {
  1332             if (tree.type.hasTag(CLASS)) {
  1333                 visitSelectInternal(tree);
  1335                 // Check that this type is either fully parameterized, or
  1336                 // not parameterized at all.
  1337                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1338                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1342         public void visitSelectInternal(JCFieldAccess tree) {
  1343             if (tree.type.tsym.isStatic() &&
  1344                 tree.selected.type.isParameterized()) {
  1345                 // The enclosing type is not a class, so we are
  1346                 // looking at a static member type.  However, the
  1347                 // qualifying expression is parameterized.
  1348                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1349             } else {
  1350                 // otherwise validate the rest of the expression
  1351                 tree.selected.accept(this);
  1355         @Override
  1356         public void visitAnnotatedType(JCAnnotatedType tree) {
  1357             tree.underlyingType.accept(this);
  1360         /** Default visitor method: do nothing.
  1361          */
  1362         @Override
  1363         public void visitTree(JCTree tree) {
  1366         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1367             if (tree != null) {
  1368                 boolean prevCheckRaw = this.checkRaw;
  1369                 this.checkRaw = checkRaw;
  1370                 this.isOuter = isOuter;
  1372                 try {
  1373                     tree.accept(this);
  1374                     if (checkRaw)
  1375                         checkRaw(tree, env);
  1376                 } catch (CompletionFailure ex) {
  1377                     completionError(tree.pos(), ex);
  1378                 } finally {
  1379                     this.checkRaw = prevCheckRaw;
  1384         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1385             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1386                 validateTree(l.head, checkRaw, isOuter);
  1390     void checkRaw(JCTree tree, Env<AttrContext> env) {
  1391         if (lint.isEnabled(LintCategory.RAW) &&
  1392             tree.type.hasTag(CLASS) &&
  1393             !TreeInfo.isDiamond(tree) &&
  1394             !withinAnonConstr(env) &&
  1395             tree.type.isRaw()) {
  1396             log.warning(LintCategory.RAW,
  1397                     tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1400     //where
  1401         private boolean withinAnonConstr(Env<AttrContext> env) {
  1402             return env.enclClass.name.isEmpty() &&
  1403                     env.enclMethod != null && env.enclMethod.name == names.init;
  1406 /* *************************************************************************
  1407  * Exception checking
  1408  **************************************************************************/
  1410     /* The following methods treat classes as sets that contain
  1411      * the class itself and all their subclasses
  1412      */
  1414     /** Is given type a subtype of some of the types in given list?
  1415      */
  1416     boolean subset(Type t, List<Type> ts) {
  1417         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1418             if (types.isSubtype(t, l.head)) return true;
  1419         return false;
  1422     /** Is given type a subtype or supertype of
  1423      *  some of the types in given list?
  1424      */
  1425     boolean intersects(Type t, List<Type> ts) {
  1426         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1427             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1428         return false;
  1431     /** Add type set to given type list, unless it is a subclass of some class
  1432      *  in the list.
  1433      */
  1434     List<Type> incl(Type t, List<Type> ts) {
  1435         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1438     /** Remove type set from type set list.
  1439      */
  1440     List<Type> excl(Type t, List<Type> ts) {
  1441         if (ts.isEmpty()) {
  1442             return ts;
  1443         } else {
  1444             List<Type> ts1 = excl(t, ts.tail);
  1445             if (types.isSubtype(ts.head, t)) return ts1;
  1446             else if (ts1 == ts.tail) return ts;
  1447             else return ts1.prepend(ts.head);
  1451     /** Form the union of two type set lists.
  1452      */
  1453     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1454         List<Type> ts = ts1;
  1455         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1456             ts = incl(l.head, ts);
  1457         return ts;
  1460     /** Form the difference of two type lists.
  1461      */
  1462     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1463         List<Type> ts = ts1;
  1464         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1465             ts = excl(l.head, ts);
  1466         return ts;
  1469     /** Form the intersection of two type lists.
  1470      */
  1471     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1472         List<Type> ts = List.nil();
  1473         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1474             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1475         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1476             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1477         return ts;
  1480     /** Is exc an exception symbol that need not be declared?
  1481      */
  1482     boolean isUnchecked(ClassSymbol exc) {
  1483         return
  1484             exc.kind == ERR ||
  1485             exc.isSubClass(syms.errorType.tsym, types) ||
  1486             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1489     /** Is exc an exception type that need not be declared?
  1490      */
  1491     boolean isUnchecked(Type exc) {
  1492         return
  1493             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1494             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1495             exc.hasTag(BOT);
  1498     /** Same, but handling completion failures.
  1499      */
  1500     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1501         try {
  1502             return isUnchecked(exc);
  1503         } catch (CompletionFailure ex) {
  1504             completionError(pos, ex);
  1505             return true;
  1509     /** Is exc handled by given exception list?
  1510      */
  1511     boolean isHandled(Type exc, List<Type> handled) {
  1512         return isUnchecked(exc) || subset(exc, handled);
  1515     /** Return all exceptions in thrown list that are not in handled list.
  1516      *  @param thrown     The list of thrown exceptions.
  1517      *  @param handled    The list of handled exceptions.
  1518      */
  1519     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1520         List<Type> unhandled = List.nil();
  1521         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1522             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1523         return unhandled;
  1526 /* *************************************************************************
  1527  * Overriding/Implementation checking
  1528  **************************************************************************/
  1530     /** The level of access protection given by a flag set,
  1531      *  where PRIVATE is highest and PUBLIC is lowest.
  1532      */
  1533     static int protection(long flags) {
  1534         switch ((short)(flags & AccessFlags)) {
  1535         case PRIVATE: return 3;
  1536         case PROTECTED: return 1;
  1537         default:
  1538         case PUBLIC: return 0;
  1539         case 0: return 2;
  1543     /** A customized "cannot override" error message.
  1544      *  @param m      The overriding method.
  1545      *  @param other  The overridden method.
  1546      *  @return       An internationalized string.
  1547      */
  1548     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1549         String key;
  1550         if ((other.owner.flags() & INTERFACE) == 0)
  1551             key = "cant.override";
  1552         else if ((m.owner.flags() & INTERFACE) == 0)
  1553             key = "cant.implement";
  1554         else
  1555             key = "clashes.with";
  1556         return diags.fragment(key, m, m.location(), other, other.location());
  1559     /** A customized "override" warning message.
  1560      *  @param m      The overriding method.
  1561      *  @param other  The overridden method.
  1562      *  @return       An internationalized string.
  1563      */
  1564     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1565         String key;
  1566         if ((other.owner.flags() & INTERFACE) == 0)
  1567             key = "unchecked.override";
  1568         else if ((m.owner.flags() & INTERFACE) == 0)
  1569             key = "unchecked.implement";
  1570         else
  1571             key = "unchecked.clash.with";
  1572         return diags.fragment(key, m, m.location(), other, other.location());
  1575     /** A customized "override" warning message.
  1576      *  @param m      The overriding method.
  1577      *  @param other  The overridden method.
  1578      *  @return       An internationalized string.
  1579      */
  1580     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1581         String key;
  1582         if ((other.owner.flags() & INTERFACE) == 0)
  1583             key = "varargs.override";
  1584         else  if ((m.owner.flags() & INTERFACE) == 0)
  1585             key = "varargs.implement";
  1586         else
  1587             key = "varargs.clash.with";
  1588         return diags.fragment(key, m, m.location(), other, other.location());
  1591     /** Check that this method conforms with overridden method 'other'.
  1592      *  where `origin' is the class where checking started.
  1593      *  Complications:
  1594      *  (1) Do not check overriding of synthetic methods
  1595      *      (reason: they might be final).
  1596      *      todo: check whether this is still necessary.
  1597      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1598      *      than the method it implements. Augment the proxy methods with the
  1599      *      undeclared exceptions in this case.
  1600      *  (3) When generics are enabled, admit the case where an interface proxy
  1601      *      has a result type
  1602      *      extended by the result type of the method it implements.
  1603      *      Change the proxies result type to the smaller type in this case.
  1605      *  @param tree         The tree from which positions
  1606      *                      are extracted for errors.
  1607      *  @param m            The overriding method.
  1608      *  @param other        The overridden method.
  1609      *  @param origin       The class of which the overriding method
  1610      *                      is a member.
  1611      */
  1612     void checkOverride(JCTree tree,
  1613                        MethodSymbol m,
  1614                        MethodSymbol other,
  1615                        ClassSymbol origin) {
  1616         // Don't check overriding of synthetic methods or by bridge methods.
  1617         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1618             return;
  1621         // Error if static method overrides instance method (JLS 8.4.6.2).
  1622         if ((m.flags() & STATIC) != 0 &&
  1623                    (other.flags() & STATIC) == 0) {
  1624             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1625                       cannotOverride(m, other));
  1626             m.flags_field |= BAD_OVERRIDE;
  1627             return;
  1630         // Error if instance method overrides static or final
  1631         // method (JLS 8.4.6.1).
  1632         if ((other.flags() & FINAL) != 0 ||
  1633                  (m.flags() & STATIC) == 0 &&
  1634                  (other.flags() & STATIC) != 0) {
  1635             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1636                       cannotOverride(m, other),
  1637                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1638             m.flags_field |= BAD_OVERRIDE;
  1639             return;
  1642         if ((m.owner.flags() & ANNOTATION) != 0) {
  1643             // handled in validateAnnotationMethod
  1644             return;
  1647         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1648         if ((origin.flags() & INTERFACE) == 0 &&
  1649                  protection(m.flags()) > protection(other.flags())) {
  1650             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1651                       cannotOverride(m, other),
  1652                       other.flags() == 0 ?
  1653                           "package" :
  1654                           asFlagSet(other.flags() & AccessFlags));
  1655             m.flags_field |= BAD_OVERRIDE;
  1656             return;
  1659         Type mt = types.memberType(origin.type, m);
  1660         Type ot = types.memberType(origin.type, other);
  1661         // Error if overriding result type is different
  1662         // (or, in the case of generics mode, not a subtype) of
  1663         // overridden result type. We have to rename any type parameters
  1664         // before comparing types.
  1665         List<Type> mtvars = mt.getTypeArguments();
  1666         List<Type> otvars = ot.getTypeArguments();
  1667         Type mtres = mt.getReturnType();
  1668         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1670         overrideWarner.clear();
  1671         boolean resultTypesOK =
  1672             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1673         if (!resultTypesOK) {
  1674             if (!allowCovariantReturns &&
  1675                 m.owner != origin &&
  1676                 m.owner.isSubClass(other.owner, types)) {
  1677                 // allow limited interoperability with covariant returns
  1678             } else {
  1679                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1680                           "override.incompatible.ret",
  1681                           cannotOverride(m, other),
  1682                           mtres, otres);
  1683                 m.flags_field |= BAD_OVERRIDE;
  1684                 return;
  1686         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1687             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1688                     "override.unchecked.ret",
  1689                     uncheckedOverrides(m, other),
  1690                     mtres, otres);
  1693         // Error if overriding method throws an exception not reported
  1694         // by overridden method.
  1695         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1696         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1697         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1698         if (unhandledErased.nonEmpty()) {
  1699             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1700                       "override.meth.doesnt.throw",
  1701                       cannotOverride(m, other),
  1702                       unhandledUnerased.head);
  1703             m.flags_field |= BAD_OVERRIDE;
  1704             return;
  1706         else if (unhandledUnerased.nonEmpty()) {
  1707             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1708                           "override.unchecked.thrown",
  1709                          cannotOverride(m, other),
  1710                          unhandledUnerased.head);
  1711             return;
  1714         // Optional warning if varargs don't agree
  1715         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1716             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1717             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1718                         ((m.flags() & Flags.VARARGS) != 0)
  1719                         ? "override.varargs.missing"
  1720                         : "override.varargs.extra",
  1721                         varargsOverrides(m, other));
  1724         // Warn if instance method overrides bridge method (compiler spec ??)
  1725         if ((other.flags() & BRIDGE) != 0) {
  1726             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1727                         uncheckedOverrides(m, other));
  1730         // Warn if a deprecated method overridden by a non-deprecated one.
  1731         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1732             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1735     // where
  1736         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1737             // If the method, m, is defined in an interface, then ignore the issue if the method
  1738             // is only inherited via a supertype and also implemented in the supertype,
  1739             // because in that case, we will rediscover the issue when examining the method
  1740             // in the supertype.
  1741             // If the method, m, is not defined in an interface, then the only time we need to
  1742             // address the issue is when the method is the supertype implemementation: any other
  1743             // case, we will have dealt with when examining the supertype classes
  1744             ClassSymbol mc = m.enclClass();
  1745             Type st = types.supertype(origin.type);
  1746             if (!st.hasTag(CLASS))
  1747                 return true;
  1748             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1750             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1751                 List<Type> intfs = types.interfaces(origin.type);
  1752                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1754             else
  1755                 return (stimpl != m);
  1759     // used to check if there were any unchecked conversions
  1760     Warner overrideWarner = new Warner();
  1762     /** Check that a class does not inherit two concrete methods
  1763      *  with the same signature.
  1764      *  @param pos          Position to be used for error reporting.
  1765      *  @param site         The class type to be checked.
  1766      */
  1767     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1768         Type sup = types.supertype(site);
  1769         if (!sup.hasTag(CLASS)) return;
  1771         for (Type t1 = sup;
  1772              t1.hasTag(CLASS) && t1.tsym.type.isParameterized();
  1773              t1 = types.supertype(t1)) {
  1774             for (Scope.Entry e1 = t1.tsym.members().elems;
  1775                  e1 != null;
  1776                  e1 = e1.sibling) {
  1777                 Symbol s1 = e1.sym;
  1778                 if (s1.kind != MTH ||
  1779                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1780                     !s1.isInheritedIn(site.tsym, types) ||
  1781                     ((MethodSymbol)s1).implementation(site.tsym,
  1782                                                       types,
  1783                                                       true) != s1)
  1784                     continue;
  1785                 Type st1 = types.memberType(t1, s1);
  1786                 int s1ArgsLength = st1.getParameterTypes().length();
  1787                 if (st1 == s1.type) continue;
  1789                 for (Type t2 = sup;
  1790                      t2.hasTag(CLASS);
  1791                      t2 = types.supertype(t2)) {
  1792                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1793                          e2.scope != null;
  1794                          e2 = e2.next()) {
  1795                         Symbol s2 = e2.sym;
  1796                         if (s2 == s1 ||
  1797                             s2.kind != MTH ||
  1798                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1799                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1800                             !s2.isInheritedIn(site.tsym, types) ||
  1801                             ((MethodSymbol)s2).implementation(site.tsym,
  1802                                                               types,
  1803                                                               true) != s2)
  1804                             continue;
  1805                         Type st2 = types.memberType(t2, s2);
  1806                         if (types.overrideEquivalent(st1, st2))
  1807                             log.error(pos, "concrete.inheritance.conflict",
  1808                                       s1, t1, s2, t2, sup);
  1815     /** Check that classes (or interfaces) do not each define an abstract
  1816      *  method with same name and arguments but incompatible return types.
  1817      *  @param pos          Position to be used for error reporting.
  1818      *  @param t1           The first argument type.
  1819      *  @param t2           The second argument type.
  1820      */
  1821     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1822                                             Type t1,
  1823                                             Type t2) {
  1824         return checkCompatibleAbstracts(pos, t1, t2,
  1825                                         types.makeCompoundType(t1, t2));
  1828     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1829                                             Type t1,
  1830                                             Type t2,
  1831                                             Type site) {
  1832         return firstIncompatibility(pos, t1, t2, site) == null;
  1835     /** Return the first method which is defined with same args
  1836      *  but different return types in two given interfaces, or null if none
  1837      *  exists.
  1838      *  @param t1     The first type.
  1839      *  @param t2     The second type.
  1840      *  @param site   The most derived type.
  1841      *  @returns symbol from t2 that conflicts with one in t1.
  1842      */
  1843     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1844         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1845         closure(t1, interfaces1);
  1846         Map<TypeSymbol,Type> interfaces2;
  1847         if (t1 == t2)
  1848             interfaces2 = interfaces1;
  1849         else
  1850             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1852         for (Type t3 : interfaces1.values()) {
  1853             for (Type t4 : interfaces2.values()) {
  1854                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1855                 if (s != null) return s;
  1858         return null;
  1861     /** Compute all the supertypes of t, indexed by type symbol. */
  1862     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1863         if (!t.hasTag(CLASS)) return;
  1864         if (typeMap.put(t.tsym, t) == null) {
  1865             closure(types.supertype(t), typeMap);
  1866             for (Type i : types.interfaces(t))
  1867                 closure(i, typeMap);
  1871     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1872     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1873         if (!t.hasTag(CLASS)) return;
  1874         if (typesSkip.get(t.tsym) != null) return;
  1875         if (typeMap.put(t.tsym, t) == null) {
  1876             closure(types.supertype(t), typesSkip, typeMap);
  1877             for (Type i : types.interfaces(t))
  1878                 closure(i, typesSkip, typeMap);
  1882     /** Return the first method in t2 that conflicts with a method from t1. */
  1883     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1884         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1885             Symbol s1 = e1.sym;
  1886             Type st1 = null;
  1887             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1888                     (s1.flags() & SYNTHETIC) != 0) continue;
  1889             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1890             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1891             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1892                 Symbol s2 = e2.sym;
  1893                 if (s1 == s2) continue;
  1894                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1895                         (s2.flags() & SYNTHETIC) != 0) continue;
  1896                 if (st1 == null) st1 = types.memberType(t1, s1);
  1897                 Type st2 = types.memberType(t2, s2);
  1898                 if (types.overrideEquivalent(st1, st2)) {
  1899                     List<Type> tvars1 = st1.getTypeArguments();
  1900                     List<Type> tvars2 = st2.getTypeArguments();
  1901                     Type rt1 = st1.getReturnType();
  1902                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1903                     boolean compat =
  1904                         types.isSameType(rt1, rt2) ||
  1905                         !rt1.isPrimitiveOrVoid() &&
  1906                         !rt2.isPrimitiveOrVoid() &&
  1907                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1908                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1909                          checkCommonOverriderIn(s1,s2,site);
  1910                     if (!compat) {
  1911                         log.error(pos, "types.incompatible.diff.ret",
  1912                             t1, t2, s2.name +
  1913                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1914                         return s2;
  1916                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1917                         !checkCommonOverriderIn(s1, s2, site)) {
  1918                     log.error(pos,
  1919                             "name.clash.same.erasure.no.override",
  1920                             s1, s1.location(),
  1921                             s2, s2.location());
  1922                     return s2;
  1926         return null;
  1928     //WHERE
  1929     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1930         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1931         Type st1 = types.memberType(site, s1);
  1932         Type st2 = types.memberType(site, s2);
  1933         closure(site, supertypes);
  1934         for (Type t : supertypes.values()) {
  1935             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1936                 Symbol s3 = e.sym;
  1937                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1938                 Type st3 = types.memberType(site,s3);
  1939                 if (types.overrideEquivalent(st3, st1) &&
  1940                         types.overrideEquivalent(st3, st2) &&
  1941                         types.returnTypeSubstitutable(st3, st1) &&
  1942                         types.returnTypeSubstitutable(st3, st2)) {
  1943                     return true;
  1947         return false;
  1950     /** Check that a given method conforms with any method it overrides.
  1951      *  @param tree         The tree from which positions are extracted
  1952      *                      for errors.
  1953      *  @param m            The overriding method.
  1954      */
  1955     void checkOverride(JCMethodDecl tree, MethodSymbol m) {
  1956         ClassSymbol origin = (ClassSymbol)m.owner;
  1957         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1958             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1959                 log.error(tree.pos(), "enum.no.finalize");
  1960                 return;
  1962         for (Type t = origin.type; t.hasTag(CLASS);
  1963              t = types.supertype(t)) {
  1964             if (t != origin.type) {
  1965                 checkOverride(tree, t, origin, m);
  1967             for (Type t2 : types.interfaces(t)) {
  1968                 checkOverride(tree, t2, origin, m);
  1972         if (m.attribute(syms.overrideType.tsym) != null && !isOverrider(m)) {
  1973             DiagnosticPosition pos = tree.pos();
  1974             for (JCAnnotation a : tree.getModifiers().annotations) {
  1975                 if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1976                     pos = a.pos();
  1977                     break;
  1980             log.error(pos, "method.does.not.override.superclass");
  1984     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1985         TypeSymbol c = site.tsym;
  1986         Scope.Entry e = c.members().lookup(m.name);
  1987         while (e.scope != null) {
  1988             if (m.overrides(e.sym, origin, types, false)) {
  1989                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1990                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1993             e = e.next();
  1997     private Filter<Symbol> equalsHasCodeFilter = new Filter<Symbol>() {
  1998         public boolean accepts(Symbol s) {
  1999             return MethodSymbol.implementation_filter.accepts(s) &&
  2000                     (s.flags() & BAD_OVERRIDE) == 0;
  2003     };
  2005     public void checkClassOverrideEqualsAndHashIfNeeded(DiagnosticPosition pos,
  2006             ClassSymbol someClass) {
  2007         /* At present, annotations cannot possibly have a method that is override
  2008          * equivalent with Object.equals(Object) but in any case the condition is
  2009          * fine for completeness.
  2010          */
  2011         if (someClass == (ClassSymbol)syms.objectType.tsym ||
  2012             someClass.isInterface() || someClass.isEnum() ||
  2013             (someClass.flags() & ANNOTATION) != 0 ||
  2014             (someClass.flags() & ABSTRACT) != 0) return;
  2015         //anonymous inner classes implementing interfaces need especial treatment
  2016         if (someClass.isAnonymous()) {
  2017             List<Type> interfaces =  types.interfaces(someClass.type);
  2018             if (interfaces != null && !interfaces.isEmpty() &&
  2019                 interfaces.head.tsym == syms.comparatorType.tsym) return;
  2021         checkClassOverrideEqualsAndHash(pos, someClass);
  2024     private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
  2025             ClassSymbol someClass) {
  2026         if (lint.isEnabled(LintCategory.OVERRIDES)) {
  2027             MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
  2028                     .tsym.members().lookup(names.equals).sym;
  2029             MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
  2030                     .tsym.members().lookup(names.hashCode).sym;
  2031             boolean overridesEquals = types.implementation(equalsAtObject,
  2032                 someClass, false, equalsHasCodeFilter).owner == someClass;
  2033             boolean overridesHashCode = types.implementation(hashCodeAtObject,
  2034                 someClass, false, equalsHasCodeFilter) != hashCodeAtObject;
  2036             if (overridesEquals && !overridesHashCode) {
  2037                 log.warning(LintCategory.OVERRIDES, pos,
  2038                         "override.equals.but.not.hashcode", someClass);
  2043     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  2044         ClashFilter cf = new ClashFilter(origin.type);
  2045         return (cf.accepts(s1) &&
  2046                 cf.accepts(s2) &&
  2047                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  2051     /** Check that all abstract members of given class have definitions.
  2052      *  @param pos          Position to be used for error reporting.
  2053      *  @param c            The class.
  2054      */
  2055     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  2056         try {
  2057             MethodSymbol undef = firstUndef(c, c);
  2058             if (undef != null) {
  2059                 if ((c.flags() & ENUM) != 0 &&
  2060                     types.supertype(c.type).tsym == syms.enumSym &&
  2061                     (c.flags() & FINAL) == 0) {
  2062                     // add the ABSTRACT flag to an enum
  2063                     c.flags_field |= ABSTRACT;
  2064                 } else {
  2065                     MethodSymbol undef1 =
  2066                         new MethodSymbol(undef.flags(), undef.name,
  2067                                          types.memberType(c.type, undef), undef.owner);
  2068                     log.error(pos, "does.not.override.abstract",
  2069                               c, undef1, undef1.location());
  2072         } catch (CompletionFailure ex) {
  2073             completionError(pos, ex);
  2076 //where
  2077         /** Return first abstract member of class `c' that is not defined
  2078          *  in `impl', null if there is none.
  2079          */
  2080         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  2081             MethodSymbol undef = null;
  2082             // Do not bother to search in classes that are not abstract,
  2083             // since they cannot have abstract members.
  2084             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2085                 Scope s = c.members();
  2086                 for (Scope.Entry e = s.elems;
  2087                      undef == null && e != null;
  2088                      e = e.sibling) {
  2089                     if (e.sym.kind == MTH &&
  2090                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2091                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2092                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2093                         if (implmeth == null || implmeth == absmeth) {
  2094                             //look for default implementations
  2095                             if (allowDefaultMethods) {
  2096                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2097                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2098                                     implmeth = prov;
  2102                         if (implmeth == null || implmeth == absmeth) {
  2103                             undef = absmeth;
  2107                 if (undef == null) {
  2108                     Type st = types.supertype(c.type);
  2109                     if (st.hasTag(CLASS))
  2110                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2112                 for (List<Type> l = types.interfaces(c.type);
  2113                      undef == null && l.nonEmpty();
  2114                      l = l.tail) {
  2115                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2118             return undef;
  2121     void checkNonCyclicDecl(JCClassDecl tree) {
  2122         CycleChecker cc = new CycleChecker();
  2123         cc.scan(tree);
  2124         if (!cc.errorFound && !cc.partialCheck) {
  2125             tree.sym.flags_field |= ACYCLIC;
  2129     class CycleChecker extends TreeScanner {
  2131         List<Symbol> seenClasses = List.nil();
  2132         boolean errorFound = false;
  2133         boolean partialCheck = false;
  2135         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2136             if (sym != null && sym.kind == TYP) {
  2137                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2138                 if (classEnv != null) {
  2139                     DiagnosticSource prevSource = log.currentSource();
  2140                     try {
  2141                         log.useSource(classEnv.toplevel.sourcefile);
  2142                         scan(classEnv.tree);
  2144                     finally {
  2145                         log.useSource(prevSource.getFile());
  2147                 } else if (sym.kind == TYP) {
  2148                     checkClass(pos, sym, List.<JCTree>nil());
  2150             } else {
  2151                 //not completed yet
  2152                 partialCheck = true;
  2156         @Override
  2157         public void visitSelect(JCFieldAccess tree) {
  2158             super.visitSelect(tree);
  2159             checkSymbol(tree.pos(), tree.sym);
  2162         @Override
  2163         public void visitIdent(JCIdent tree) {
  2164             checkSymbol(tree.pos(), tree.sym);
  2167         @Override
  2168         public void visitTypeApply(JCTypeApply tree) {
  2169             scan(tree.clazz);
  2172         @Override
  2173         public void visitTypeArray(JCArrayTypeTree tree) {
  2174             scan(tree.elemtype);
  2177         @Override
  2178         public void visitClassDef(JCClassDecl tree) {
  2179             List<JCTree> supertypes = List.nil();
  2180             if (tree.getExtendsClause() != null) {
  2181                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2183             if (tree.getImplementsClause() != null) {
  2184                 for (JCTree intf : tree.getImplementsClause()) {
  2185                     supertypes = supertypes.prepend(intf);
  2188             checkClass(tree.pos(), tree.sym, supertypes);
  2191         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2192             if ((c.flags_field & ACYCLIC) != 0)
  2193                 return;
  2194             if (seenClasses.contains(c)) {
  2195                 errorFound = true;
  2196                 noteCyclic(pos, (ClassSymbol)c);
  2197             } else if (!c.type.isErroneous()) {
  2198                 try {
  2199                     seenClasses = seenClasses.prepend(c);
  2200                     if (c.type.hasTag(CLASS)) {
  2201                         if (supertypes.nonEmpty()) {
  2202                             scan(supertypes);
  2204                         else {
  2205                             ClassType ct = (ClassType)c.type;
  2206                             if (ct.supertype_field == null ||
  2207                                     ct.interfaces_field == null) {
  2208                                 //not completed yet
  2209                                 partialCheck = true;
  2210                                 return;
  2212                             checkSymbol(pos, ct.supertype_field.tsym);
  2213                             for (Type intf : ct.interfaces_field) {
  2214                                 checkSymbol(pos, intf.tsym);
  2217                         if (c.owner.kind == TYP) {
  2218                             checkSymbol(pos, c.owner);
  2221                 } finally {
  2222                     seenClasses = seenClasses.tail;
  2228     /** Check for cyclic references. Issue an error if the
  2229      *  symbol of the type referred to has a LOCKED flag set.
  2231      *  @param pos      Position to be used for error reporting.
  2232      *  @param t        The type referred to.
  2233      */
  2234     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2235         checkNonCyclicInternal(pos, t);
  2239     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2240         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2243     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2244         final TypeVar tv;
  2245         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2246             return;
  2247         if (seen.contains(t)) {
  2248             tv = (TypeVar)t.unannotatedType();
  2249             tv.bound = types.createErrorType(t);
  2250             log.error(pos, "cyclic.inheritance", t);
  2251         } else if (t.hasTag(TYPEVAR)) {
  2252             tv = (TypeVar)t.unannotatedType();
  2253             seen = seen.prepend(tv);
  2254             for (Type b : types.getBounds(tv))
  2255                 checkNonCyclic1(pos, b, seen);
  2256         } else if (t.hasTag(ARRAY)) {
  2257             final ArrayType at = (ArrayType)t.unannotatedType();
  2258             checkNonCyclic1(pos, at.elemtype, seen);
  2262     /** Check for cyclic references. Issue an error if the
  2263      *  symbol of the type referred to has a LOCKED flag set.
  2265      *  @param pos      Position to be used for error reporting.
  2266      *  @param t        The type referred to.
  2267      *  @returns        True if the check completed on all attributed classes
  2268      */
  2269     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2270         boolean complete = true; // was the check complete?
  2271         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2272         Symbol c = t.tsym;
  2273         if ((c.flags_field & ACYCLIC) != 0) return true;
  2275         if ((c.flags_field & LOCKED) != 0) {
  2276             noteCyclic(pos, (ClassSymbol)c);
  2277         } else if (!c.type.isErroneous()) {
  2278             try {
  2279                 c.flags_field |= LOCKED;
  2280                 if (c.type.hasTag(CLASS)) {
  2281                     ClassType clazz = (ClassType)c.type;
  2282                     if (clazz.interfaces_field != null)
  2283                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2284                             complete &= checkNonCyclicInternal(pos, l.head);
  2285                     if (clazz.supertype_field != null) {
  2286                         Type st = clazz.supertype_field;
  2287                         if (st != null && st.hasTag(CLASS))
  2288                             complete &= checkNonCyclicInternal(pos, st);
  2290                     if (c.owner.kind == TYP)
  2291                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2293             } finally {
  2294                 c.flags_field &= ~LOCKED;
  2297         if (complete)
  2298             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2299         if (complete) c.flags_field |= ACYCLIC;
  2300         return complete;
  2303     /** Note that we found an inheritance cycle. */
  2304     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2305         log.error(pos, "cyclic.inheritance", c);
  2306         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2307             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2308         Type st = types.supertype(c.type);
  2309         if (st.hasTag(CLASS))
  2310             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2311         c.type = types.createErrorType(c, c.type);
  2312         c.flags_field |= ACYCLIC;
  2315     /** Check that all methods which implement some
  2316      *  method conform to the method they implement.
  2317      *  @param tree         The class definition whose members are checked.
  2318      */
  2319     void checkImplementations(JCClassDecl tree) {
  2320         checkImplementations(tree, tree.sym, tree.sym);
  2322     //where
  2323         /** Check that all methods which implement some
  2324          *  method in `ic' conform to the method they implement.
  2325          */
  2326         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2327             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2328                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2329                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2330                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2331                         if (e.sym.kind == MTH &&
  2332                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2333                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2334                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2335                             if (implmeth != null && implmeth != absmeth &&
  2336                                 (implmeth.owner.flags() & INTERFACE) ==
  2337                                 (origin.flags() & INTERFACE)) {
  2338                                 // don't check if implmeth is in a class, yet
  2339                                 // origin is an interface. This case arises only
  2340                                 // if implmeth is declared in Object. The reason is
  2341                                 // that interfaces really don't inherit from
  2342                                 // Object it's just that the compiler represents
  2343                                 // things that way.
  2344                                 checkOverride(tree, implmeth, absmeth, origin);
  2352     /** Check that all abstract methods implemented by a class are
  2353      *  mutually compatible.
  2354      *  @param pos          Position to be used for error reporting.
  2355      *  @param c            The class whose interfaces are checked.
  2356      */
  2357     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2358         List<Type> supertypes = types.interfaces(c);
  2359         Type supertype = types.supertype(c);
  2360         if (supertype.hasTag(CLASS) &&
  2361             (supertype.tsym.flags() & ABSTRACT) != 0)
  2362             supertypes = supertypes.prepend(supertype);
  2363         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2364             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2365                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2366                 return;
  2367             for (List<Type> m = supertypes; m != l; m = m.tail)
  2368                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2369                     return;
  2371         checkCompatibleConcretes(pos, c);
  2374     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2375         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2376             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2377                 // VM allows methods and variables with differing types
  2378                 if (sym.kind == e.sym.kind &&
  2379                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2380                     sym != e.sym &&
  2381                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2382                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2383                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2384                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2385                     return;
  2391     /** Check that all non-override equivalent methods accessible from 'site'
  2392      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2394      *  @param pos  Position to be used for error reporting.
  2395      *  @param site The class whose methods are checked.
  2396      *  @param sym  The method symbol to be checked.
  2397      */
  2398     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2399          ClashFilter cf = new ClashFilter(site);
  2400         //for each method m1 that is overridden (directly or indirectly)
  2401         //by method 'sym' in 'site'...
  2402         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2403              if (!sym.overrides(m1, site.tsym, types, false)) {
  2404                  checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)m1);
  2405                  continue;
  2407              //...check each method m2 that is a member of 'site'
  2408              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2409                 if (m2 == m1) continue;
  2410                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2411                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2412                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2413                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2414                     sym.flags_field |= CLASH;
  2415                     String key = m1 == sym ?
  2416                             "name.clash.same.erasure.no.override" :
  2417                             "name.clash.same.erasure.no.override.1";
  2418                     log.error(pos,
  2419                             key,
  2420                             sym, sym.location(),
  2421                             m2, m2.location(),
  2422                             m1, m1.location());
  2423                     return;
  2431     /** Check that all static methods accessible from 'site' are
  2432      *  mutually compatible (JLS 8.4.8).
  2434      *  @param pos  Position to be used for error reporting.
  2435      *  @param site The class whose methods are checked.
  2436      *  @param sym  The method symbol to be checked.
  2437      */
  2438     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2439         ClashFilter cf = new ClashFilter(site);
  2440         //for each method m1 that is a member of 'site'...
  2441         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2442             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2443             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2444             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck)) {
  2445                 if (types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2446                     log.error(pos,
  2447                             "name.clash.same.erasure.no.hide",
  2448                             sym, sym.location(),
  2449                             s, s.location());
  2450                     return;
  2451                 } else {
  2452                     checkPotentiallyAmbiguousOverloads(pos, site, sym, (MethodSymbol)s);
  2458      //where
  2459      private class ClashFilter implements Filter<Symbol> {
  2461          Type site;
  2463          ClashFilter(Type site) {
  2464              this.site = site;
  2467          boolean shouldSkip(Symbol s) {
  2468              return (s.flags() & CLASH) != 0 &&
  2469                 s.owner == site.tsym;
  2472          public boolean accepts(Symbol s) {
  2473              return s.kind == MTH &&
  2474                      (s.flags() & SYNTHETIC) == 0 &&
  2475                      !shouldSkip(s) &&
  2476                      s.isInheritedIn(site.tsym, types) &&
  2477                      !s.isConstructor();
  2481     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2482         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2483         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2484             Assert.check(m.kind == MTH);
  2485             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2486             if (prov.size() > 1) {
  2487                 ListBuffer<Symbol> abstracts = new ListBuffer<>();
  2488                 ListBuffer<Symbol> defaults = new ListBuffer<>();
  2489                 for (MethodSymbol provSym : prov) {
  2490                     if ((provSym.flags() & DEFAULT) != 0) {
  2491                         defaults = defaults.append(provSym);
  2492                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2493                         abstracts = abstracts.append(provSym);
  2495                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2496                         //strong semantics - issue an error if two sibling interfaces
  2497                         //have two override-equivalent defaults - or if one is abstract
  2498                         //and the other is default
  2499                         String errKey;
  2500                         Symbol s1 = defaults.first();
  2501                         Symbol s2;
  2502                         if (defaults.size() > 1) {
  2503                             errKey = "types.incompatible.unrelated.defaults";
  2504                             s2 = defaults.toList().tail.head;
  2505                         } else {
  2506                             errKey = "types.incompatible.abstract.default";
  2507                             s2 = abstracts.first();
  2509                         log.error(pos, errKey,
  2510                                 Kinds.kindName(site.tsym), site,
  2511                                 m.name, types.memberType(site, m).getParameterTypes(),
  2512                                 s1.location(), s2.location());
  2513                         break;
  2520     //where
  2521      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2523          Type site;
  2525          DefaultMethodClashFilter(Type site) {
  2526              this.site = site;
  2529          public boolean accepts(Symbol s) {
  2530              return s.kind == MTH &&
  2531                      (s.flags() & DEFAULT) != 0 &&
  2532                      s.isInheritedIn(site.tsym, types) &&
  2533                      !s.isConstructor();
  2537     /**
  2538       * Report warnings for potentially ambiguous method declarations. Two declarations
  2539       * are potentially ambiguous if they feature two unrelated functional interface
  2540       * in same argument position (in which case, a call site passing an implicit
  2541       * lambda would be ambiguous).
  2542       */
  2543     void checkPotentiallyAmbiguousOverloads(DiagnosticPosition pos, Type site,
  2544             MethodSymbol msym1, MethodSymbol msym2) {
  2545         if (msym1 != msym2 &&
  2546                 allowDefaultMethods &&
  2547                 lint.isEnabled(LintCategory.OVERLOADS) &&
  2548                 (msym1.flags() & POTENTIALLY_AMBIGUOUS) == 0 &&
  2549                 (msym2.flags() & POTENTIALLY_AMBIGUOUS) == 0) {
  2550             Type mt1 = types.memberType(site, msym1);
  2551             Type mt2 = types.memberType(site, msym2);
  2552             //if both generic methods, adjust type variables
  2553             if (mt1.hasTag(FORALL) && mt2.hasTag(FORALL) &&
  2554                     types.hasSameBounds((ForAll)mt1, (ForAll)mt2)) {
  2555                 mt2 = types.subst(mt2, ((ForAll)mt2).tvars, ((ForAll)mt1).tvars);
  2557             //expand varargs methods if needed
  2558             int maxLength = Math.max(mt1.getParameterTypes().length(), mt2.getParameterTypes().length());
  2559             List<Type> args1 = rs.adjustArgs(mt1.getParameterTypes(), msym1, maxLength, true);
  2560             List<Type> args2 = rs.adjustArgs(mt2.getParameterTypes(), msym2, maxLength, true);
  2561             //if arities don't match, exit
  2562             if (args1.length() != args2.length()) return;
  2563             boolean potentiallyAmbiguous = false;
  2564             while (args1.nonEmpty() && args2.nonEmpty()) {
  2565                 Type s = args1.head;
  2566                 Type t = args2.head;
  2567                 if (!types.isSubtype(t, s) && !types.isSubtype(s, t)) {
  2568                     if (types.isFunctionalInterface(s) && types.isFunctionalInterface(t) &&
  2569                             types.findDescriptorType(s).getParameterTypes().length() > 0 &&
  2570                             types.findDescriptorType(s).getParameterTypes().length() ==
  2571                             types.findDescriptorType(t).getParameterTypes().length()) {
  2572                         potentiallyAmbiguous = true;
  2573                     } else {
  2574                         break;
  2577                 args1 = args1.tail;
  2578                 args2 = args2.tail;
  2580             if (potentiallyAmbiguous) {
  2581                 //we found two incompatible functional interfaces with same arity
  2582                 //this means a call site passing an implicit lambda would be ambigiuous
  2583                 msym1.flags_field |= POTENTIALLY_AMBIGUOUS;
  2584                 msym2.flags_field |= POTENTIALLY_AMBIGUOUS;
  2585                 log.warning(LintCategory.OVERLOADS, pos, "potentially.ambiguous.overload",
  2586                             msym1, msym1.location(),
  2587                             msym2, msym2.location());
  2588                 return;
  2593     /** Report a conflict between a user symbol and a synthetic symbol.
  2594      */
  2595     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2596         if (!sym.type.isErroneous()) {
  2597             if (warnOnSyntheticConflicts) {
  2598                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2600             else {
  2601                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2606     /** Check that class c does not implement directly or indirectly
  2607      *  the same parameterized interface with two different argument lists.
  2608      *  @param pos          Position to be used for error reporting.
  2609      *  @param type         The type whose interfaces are checked.
  2610      */
  2611     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2612         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2614 //where
  2615         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2616          *  with their class symbol as key and their type as value. Make
  2617          *  sure no class is entered with two different types.
  2618          */
  2619         void checkClassBounds(DiagnosticPosition pos,
  2620                               Map<TypeSymbol,Type> seensofar,
  2621                               Type type) {
  2622             if (type.isErroneous()) return;
  2623             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2624                 Type it = l.head;
  2625                 Type oldit = seensofar.put(it.tsym, it);
  2626                 if (oldit != null) {
  2627                     List<Type> oldparams = oldit.allparams();
  2628                     List<Type> newparams = it.allparams();
  2629                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2630                         log.error(pos, "cant.inherit.diff.arg",
  2631                                   it.tsym, Type.toString(oldparams),
  2632                                   Type.toString(newparams));
  2634                 checkClassBounds(pos, seensofar, it);
  2636             Type st = types.supertype(type);
  2637             if (st != null) checkClassBounds(pos, seensofar, st);
  2640     /** Enter interface into into set.
  2641      *  If it existed already, issue a "repeated interface" error.
  2642      */
  2643     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2644         if (its.contains(it))
  2645             log.error(pos, "repeated.interface");
  2646         else {
  2647             its.add(it);
  2651 /* *************************************************************************
  2652  * Check annotations
  2653  **************************************************************************/
  2655     /**
  2656      * Recursively validate annotations values
  2657      */
  2658     void validateAnnotationTree(JCTree tree) {
  2659         class AnnotationValidator extends TreeScanner {
  2660             @Override
  2661             public void visitAnnotation(JCAnnotation tree) {
  2662                 if (!tree.type.isErroneous()) {
  2663                     super.visitAnnotation(tree);
  2664                     validateAnnotation(tree);
  2668         tree.accept(new AnnotationValidator());
  2671     /**
  2672      *  {@literal
  2673      *  Annotation types are restricted to primitives, String, an
  2674      *  enum, an annotation, Class, Class<?>, Class<? extends
  2675      *  Anything>, arrays of the preceding.
  2676      *  }
  2677      */
  2678     void validateAnnotationType(JCTree restype) {
  2679         // restype may be null if an error occurred, so don't bother validating it
  2680         if (restype != null) {
  2681             validateAnnotationType(restype.pos(), restype.type);
  2685     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2686         if (type.isPrimitive()) return;
  2687         if (types.isSameType(type, syms.stringType)) return;
  2688         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2689         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2690         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2691         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2692             validateAnnotationType(pos, types.elemtype(type));
  2693             return;
  2695         log.error(pos, "invalid.annotation.member.type");
  2698     /**
  2699      * "It is also a compile-time error if any method declared in an
  2700      * annotation type has a signature that is override-equivalent to
  2701      * that of any public or protected method declared in class Object
  2702      * or in the interface annotation.Annotation."
  2704      * @jls 9.6 Annotation Types
  2705      */
  2706     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2707         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2708             Scope s = sup.tsym.members();
  2709             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2710                 if (e.sym.kind == MTH &&
  2711                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2712                     types.overrideEquivalent(m.type, e.sym.type))
  2713                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2718     /** Check the annotations of a symbol.
  2719      */
  2720     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2721         for (JCAnnotation a : annotations)
  2722             validateAnnotation(a, s);
  2725     /** Check the type annotations.
  2726      */
  2727     public void validateTypeAnnotations(List<JCAnnotation> annotations, boolean isTypeParameter) {
  2728         for (JCAnnotation a : annotations)
  2729             validateTypeAnnotation(a, isTypeParameter);
  2732     /** Check an annotation of a symbol.
  2733      */
  2734     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2735         validateAnnotationTree(a);
  2737         if (!annotationApplicable(a, s))
  2738             log.error(a.pos(), "annotation.type.not.applicable");
  2740         if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  2741             if (s.kind != TYP) {
  2742                 log.error(a.pos(), "bad.functional.intf.anno");
  2743             } else if (!s.isInterface() || (s.flags() & ANNOTATION) != 0) {
  2744                 log.error(a.pos(), "bad.functional.intf.anno.1", diags.fragment("not.a.functional.intf", s));
  2749     public void validateTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2750         Assert.checkNonNull(a.type, "annotation tree hasn't been attributed yet: " + a);
  2751         validateAnnotationTree(a);
  2753         if (!isTypeAnnotation(a, isTypeParameter))
  2754             log.error(a.pos(), "annotation.type.not.applicable");
  2757     /**
  2758      * Validate the proposed container 'repeatable' on the
  2759      * annotation type symbol 's'. Report errors at position
  2760      * 'pos'.
  2762      * @param s The (annotation)type declaration annotated with a @Repeatable
  2763      * @param repeatable the @Repeatable on 's'
  2764      * @param pos where to report errors
  2765      */
  2766     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2767         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2769         Type t = null;
  2770         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2771         if (!l.isEmpty()) {
  2772             Assert.check(l.head.fst.name == names.value);
  2773             t = ((Attribute.Class)l.head.snd).getValue();
  2776         if (t == null) {
  2777             // errors should already have been reported during Annotate
  2778             return;
  2781         validateValue(t.tsym, s, pos);
  2782         validateRetention(t.tsym, s, pos);
  2783         validateDocumented(t.tsym, s, pos);
  2784         validateInherited(t.tsym, s, pos);
  2785         validateTarget(t.tsym, s, pos);
  2786         validateDefault(t.tsym, s, pos);
  2789     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2790         Scope.Entry e = container.members().lookup(names.value);
  2791         if (e.scope != null && e.sym.kind == MTH) {
  2792             MethodSymbol m = (MethodSymbol) e.sym;
  2793             Type ret = m.getReturnType();
  2794             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2795                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2796                         container, ret, types.makeArrayType(contained.type));
  2798         } else {
  2799             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2803     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2804         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2805         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2807         boolean error = false;
  2808         switch (containedRetention) {
  2809         case RUNTIME:
  2810             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2811                 error = true;
  2813             break;
  2814         case CLASS:
  2815             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2816                 error = true;
  2819         if (error ) {
  2820             log.error(pos, "invalid.repeatable.annotation.retention",
  2821                       container, containerRetention,
  2822                       contained, containedRetention);
  2826     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2827         if (contained.attribute(syms.documentedType.tsym) != null) {
  2828             if (container.attribute(syms.documentedType.tsym) == null) {
  2829                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2834     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2835         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2836             if (container.attribute(syms.inheritedType.tsym) == null) {
  2837                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2842     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2843         // The set of targets the container is applicable to must be a subset
  2844         // (with respect to annotation target semantics) of the set of targets
  2845         // the contained is applicable to. The target sets may be implicit or
  2846         // explicit.
  2848         Set<Name> containerTargets;
  2849         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2850         if (containerTarget == null) {
  2851             containerTargets = getDefaultTargetSet();
  2852         } else {
  2853             containerTargets = new HashSet<Name>();
  2854         for (Attribute app : containerTarget.values) {
  2855             if (!(app instanceof Attribute.Enum)) {
  2856                 continue; // recovery
  2858             Attribute.Enum e = (Attribute.Enum)app;
  2859             containerTargets.add(e.value.name);
  2863         Set<Name> containedTargets;
  2864         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2865         if (containedTarget == null) {
  2866             containedTargets = getDefaultTargetSet();
  2867         } else {
  2868             containedTargets = new HashSet<Name>();
  2869         for (Attribute app : containedTarget.values) {
  2870             if (!(app instanceof Attribute.Enum)) {
  2871                 continue; // recovery
  2873             Attribute.Enum e = (Attribute.Enum)app;
  2874             containedTargets.add(e.value.name);
  2878         if (!isTargetSubsetOf(containerTargets, containedTargets)) {
  2879             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2883     /* get a set of names for the default target */
  2884     private Set<Name> getDefaultTargetSet() {
  2885         if (defaultTargets == null) {
  2886             Set<Name> targets = new HashSet<Name>();
  2887             targets.add(names.ANNOTATION_TYPE);
  2888             targets.add(names.CONSTRUCTOR);
  2889             targets.add(names.FIELD);
  2890             targets.add(names.LOCAL_VARIABLE);
  2891             targets.add(names.METHOD);
  2892             targets.add(names.PACKAGE);
  2893             targets.add(names.PARAMETER);
  2894             targets.add(names.TYPE);
  2896             defaultTargets = java.util.Collections.unmodifiableSet(targets);
  2899         return defaultTargets;
  2901     private Set<Name> defaultTargets;
  2904     /** Checks that s is a subset of t, with respect to ElementType
  2905      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2906      */
  2907     private boolean isTargetSubsetOf(Set<Name> s, Set<Name> t) {
  2908         // Check that all elements in s are present in t
  2909         for (Name n2 : s) {
  2910             boolean currentElementOk = false;
  2911             for (Name n1 : t) {
  2912                 if (n1 == n2) {
  2913                     currentElementOk = true;
  2914                     break;
  2915                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2916                     currentElementOk = true;
  2917                     break;
  2920             if (!currentElementOk)
  2921                 return false;
  2923         return true;
  2926     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2927         // validate that all other elements of containing type has defaults
  2928         Scope scope = container.members();
  2929         for(Symbol elm : scope.getElements()) {
  2930             if (elm.name != names.value &&
  2931                 elm.kind == Kinds.MTH &&
  2932                 ((MethodSymbol)elm).defaultValue == null) {
  2933                 log.error(pos,
  2934                           "invalid.repeatable.annotation.elem.nondefault",
  2935                           container,
  2936                           elm);
  2941     /** Is s a method symbol that overrides a method in a superclass? */
  2942     boolean isOverrider(Symbol s) {
  2943         if (s.kind != MTH || s.isStatic())
  2944             return false;
  2945         MethodSymbol m = (MethodSymbol)s;
  2946         TypeSymbol owner = (TypeSymbol)m.owner;
  2947         for (Type sup : types.closure(owner.type)) {
  2948             if (sup == owner.type)
  2949                 continue; // skip "this"
  2950             Scope scope = sup.tsym.members();
  2951             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2952                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2953                     return true;
  2956         return false;
  2959     /** Is the annotation applicable to types? */
  2960     protected boolean isTypeAnnotation(JCAnnotation a, boolean isTypeParameter) {
  2961         Attribute.Compound atTarget =
  2962             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2963         if (atTarget == null) {
  2964             // An annotation without @Target is not a type annotation.
  2965             return false;
  2968         Attribute atValue = atTarget.member(names.value);
  2969         if (!(atValue instanceof Attribute.Array)) {
  2970             return false; // error recovery
  2973         Attribute.Array arr = (Attribute.Array) atValue;
  2974         for (Attribute app : arr.values) {
  2975             if (!(app instanceof Attribute.Enum)) {
  2976                 return false; // recovery
  2978             Attribute.Enum e = (Attribute.Enum) app;
  2980             if (e.value.name == names.TYPE_USE)
  2981                 return true;
  2982             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  2983                 return true;
  2985         return false;
  2988     /** Is the annotation applicable to the symbol? */
  2989     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2990         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2991         Name[] targets;
  2993         if (arr == null) {
  2994             targets = defaultTargetMetaInfo(a, s);
  2995         } else {
  2996             // TODO: can we optimize this?
  2997             targets = new Name[arr.values.length];
  2998             for (int i=0; i<arr.values.length; ++i) {
  2999                 Attribute app = arr.values[i];
  3000                 if (!(app instanceof Attribute.Enum)) {
  3001                     return true; // recovery
  3003                 Attribute.Enum e = (Attribute.Enum) app;
  3004                 targets[i] = e.value.name;
  3007         for (Name target : targets) {
  3008             if (target == names.TYPE)
  3009                 { if (s.kind == TYP) return true; }
  3010             else if (target == names.FIELD)
  3011                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  3012             else if (target == names.METHOD)
  3013                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  3014             else if (target == names.PARAMETER)
  3015                 { if (s.kind == VAR &&
  3016                       s.owner.kind == MTH &&
  3017                       (s.flags() & PARAMETER) != 0)
  3018                     return true;
  3020             else if (target == names.CONSTRUCTOR)
  3021                 { if (s.kind == MTH && s.isConstructor()) return true; }
  3022             else if (target == names.LOCAL_VARIABLE)
  3023                 { if (s.kind == VAR && s.owner.kind == MTH &&
  3024                       (s.flags() & PARAMETER) == 0)
  3025                     return true;
  3027             else if (target == names.ANNOTATION_TYPE)
  3028                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  3029                     return true;
  3031             else if (target == names.PACKAGE)
  3032                 { if (s.kind == PCK) return true; }
  3033             else if (target == names.TYPE_USE)
  3034                 { if (s.kind == TYP ||
  3035                       s.kind == VAR ||
  3036                       (s.kind == MTH && !s.isConstructor() &&
  3037                       !s.type.getReturnType().hasTag(VOID)) ||
  3038                       (s.kind == MTH && s.isConstructor()))
  3039                     return true;
  3041             else if (target == names.TYPE_PARAMETER)
  3042                 { if (s.kind == TYP && s.type.hasTag(TYPEVAR))
  3043                     return true;
  3045             else
  3046                 return true; // recovery
  3048         return false;
  3052     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  3053         Attribute.Compound atTarget =
  3054             s.attribute(syms.annotationTargetType.tsym);
  3055         if (atTarget == null) return null; // ok, is applicable
  3056         Attribute atValue = atTarget.member(names.value);
  3057         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  3058         return (Attribute.Array) atValue;
  3061     private final Name[] dfltTargetMeta;
  3062     private Name[] defaultTargetMetaInfo(JCAnnotation a, Symbol s) {
  3063         return dfltTargetMeta;
  3066     /** Check an annotation value.
  3068      * @param a The annotation tree to check
  3069      * @return true if this annotation tree is valid, otherwise false
  3070      */
  3071     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  3072         boolean res = false;
  3073         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  3074         try {
  3075             res = validateAnnotation(a);
  3076         } finally {
  3077             log.popDiagnosticHandler(diagHandler);
  3079         return res;
  3082     private boolean validateAnnotation(JCAnnotation a) {
  3083         boolean isValid = true;
  3084         // collect an inventory of the annotation elements
  3085         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  3086         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  3087                 e != null;
  3088                 e = e.sibling)
  3089             if (e.sym.kind == MTH && e.sym.name != names.clinit &&
  3090                     (e.sym.flags() & SYNTHETIC) == 0)
  3091                 members.add((MethodSymbol) e.sym);
  3093         // remove the ones that are assigned values
  3094         for (JCTree arg : a.args) {
  3095             if (!arg.hasTag(ASSIGN)) continue; // recovery
  3096             JCAssign assign = (JCAssign) arg;
  3097             Symbol m = TreeInfo.symbol(assign.lhs);
  3098             if (m == null || m.type.isErroneous()) continue;
  3099             if (!members.remove(m)) {
  3100                 isValid = false;
  3101                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  3102                           m.name, a.type);
  3106         // all the remaining ones better have default values
  3107         List<Name> missingDefaults = List.nil();
  3108         for (MethodSymbol m : members) {
  3109             if (m.defaultValue == null && !m.type.isErroneous()) {
  3110                 missingDefaults = missingDefaults.append(m.name);
  3113         missingDefaults = missingDefaults.reverse();
  3114         if (missingDefaults.nonEmpty()) {
  3115             isValid = false;
  3116             String key = (missingDefaults.size() > 1)
  3117                     ? "annotation.missing.default.value.1"
  3118                     : "annotation.missing.default.value";
  3119             log.error(a.pos(), key, a.type, missingDefaults);
  3122         // special case: java.lang.annotation.Target must not have
  3123         // repeated values in its value member
  3124         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  3125             a.args.tail == null)
  3126             return isValid;
  3128         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  3129         JCAssign assign = (JCAssign) a.args.head;
  3130         Symbol m = TreeInfo.symbol(assign.lhs);
  3131         if (m.name != names.value) return false;
  3132         JCTree rhs = assign.rhs;
  3133         if (!rhs.hasTag(NEWARRAY)) return false;
  3134         JCNewArray na = (JCNewArray) rhs;
  3135         Set<Symbol> targets = new HashSet<Symbol>();
  3136         for (JCTree elem : na.elems) {
  3137             if (!targets.add(TreeInfo.symbol(elem))) {
  3138                 isValid = false;
  3139                 log.error(elem.pos(), "repeated.annotation.target");
  3142         return isValid;
  3145     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  3146         if (allowAnnotations &&
  3147             lint.isEnabled(LintCategory.DEP_ANN) &&
  3148             (s.flags() & DEPRECATED) != 0 &&
  3149             !syms.deprecatedType.isErroneous() &&
  3150             s.attribute(syms.deprecatedType.tsym) == null) {
  3151             log.warning(LintCategory.DEP_ANN,
  3152                     pos, "missing.deprecated.annotation");
  3156     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  3157         if ((s.flags() & DEPRECATED) != 0 &&
  3158                 (other.flags() & DEPRECATED) == 0 &&
  3159                 s.outermostClass() != other.outermostClass()) {
  3160             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3161                 @Override
  3162                 public void report() {
  3163                     warnDeprecated(pos, s);
  3165             });
  3169     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  3170         if ((s.flags() & PROPRIETARY) != 0) {
  3171             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  3172                 public void report() {
  3173                     if (enableSunApiLintControl)
  3174                       warnSunApi(pos, "sun.proprietary", s);
  3175                     else
  3176                       log.mandatoryWarning(pos, "sun.proprietary", s);
  3178             });
  3182     void checkProfile(final DiagnosticPosition pos, final Symbol s) {
  3183         if (profile != Profile.DEFAULT && (s.flags() & NOT_IN_PROFILE) != 0) {
  3184             log.error(pos, "not.in.profile", s, profile);
  3188 /* *************************************************************************
  3189  * Check for recursive annotation elements.
  3190  **************************************************************************/
  3192     /** Check for cycles in the graph of annotation elements.
  3193      */
  3194     void checkNonCyclicElements(JCClassDecl tree) {
  3195         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  3196         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  3197         try {
  3198             tree.sym.flags_field |= LOCKED;
  3199             for (JCTree def : tree.defs) {
  3200                 if (!def.hasTag(METHODDEF)) continue;
  3201                 JCMethodDecl meth = (JCMethodDecl)def;
  3202                 checkAnnotationResType(meth.pos(), meth.restype.type);
  3204         } finally {
  3205             tree.sym.flags_field &= ~LOCKED;
  3206             tree.sym.flags_field |= ACYCLIC_ANN;
  3210     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  3211         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  3212             return;
  3213         if ((tsym.flags_field & LOCKED) != 0) {
  3214             log.error(pos, "cyclic.annotation.element");
  3215             return;
  3217         try {
  3218             tsym.flags_field |= LOCKED;
  3219             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3220                 Symbol s = e.sym;
  3221                 if (s.kind != Kinds.MTH)
  3222                     continue;
  3223                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3225         } finally {
  3226             tsym.flags_field &= ~LOCKED;
  3227             tsym.flags_field |= ACYCLIC_ANN;
  3231     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3232         switch (type.getTag()) {
  3233         case CLASS:
  3234             if ((type.tsym.flags() & ANNOTATION) != 0)
  3235                 checkNonCyclicElementsInternal(pos, type.tsym);
  3236             break;
  3237         case ARRAY:
  3238             checkAnnotationResType(pos, types.elemtype(type));
  3239             break;
  3240         default:
  3241             break; // int etc
  3245 /* *************************************************************************
  3246  * Check for cycles in the constructor call graph.
  3247  **************************************************************************/
  3249     /** Check for cycles in the graph of constructors calling other
  3250      *  constructors.
  3251      */
  3252     void checkCyclicConstructors(JCClassDecl tree) {
  3253         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3255         // enter each constructor this-call into the map
  3256         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3257             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3258             if (app == null) continue;
  3259             JCMethodDecl meth = (JCMethodDecl) l.head;
  3260             if (TreeInfo.name(app.meth) == names._this) {
  3261                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3262             } else {
  3263                 meth.sym.flags_field |= ACYCLIC;
  3267         // Check for cycles in the map
  3268         Symbol[] ctors = new Symbol[0];
  3269         ctors = callMap.keySet().toArray(ctors);
  3270         for (Symbol caller : ctors) {
  3271             checkCyclicConstructor(tree, caller, callMap);
  3275     /** Look in the map to see if the given constructor is part of a
  3276      *  call cycle.
  3277      */
  3278     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3279                                         Map<Symbol,Symbol> callMap) {
  3280         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3281             if ((ctor.flags_field & LOCKED) != 0) {
  3282                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3283                           "recursive.ctor.invocation");
  3284             } else {
  3285                 ctor.flags_field |= LOCKED;
  3286                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3287                 ctor.flags_field &= ~LOCKED;
  3289             ctor.flags_field |= ACYCLIC;
  3293 /* *************************************************************************
  3294  * Miscellaneous
  3295  **************************************************************************/
  3297     /**
  3298      * Return the opcode of the operator but emit an error if it is an
  3299      * error.
  3300      * @param pos        position for error reporting.
  3301      * @param operator   an operator
  3302      * @param tag        a tree tag
  3303      * @param left       type of left hand side
  3304      * @param right      type of right hand side
  3305      */
  3306     int checkOperator(DiagnosticPosition pos,
  3307                        OperatorSymbol operator,
  3308                        JCTree.Tag tag,
  3309                        Type left,
  3310                        Type right) {
  3311         if (operator.opcode == ByteCodes.error) {
  3312             log.error(pos,
  3313                       "operator.cant.be.applied.1",
  3314                       treeinfo.operatorName(tag),
  3315                       left, right);
  3317         return operator.opcode;
  3321     /**
  3322      *  Check for division by integer constant zero
  3323      *  @param pos           Position for error reporting.
  3324      *  @param operator      The operator for the expression
  3325      *  @param operand       The right hand operand for the expression
  3326      */
  3327     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3328         if (operand.constValue() != null
  3329             && lint.isEnabled(LintCategory.DIVZERO)
  3330             && operand.getTag().isSubRangeOf(LONG)
  3331             && ((Number) (operand.constValue())).longValue() == 0) {
  3332             int opc = ((OperatorSymbol)operator).opcode;
  3333             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3334                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3335                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3340     /**
  3341      * Check for empty statements after if
  3342      */
  3343     void checkEmptyIf(JCIf tree) {
  3344         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3345                 lint.isEnabled(LintCategory.EMPTY))
  3346             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3349     /** Check that symbol is unique in given scope.
  3350      *  @param pos           Position for error reporting.
  3351      *  @param sym           The symbol.
  3352      *  @param s             The scope.
  3353      */
  3354     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3355         if (sym.type.isErroneous())
  3356             return true;
  3357         if (sym.owner.name == names.any) return false;
  3358         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3359             if (sym != e.sym &&
  3360                     (e.sym.flags() & CLASH) == 0 &&
  3361                     sym.kind == e.sym.kind &&
  3362                     sym.name != names.error &&
  3363                     (sym.kind != MTH ||
  3364                      types.hasSameArgs(sym.type, e.sym.type) ||
  3365                      types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3366                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3367                     varargsDuplicateError(pos, sym, e.sym);
  3368                     return true;
  3369                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3370                     duplicateErasureError(pos, sym, e.sym);
  3371                     sym.flags_field |= CLASH;
  3372                     return true;
  3373                 } else {
  3374                     duplicateError(pos, e.sym);
  3375                     return false;
  3379         return true;
  3382     /** Report duplicate declaration error.
  3383      */
  3384     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3385         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3386             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3390     /** Check that single-type import is not already imported or top-level defined,
  3391      *  but make an exception for two single-type imports which denote the same type.
  3392      *  @param pos           Position for error reporting.
  3393      *  @param sym           The symbol.
  3394      *  @param s             The scope
  3395      */
  3396     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3397         return checkUniqueImport(pos, sym, s, false);
  3400     /** Check that static single-type import is not already imported or top-level defined,
  3401      *  but make an exception for two single-type imports which denote the same type.
  3402      *  @param pos           Position for error reporting.
  3403      *  @param sym           The symbol.
  3404      *  @param s             The scope
  3405      */
  3406     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3407         return checkUniqueImport(pos, sym, s, true);
  3410     /** Check that single-type import is not already imported or top-level defined,
  3411      *  but make an exception for two single-type imports which denote the same type.
  3412      *  @param pos           Position for error reporting.
  3413      *  @param sym           The symbol.
  3414      *  @param s             The scope.
  3415      *  @param staticImport  Whether or not this was a static import
  3416      */
  3417     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3418         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3419             // is encountered class entered via a class declaration?
  3420             boolean isClassDecl = e.scope == s;
  3421             if ((isClassDecl || sym != e.sym) &&
  3422                 sym.kind == e.sym.kind &&
  3423                 sym.name != names.error &&
  3424                 (!staticImport || !e.isStaticallyImported())) {
  3425                 if (!e.sym.type.isErroneous()) {
  3426                     if (!isClassDecl) {
  3427                         if (staticImport)
  3428                             log.error(pos, "already.defined.static.single.import", e.sym);
  3429                         else
  3430                         log.error(pos, "already.defined.single.import", e.sym);
  3432                     else if (sym != e.sym)
  3433                         log.error(pos, "already.defined.this.unit", e.sym);
  3435                 return false;
  3438         return true;
  3441     /** Check that a qualified name is in canonical form (for import decls).
  3442      */
  3443     public void checkCanonical(JCTree tree) {
  3444         if (!isCanonical(tree))
  3445             log.error(tree.pos(), "import.requires.canonical",
  3446                       TreeInfo.symbol(tree));
  3448         // where
  3449         private boolean isCanonical(JCTree tree) {
  3450             while (tree.hasTag(SELECT)) {
  3451                 JCFieldAccess s = (JCFieldAccess) tree;
  3452                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3453                     return false;
  3454                 tree = s.selected;
  3456             return true;
  3459     /** Check that an auxiliary class is not accessed from any other file than its own.
  3460      */
  3461     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3462         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3463             (c.flags() & AUXILIARY) != 0 &&
  3464             rs.isAccessible(env, c) &&
  3465             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3467             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3468                         c, c.sourcefile);
  3472     private class ConversionWarner extends Warner {
  3473         final String uncheckedKey;
  3474         final Type found;
  3475         final Type expected;
  3476         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3477             super(pos);
  3478             this.uncheckedKey = uncheckedKey;
  3479             this.found = found;
  3480             this.expected = expected;
  3483         @Override
  3484         public void warn(LintCategory lint) {
  3485             boolean warned = this.warned;
  3486             super.warn(lint);
  3487             if (warned) return; // suppress redundant diagnostics
  3488             switch (lint) {
  3489                 case UNCHECKED:
  3490                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3491                     break;
  3492                 case VARARGS:
  3493                     if (method != null &&
  3494                             method.attribute(syms.trustMeType.tsym) != null &&
  3495                             isTrustMeAllowedOnMethod(method) &&
  3496                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3497                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3499                     break;
  3500                 default:
  3501                     throw new AssertionError("Unexpected lint: " + lint);
  3506     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3507         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3510     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3511         return new ConversionWarner(pos, "unchecked.assign", found, expected);
  3514     public void checkFunctionalInterface(JCClassDecl tree, ClassSymbol cs) {
  3515         Compound functionalType = cs.attribute(syms.functionalInterfaceType.tsym);
  3517         if (functionalType != null) {
  3518             try {
  3519                 types.findDescriptorSymbol((TypeSymbol)cs);
  3520             } catch (Types.FunctionDescriptorLookupError ex) {
  3521                 DiagnosticPosition pos = tree.pos();
  3522                 for (JCAnnotation a : tree.getModifiers().annotations) {
  3523                     if (a.annotationType.type.tsym == syms.functionalInterfaceType.tsym) {
  3524                         pos = a.pos();
  3525                         break;
  3528                 log.error(pos, "bad.functional.intf.anno.1", ex.getDiagnostic());

mercurial