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

Wed, 16 Jan 2013 16:27:01 +0000

author
mcimadamore
date
Wed, 16 Jan 2013 16:27:01 +0000
changeset 1496
f785dcac17b7
parent 1492
df694c775e8a
child 1497
7aa2025bbb7b
permissions
-rw-r--r--

8005854: Add support for array constructor references
Summary: Support constructor references of the kind int[]::new
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.tools.JavaFileManager;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.jvm.*;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.util.*;
    36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    37 import com.sun.tools.javac.util.List;
    39 import com.sun.tools.javac.tree.JCTree.*;
    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.InferenceContext.FreeTypeListener;
    48 import static com.sun.tools.javac.code.Flags.*;
    49 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    50 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    51 import static com.sun.tools.javac.code.Kinds.*;
    52 import static com.sun.tools.javac.code.TypeTag.*;
    53 import static com.sun.tools.javac.code.TypeTag.WILDCARD;
    55 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    57 /** Type checking helper class for the attribution phase.
    58  *
    59  *  <p><b>This is NOT part of any supported API.
    60  *  If you write code that depends on this, you do so at your own risk.
    61  *  This code and its internal interfaces are subject to change or
    62  *  deletion without notice.</b>
    63  */
    64 public class Check {
    65     protected static final Context.Key<Check> checkKey =
    66         new Context.Key<Check>();
    68     private final Names names;
    69     private final Log log;
    70     private final Resolve rs;
    71     private final Symtab syms;
    72     private final Enter enter;
    73     private final DeferredAttr deferredAttr;
    74     private final Infer infer;
    75     private final Types types;
    76     private final JCDiagnostic.Factory diags;
    77     private boolean warnOnSyntheticConflicts;
    78     private boolean suppressAbortOnBadClassFile;
    79     private boolean enableSunApiLintControl;
    80     private final TreeInfo treeinfo;
    81     private final JavaFileManager fileManager;
    83     // The set of lint options currently in effect. It is initialized
    84     // from the context, and then is set/reset as needed by Attr as it
    85     // visits all the various parts of the trees during attribution.
    86     private Lint lint;
    88     // The method being analyzed in Attr - it is set/reset as needed by
    89     // Attr as it visits new method declarations.
    90     private MethodSymbol method;
    92     public static Check instance(Context context) {
    93         Check instance = context.get(checkKey);
    94         if (instance == null)
    95             instance = new Check(context);
    96         return instance;
    97     }
    99     protected Check(Context context) {
   100         context.put(checkKey, this);
   102         names = Names.instance(context);
   103         log = Log.instance(context);
   104         rs = Resolve.instance(context);
   105         syms = Symtab.instance(context);
   106         enter = Enter.instance(context);
   107         deferredAttr = DeferredAttr.instance(context);
   108         infer = Infer.instance(context);
   109         this.types = Types.instance(context);
   110         diags = JCDiagnostic.Factory.instance(context);
   111         Options options = Options.instance(context);
   112         lint = Lint.instance(context);
   113         treeinfo = TreeInfo.instance(context);
   114         fileManager = context.get(JavaFileManager.class);
   116         Source source = Source.instance(context);
   117         allowGenerics = source.allowGenerics();
   118         allowVarargs = source.allowVarargs();
   119         allowAnnotations = source.allowAnnotations();
   120         allowCovariantReturns = source.allowCovariantReturns();
   121         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   122         allowDefaultMethods = source.allowDefaultMethods();
   123         allowStrictMethodClashCheck = source.allowStrictMethodClashCheck();
   124         complexInference = options.isSet("complexinference");
   125         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   126         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   127         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   129         Target target = Target.instance(context);
   130         syntheticNameChar = target.syntheticNameChar();
   132         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   133         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   134         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   135         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   137         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   138                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   139         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   140                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   141         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   142                 enforceMandatoryWarnings, "sunapi", null);
   144         deferredLintHandler = DeferredLintHandler.immediateHandler;
   145     }
   147     /** Switch: generics enabled?
   148      */
   149     boolean allowGenerics;
   151     /** Switch: varargs enabled?
   152      */
   153     boolean allowVarargs;
   155     /** Switch: annotations enabled?
   156      */
   157     boolean allowAnnotations;
   159     /** Switch: covariant returns enabled?
   160      */
   161     boolean allowCovariantReturns;
   163     /** Switch: simplified varargs enabled?
   164      */
   165     boolean allowSimplifiedVarargs;
   167     /** Switch: default methods enabled?
   168      */
   169     boolean allowDefaultMethods;
   171     /** Switch: should unrelated return types trigger a method clash?
   172      */
   173     boolean allowStrictMethodClashCheck;
   175     /** Switch: -complexinference option set?
   176      */
   177     boolean complexInference;
   179     /** Character for synthetic names
   180      */
   181     char syntheticNameChar;
   183     /** A table mapping flat names of all compiled classes in this run to their
   184      *  symbols; maintained from outside.
   185      */
   186     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   188     /** A handler for messages about deprecated usage.
   189      */
   190     private MandatoryWarningHandler deprecationHandler;
   192     /** A handler for messages about unchecked or unsafe usage.
   193      */
   194     private MandatoryWarningHandler uncheckedHandler;
   196     /** A handler for messages about using proprietary API.
   197      */
   198     private MandatoryWarningHandler sunApiHandler;
   200     /** A handler for deferred lint warnings.
   201      */
   202     private DeferredLintHandler deferredLintHandler;
   204 /* *************************************************************************
   205  * Errors and Warnings
   206  **************************************************************************/
   208     Lint setLint(Lint newLint) {
   209         Lint prev = lint;
   210         lint = newLint;
   211         return prev;
   212     }
   214     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   215         DeferredLintHandler prev = deferredLintHandler;
   216         deferredLintHandler = newDeferredLintHandler;
   217         return prev;
   218     }
   220     MethodSymbol setMethod(MethodSymbol newMethod) {
   221         MethodSymbol prev = method;
   222         method = newMethod;
   223         return prev;
   224     }
   226     /** Warn about deprecated symbol.
   227      *  @param pos        Position to be used for error reporting.
   228      *  @param sym        The deprecated symbol.
   229      */
   230     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   231         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   232             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   233     }
   235     /** Warn about unchecked operation.
   236      *  @param pos        Position to be used for error reporting.
   237      *  @param msg        A string describing the problem.
   238      */
   239     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   240         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   241             uncheckedHandler.report(pos, msg, args);
   242     }
   244     /** Warn about unsafe vararg method decl.
   245      *  @param pos        Position to be used for error reporting.
   246      */
   247     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   248         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   249             log.warning(LintCategory.VARARGS, pos, key, args);
   250     }
   252     /** Warn about using proprietary API.
   253      *  @param pos        Position to be used for error reporting.
   254      *  @param msg        A string describing the problem.
   255      */
   256     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   257         if (!lint.isSuppressed(LintCategory.SUNAPI))
   258             sunApiHandler.report(pos, msg, args);
   259     }
   261     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   262         if (lint.isEnabled(LintCategory.STATIC))
   263             log.warning(LintCategory.STATIC, pos, msg, args);
   264     }
   266     /**
   267      * Report any deferred diagnostics.
   268      */
   269     public void reportDeferredDiagnostics() {
   270         deprecationHandler.reportDeferredDiagnostic();
   271         uncheckedHandler.reportDeferredDiagnostic();
   272         sunApiHandler.reportDeferredDiagnostic();
   273     }
   276     /** Report a failure to complete a class.
   277      *  @param pos        Position to be used for error reporting.
   278      *  @param ex         The failure to report.
   279      */
   280     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   281         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   282         if (ex instanceof ClassReader.BadClassFile
   283                 && !suppressAbortOnBadClassFile) throw new Abort();
   284         else return syms.errType;
   285     }
   287     /** Report an error that wrong type tag was found.
   288      *  @param pos        Position to be used for error reporting.
   289      *  @param required   An internationalized string describing the type tag
   290      *                    required.
   291      *  @param found      The type that was found.
   292      */
   293     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   294         // this error used to be raised by the parser,
   295         // but has been delayed to this point:
   296         if (found instanceof Type && ((Type)found).hasTag(VOID)) {
   297             log.error(pos, "illegal.start.of.type");
   298             return syms.errType;
   299         }
   300         log.error(pos, "type.found.req", found, required);
   301         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   302     }
   304     /** Report an error that symbol cannot be referenced before super
   305      *  has been called.
   306      *  @param pos        Position to be used for error reporting.
   307      *  @param sym        The referenced symbol.
   308      */
   309     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   310         log.error(pos, "cant.ref.before.ctor.called", sym);
   311     }
   313     /** Report duplicate declaration error.
   314      */
   315     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   316         if (!sym.type.isErroneous()) {
   317             Symbol location = sym.location();
   318             if (location.kind == MTH &&
   319                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   320                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   321                         kindName(sym.location()), kindName(sym.location().enclClass()),
   322                         sym.location().enclClass());
   323             } else {
   324                 log.error(pos, "already.defined", kindName(sym), sym,
   325                         kindName(sym.location()), sym.location());
   326             }
   327         }
   328     }
   330     /** Report array/varargs duplicate declaration
   331      */
   332     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   333         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   334             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   335         }
   336     }
   338 /* ************************************************************************
   339  * duplicate declaration checking
   340  *************************************************************************/
   342     /** Check that variable does not hide variable with same name in
   343      *  immediately enclosing local scope.
   344      *  @param pos           Position for error reporting.
   345      *  @param v             The symbol.
   346      *  @param s             The scope.
   347      */
   348     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   349         if (s.next != null) {
   350             for (Scope.Entry e = s.next.lookup(v.name);
   351                  e.scope != null && e.sym.owner == v.owner;
   352                  e = e.next()) {
   353                 if (e.sym.kind == VAR &&
   354                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   355                     v.name != names.error) {
   356                     duplicateError(pos, e.sym);
   357                     return;
   358                 }
   359             }
   360         }
   361     }
   363     /** Check that a class or interface does not hide a class or
   364      *  interface with same name in immediately enclosing local scope.
   365      *  @param pos           Position for error reporting.
   366      *  @param c             The symbol.
   367      *  @param s             The scope.
   368      */
   369     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   370         if (s.next != null) {
   371             for (Scope.Entry e = s.next.lookup(c.name);
   372                  e.scope != null && e.sym.owner == c.owner;
   373                  e = e.next()) {
   374                 if (e.sym.kind == TYP && !e.sym.type.hasTag(TYPEVAR) &&
   375                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   376                     c.name != names.error) {
   377                     duplicateError(pos, e.sym);
   378                     return;
   379                 }
   380             }
   381         }
   382     }
   384     /** Check that class does not have the same name as one of
   385      *  its enclosing classes, or as a class defined in its enclosing scope.
   386      *  return true if class is unique in its enclosing scope.
   387      *  @param pos           Position for error reporting.
   388      *  @param name          The class name.
   389      *  @param s             The enclosing scope.
   390      */
   391     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   392         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   393             if (e.sym.kind == TYP && e.sym.name != names.error) {
   394                 duplicateError(pos, e.sym);
   395                 return false;
   396             }
   397         }
   398         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   399             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   400                 duplicateError(pos, sym);
   401                 return true;
   402             }
   403         }
   404         return true;
   405     }
   407 /* *************************************************************************
   408  * Class name generation
   409  **************************************************************************/
   411     /** Return name of local class.
   412      *  This is of the form   {@code <enclClass> $ n <classname> }
   413      *  where
   414      *    enclClass is the flat name of the enclosing class,
   415      *    classname is the simple name of the local class
   416      */
   417     Name localClassName(ClassSymbol c) {
   418         for (int i=1; ; i++) {
   419             Name flatname = names.
   420                 fromString("" + c.owner.enclClass().flatname +
   421                            syntheticNameChar + i +
   422                            c.name);
   423             if (compiled.get(flatname) == null) return flatname;
   424         }
   425     }
   427 /* *************************************************************************
   428  * Type Checking
   429  **************************************************************************/
   431     /**
   432      * A check context is an object that can be used to perform compatibility
   433      * checks - depending on the check context, meaning of 'compatibility' might
   434      * vary significantly.
   435      */
   436     public interface CheckContext {
   437         /**
   438          * Is type 'found' compatible with type 'req' in given context
   439          */
   440         boolean compatible(Type found, Type req, Warner warn);
   441         /**
   442          * Report a check error
   443          */
   444         void report(DiagnosticPosition pos, JCDiagnostic details);
   445         /**
   446          * Obtain a warner for this check context
   447          */
   448         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   450         public Infer.InferenceContext inferenceContext();
   452         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   453     }
   455     /**
   456      * This class represent a check context that is nested within another check
   457      * context - useful to check sub-expressions. The default behavior simply
   458      * redirects all method calls to the enclosing check context leveraging
   459      * the forwarding pattern.
   460      */
   461     static class NestedCheckContext implements CheckContext {
   462         CheckContext enclosingContext;
   464         NestedCheckContext(CheckContext enclosingContext) {
   465             this.enclosingContext = enclosingContext;
   466         }
   468         public boolean compatible(Type found, Type req, Warner warn) {
   469             return enclosingContext.compatible(found, req, warn);
   470         }
   472         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   473             enclosingContext.report(pos, details);
   474         }
   476         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   477             return enclosingContext.checkWarner(pos, found, req);
   478         }
   480         public Infer.InferenceContext inferenceContext() {
   481             return enclosingContext.inferenceContext();
   482         }
   484         public DeferredAttrContext deferredAttrContext() {
   485             return enclosingContext.deferredAttrContext();
   486         }
   487     }
   489     /**
   490      * Check context to be used when evaluating assignment/return statements
   491      */
   492     CheckContext basicHandler = new CheckContext() {
   493         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   494             log.error(pos, "prob.found.req", details);
   495         }
   496         public boolean compatible(Type found, Type req, Warner warn) {
   497             return types.isAssignable(found, req, warn);
   498         }
   500         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   501             return convertWarner(pos, found, req);
   502         }
   504         public InferenceContext inferenceContext() {
   505             return infer.emptyContext;
   506         }
   508         public DeferredAttrContext deferredAttrContext() {
   509             return deferredAttr.emptyDeferredAttrContext;
   510         }
   511     };
   513     /** Check that a given type is assignable to a given proto-type.
   514      *  If it is, return the type, otherwise return errType.
   515      *  @param pos        Position to be used for error reporting.
   516      *  @param found      The type that was found.
   517      *  @param req        The type that was required.
   518      */
   519     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   520         return checkType(pos, found, req, basicHandler);
   521     }
   523     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   524         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   525         if (inferenceContext.free(req)) {
   526             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   527                 @Override
   528                 public void typesInferred(InferenceContext inferenceContext) {
   529                     checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
   530                 }
   531             });
   532         }
   533         if (req.hasTag(ERROR))
   534             return req;
   535         if (req.hasTag(NONE))
   536             return found;
   537         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   538             return found;
   539         } else {
   540             if (found.getTag().isSubRangeOf(DOUBLE) && req.getTag().isSubRangeOf(DOUBLE)) {
   541                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   542                 return types.createErrorType(found);
   543             }
   544             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   545             return types.createErrorType(found);
   546         }
   547     }
   549     /** Check that a given type can be cast to a given target type.
   550      *  Return the result of the cast.
   551      *  @param pos        Position to be used for error reporting.
   552      *  @param found      The type that is being cast.
   553      *  @param req        The target type of the cast.
   554      */
   555     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   556         return checkCastable(pos, found, req, basicHandler);
   557     }
   558     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   559         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   560             return req;
   561         } else {
   562             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   563             return types.createErrorType(found);
   564         }
   565     }
   567     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   568      * The problem should only be reported for non-292 cast
   569      */
   570     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   571         if (!tree.type.isErroneous() &&
   572                 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   573                 && types.isSameType(tree.expr.type, tree.clazz.type)
   574                 && !is292targetTypeCast(tree)) {
   575             log.warning(Lint.LintCategory.CAST,
   576                     tree.pos(), "redundant.cast", tree.expr.type);
   577         }
   578     }
   579     //where
   580             private boolean is292targetTypeCast(JCTypeCast tree) {
   581                 boolean is292targetTypeCast = false;
   582                 JCExpression expr = TreeInfo.skipParens(tree.expr);
   583                 if (expr.hasTag(APPLY)) {
   584                     JCMethodInvocation apply = (JCMethodInvocation)expr;
   585                     Symbol sym = TreeInfo.symbol(apply.meth);
   586                     is292targetTypeCast = sym != null &&
   587                         sym.kind == MTH &&
   588                         (sym.flags() & HYPOTHETICAL) != 0;
   589                 }
   590                 return is292targetTypeCast;
   591             }
   595 //where
   596         /** Is type a type variable, or a (possibly multi-dimensional) array of
   597          *  type variables?
   598          */
   599         boolean isTypeVar(Type t) {
   600             return t.hasTag(TYPEVAR) || t.hasTag(ARRAY) && isTypeVar(types.elemtype(t));
   601         }
   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");
   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             }
   679         }
   680         return t;
   681     }
   683     /** Check that type is a class or interface type.
   684      *  @param pos           Position to be used for error reporting.
   685      *  @param t             The type to be checked.
   686      *  @param noBounds    True if type bounds are illegal here.
   687      */
   688     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   689         t = checkClassType(pos, t);
   690         if (noBounds && t.isParameterized()) {
   691             List<Type> args = t.getTypeArguments();
   692             while (args.nonEmpty()) {
   693                 if (args.head.hasTag(WILDCARD))
   694                     return typeTagError(pos,
   695                                         diags.fragment("type.req.exact"),
   696                                         args.head);
   697                 args = args.tail;
   698             }
   699         }
   700         return t;
   701     }
   703     /** Check that type is a reifiable class, interface or array type.
   704      *  @param pos           Position to be used for error reporting.
   705      *  @param t             The type to be checked.
   706      */
   707     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   708         t = checkClassOrArrayType(pos, t);
   709         if (!t.isErroneous() && !types.isReifiable(t)) {
   710             log.error(pos, "illegal.generic.type.for.instof");
   711             return types.createErrorType(t);
   712         } else {
   713             return t;
   714         }
   715     }
   717     /** Check that type is a reference type, i.e. a class, interface or array type
   718      *  or a type variable.
   719      *  @param pos           Position to be used for error reporting.
   720      *  @param t             The type to be checked.
   721      */
   722     Type checkRefType(DiagnosticPosition pos, Type t) {
   723         if (t.isReference())
   724             return t;
   725         else
   726             return typeTagError(pos,
   727                                 diags.fragment("type.req.ref"),
   728                                 t);
   729     }
   731     /** Check that each type is a reference type, i.e. a class, interface or array type
   732      *  or a type variable.
   733      *  @param trees         Original trees, used for error reporting.
   734      *  @param types         The types to be checked.
   735      */
   736     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   737         List<JCExpression> tl = trees;
   738         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   739             l.head = checkRefType(tl.head.pos(), l.head);
   740             tl = tl.tail;
   741         }
   742         return types;
   743     }
   745     /** Check that type is a null or reference type.
   746      *  @param pos           Position to be used for error reporting.
   747      *  @param t             The type to be checked.
   748      */
   749     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   750         if (t.isNullOrReference())
   751             return t;
   752         else
   753             return typeTagError(pos,
   754                                 diags.fragment("type.req.ref"),
   755                                 t);
   756     }
   758     /** Check that flag set does not contain elements of two conflicting sets. s
   759      *  Return true if it doesn't.
   760      *  @param pos           Position to be used for error reporting.
   761      *  @param flags         The set of flags to be checked.
   762      *  @param set1          Conflicting flags set #1.
   763      *  @param set2          Conflicting flags set #2.
   764      */
   765     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   766         if ((flags & set1) != 0 && (flags & set2) != 0) {
   767             log.error(pos,
   768                       "illegal.combination.of.modifiers",
   769                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   770                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   771             return false;
   772         } else
   773             return true;
   774     }
   776     /** Check that usage of diamond operator is correct (i.e. diamond should not
   777      * be used with non-generic classes or in anonymous class creation expressions)
   778      */
   779     Type checkDiamond(JCNewClass tree, Type t) {
   780         if (!TreeInfo.isDiamond(tree) ||
   781                 t.isErroneous()) {
   782             return checkClassType(tree.clazz.pos(), t, true);
   783         } else if (tree.def != null) {
   784             log.error(tree.clazz.pos(),
   785                     "cant.apply.diamond.1",
   786                     t, diags.fragment("diamond.and.anon.class", t));
   787             return types.createErrorType(t);
   788         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   789             log.error(tree.clazz.pos(),
   790                 "cant.apply.diamond.1",
   791                 t, diags.fragment("diamond.non.generic", t));
   792             return types.createErrorType(t);
   793         } else if (tree.typeargs != null &&
   794                 tree.typeargs.nonEmpty()) {
   795             log.error(tree.clazz.pos(),
   796                 "cant.apply.diamond.1",
   797                 t, diags.fragment("diamond.and.explicit.params", t));
   798             return types.createErrorType(t);
   799         } else {
   800             return t;
   801         }
   802     }
   804     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   805         MethodSymbol m = tree.sym;
   806         if (!allowSimplifiedVarargs) return;
   807         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   808         Type varargElemType = null;
   809         if (m.isVarArgs()) {
   810             varargElemType = types.elemtype(tree.params.last().type);
   811         }
   812         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   813             if (varargElemType != null) {
   814                 log.error(tree,
   815                         "varargs.invalid.trustme.anno",
   816                         syms.trustMeType.tsym,
   817                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   818             } else {
   819                 log.error(tree,
   820                             "varargs.invalid.trustme.anno",
   821                             syms.trustMeType.tsym,
   822                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   823             }
   824         } else if (hasTrustMeAnno && varargElemType != null &&
   825                             types.isReifiable(varargElemType)) {
   826             warnUnsafeVararg(tree,
   827                             "varargs.redundant.trustme.anno",
   828                             syms.trustMeType.tsym,
   829                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   830         }
   831         else if (!hasTrustMeAnno && varargElemType != null &&
   832                 !types.isReifiable(varargElemType)) {
   833             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   834         }
   835     }
   836     //where
   837         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   838             return (s.flags() & VARARGS) != 0 &&
   839                 (s.isConstructor() ||
   840                     (s.flags() & (STATIC | FINAL)) != 0);
   841         }
   843     Type checkMethod(Type owntype,
   844                             Symbol sym,
   845                             Env<AttrContext> env,
   846                             final List<JCExpression> argtrees,
   847                             List<Type> argtypes,
   848                             boolean useVarargs,
   849                             boolean unchecked) {
   850         // System.out.println("call   : " + env.tree);
   851         // System.out.println("method : " + owntype);
   852         // System.out.println("actuals: " + argtypes);
   853         List<Type> formals = owntype.getParameterTypes();
   854         Type last = useVarargs ? formals.last() : null;
   855         if (sym.name==names.init &&
   856                 sym.owner == syms.enumSym)
   857                 formals = formals.tail.tail;
   858         List<JCExpression> args = argtrees;
   859         DeferredAttr.DeferredTypeMap checkDeferredMap =
   860                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   861         if (args != null) {
   862             //this is null when type-checking a method reference
   863             while (formals.head != last) {
   864                 JCTree arg = args.head;
   865                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   866                 assertConvertible(arg, arg.type, formals.head, warn);
   867                 args = args.tail;
   868                 formals = formals.tail;
   869             }
   870             if (useVarargs) {
   871                 Type varArg = types.elemtype(last);
   872                 while (args.tail != null) {
   873                     JCTree arg = args.head;
   874                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   875                     assertConvertible(arg, arg.type, varArg, warn);
   876                     args = args.tail;
   877                 }
   878             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   879                 // non-varargs call to varargs method
   880                 Type varParam = owntype.getParameterTypes().last();
   881                 Type lastArg = checkDeferredMap.apply(argtypes.last());
   882                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   883                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   884                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   885                             types.elemtype(varParam), varParam);
   886             }
   887         }
   888         if (unchecked) {
   889             warnUnchecked(env.tree.pos(),
   890                     "unchecked.meth.invocation.applied",
   891                     kindName(sym),
   892                     sym.name,
   893                     rs.methodArguments(sym.type.getParameterTypes()),
   894                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   895                     kindName(sym.location()),
   896                     sym.location());
   897            owntype = new MethodType(owntype.getParameterTypes(),
   898                    types.erasure(owntype.getReturnType()),
   899                    types.erasure(owntype.getThrownTypes()),
   900                    syms.methodClass);
   901         }
   902         if (useVarargs) {
   903             JCTree tree = env.tree;
   904             Type argtype = owntype.getParameterTypes().last();
   905             if (!types.isReifiable(argtype) &&
   906                     (!allowSimplifiedVarargs ||
   907                     sym.attribute(syms.trustMeType.tsym) == null ||
   908                     !isTrustMeAllowedOnMethod(sym))) {
   909                 warnUnchecked(env.tree.pos(),
   910                                   "unchecked.generic.array.creation",
   911                                   argtype);
   912             }
   913             if (!((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types)) {
   914                 Type elemtype = types.elemtype(argtype);
   915                 switch (tree.getTag()) {
   916                     case APPLY:
   917                         ((JCMethodInvocation) tree).varargsElement = elemtype;
   918                         break;
   919                     case NEWCLASS:
   920                         ((JCNewClass) tree).varargsElement = elemtype;
   921                         break;
   922                     case REFERENCE:
   923                         ((JCMemberReference) tree).varargsElement = elemtype;
   924                         break;
   925                     default:
   926                         throw new AssertionError(""+tree);
   927                 }
   928             }
   929          }
   930          return owntype;
   931     }
   932     //where
   933         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   934             if (types.isConvertible(actual, formal, warn))
   935                 return;
   937             if (formal.isCompound()
   938                 && types.isSubtype(actual, types.supertype(formal))
   939                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   940                 return;
   941         }
   943     /**
   944      * Check that type 't' is a valid instantiation of a generic class
   945      * (see JLS 4.5)
   946      *
   947      * @param t class type to be checked
   948      * @return true if 't' is well-formed
   949      */
   950     public boolean checkValidGenericType(Type t) {
   951         return firstIncompatibleTypeArg(t) == null;
   952     }
   953     //WHERE
   954         private Type firstIncompatibleTypeArg(Type type) {
   955             List<Type> formals = type.tsym.type.allparams();
   956             List<Type> actuals = type.allparams();
   957             List<Type> args = type.getTypeArguments();
   958             List<Type> forms = type.tsym.type.getTypeArguments();
   959             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   961             // For matching pairs of actual argument types `a' and
   962             // formal type parameters with declared bound `b' ...
   963             while (args.nonEmpty() && forms.nonEmpty()) {
   964                 // exact type arguments needs to know their
   965                 // bounds (for upper and lower bound
   966                 // calculations).  So we create new bounds where
   967                 // type-parameters are replaced with actuals argument types.
   968                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   969                 args = args.tail;
   970                 forms = forms.tail;
   971             }
   973             args = type.getTypeArguments();
   974             List<Type> tvars_cap = types.substBounds(formals,
   975                                       formals,
   976                                       types.capture(type).allparams());
   977             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   978                 // Let the actual arguments know their bound
   979                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   980                 args = args.tail;
   981                 tvars_cap = tvars_cap.tail;
   982             }
   984             args = type.getTypeArguments();
   985             List<Type> bounds = bounds_buf.toList();
   987             while (args.nonEmpty() && bounds.nonEmpty()) {
   988                 Type actual = args.head;
   989                 if (!isTypeArgErroneous(actual) &&
   990                         !bounds.head.isErroneous() &&
   991                         !checkExtends(actual, bounds.head)) {
   992                     return args.head;
   993                 }
   994                 args = args.tail;
   995                 bounds = bounds.tail;
   996             }
   998             args = type.getTypeArguments();
   999             bounds = bounds_buf.toList();
  1001             for (Type arg : types.capture(type).getTypeArguments()) {
  1002                 if (arg.hasTag(TYPEVAR) &&
  1003                         arg.getUpperBound().isErroneous() &&
  1004                         !bounds.head.isErroneous() &&
  1005                         !isTypeArgErroneous(args.head)) {
  1006                     return args.head;
  1008                 bounds = bounds.tail;
  1009                 args = args.tail;
  1012             return null;
  1014         //where
  1015         boolean isTypeArgErroneous(Type t) {
  1016             return isTypeArgErroneous.visit(t);
  1019         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1020             public Boolean visitType(Type t, Void s) {
  1021                 return t.isErroneous();
  1023             @Override
  1024             public Boolean visitTypeVar(TypeVar t, Void s) {
  1025                 return visit(t.getUpperBound());
  1027             @Override
  1028             public Boolean visitCapturedType(CapturedType t, Void s) {
  1029                 return visit(t.getUpperBound()) ||
  1030                         visit(t.getLowerBound());
  1032             @Override
  1033             public Boolean visitWildcardType(WildcardType t, Void s) {
  1034                 return visit(t.type);
  1036         };
  1038     /** Check that given modifiers are legal for given symbol and
  1039      *  return modifiers together with any implicit modififiers for that symbol.
  1040      *  Warning: we can't use flags() here since this method
  1041      *  is called during class enter, when flags() would cause a premature
  1042      *  completion.
  1043      *  @param pos           Position to be used for error reporting.
  1044      *  @param flags         The set of modifiers given in a definition.
  1045      *  @param sym           The defined symbol.
  1046      */
  1047     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1048         long mask;
  1049         long implicit = 0;
  1050         switch (sym.kind) {
  1051         case VAR:
  1052             if (sym.owner.kind != TYP)
  1053                 mask = LocalVarFlags;
  1054             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1055                 mask = implicit = InterfaceVarFlags;
  1056             else
  1057                 mask = VarFlags;
  1058             break;
  1059         case MTH:
  1060             if (sym.name == names.init) {
  1061                 if ((sym.owner.flags_field & ENUM) != 0) {
  1062                     // enum constructors cannot be declared public or
  1063                     // protected and must be implicitly or explicitly
  1064                     // private
  1065                     implicit = PRIVATE;
  1066                     mask = PRIVATE;
  1067                 } else
  1068                     mask = ConstructorFlags;
  1069             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1070                 if ((flags & DEFAULT) != 0) {
  1071                     mask = InterfaceDefaultMethodMask;
  1072                     implicit = PUBLIC | ABSTRACT;
  1073                 } else {
  1074                     mask = implicit = InterfaceMethodFlags;
  1077             else {
  1078                 mask = MethodFlags;
  1080             // Imply STRICTFP if owner has STRICTFP set.
  1081             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1082               implicit |= sym.owner.flags_field & STRICTFP;
  1083             break;
  1084         case TYP:
  1085             if (sym.isLocal()) {
  1086                 mask = LocalClassFlags;
  1087                 if (sym.name.isEmpty()) { // Anonymous class
  1088                     // Anonymous classes in static methods are themselves static;
  1089                     // that's why we admit STATIC here.
  1090                     mask |= STATIC;
  1091                     // JLS: Anonymous classes are final.
  1092                     implicit |= FINAL;
  1094                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1095                     (flags & ENUM) != 0)
  1096                     log.error(pos, "enums.must.be.static");
  1097             } else if (sym.owner.kind == TYP) {
  1098                 mask = MemberClassFlags;
  1099                 if (sym.owner.owner.kind == PCK ||
  1100                     (sym.owner.flags_field & STATIC) != 0)
  1101                     mask |= STATIC;
  1102                 else if ((flags & ENUM) != 0)
  1103                     log.error(pos, "enums.must.be.static");
  1104                 // Nested interfaces and enums are always STATIC (Spec ???)
  1105                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1106             } else {
  1107                 mask = ClassFlags;
  1109             // Interfaces are always ABSTRACT
  1110             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1112             if ((flags & ENUM) != 0) {
  1113                 // enums can't be declared abstract or final
  1114                 mask &= ~(ABSTRACT | FINAL);
  1115                 implicit |= implicitEnumFinalFlag(tree);
  1117             // Imply STRICTFP if owner has STRICTFP set.
  1118             implicit |= sym.owner.flags_field & STRICTFP;
  1119             break;
  1120         default:
  1121             throw new AssertionError();
  1123         long illegal = flags & ExtendedStandardFlags & ~mask;
  1124         if (illegal != 0) {
  1125             if ((illegal & INTERFACE) != 0) {
  1126                 log.error(pos, "intf.not.allowed.here");
  1127                 mask |= INTERFACE;
  1129             else {
  1130                 log.error(pos,
  1131                           "mod.not.allowed.here", asFlagSet(illegal));
  1134         else if ((sym.kind == TYP ||
  1135                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1136                   // in the presence of inner classes. Should it be deleted here?
  1137                   checkDisjoint(pos, flags,
  1138                                 ABSTRACT,
  1139                                 PRIVATE | STATIC | DEFAULT))
  1140                  &&
  1141                  checkDisjoint(pos, flags,
  1142                                ABSTRACT | INTERFACE,
  1143                                FINAL | NATIVE | SYNCHRONIZED)
  1144                  &&
  1145                  checkDisjoint(pos, flags,
  1146                                PUBLIC,
  1147                                PRIVATE | PROTECTED)
  1148                  &&
  1149                  checkDisjoint(pos, flags,
  1150                                PRIVATE,
  1151                                PUBLIC | PROTECTED)
  1152                  &&
  1153                  checkDisjoint(pos, flags,
  1154                                FINAL,
  1155                                VOLATILE)
  1156                  &&
  1157                  (sym.kind == TYP ||
  1158                   checkDisjoint(pos, flags,
  1159                                 ABSTRACT | NATIVE,
  1160                                 STRICTFP))) {
  1161             // skip
  1163         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1167     /** Determine if this enum should be implicitly final.
  1169      *  If the enum has no specialized enum contants, it is final.
  1171      *  If the enum does have specialized enum contants, it is
  1172      *  <i>not</i> final.
  1173      */
  1174     private long implicitEnumFinalFlag(JCTree tree) {
  1175         if (!tree.hasTag(CLASSDEF)) return 0;
  1176         class SpecialTreeVisitor extends JCTree.Visitor {
  1177             boolean specialized;
  1178             SpecialTreeVisitor() {
  1179                 this.specialized = false;
  1180             };
  1182             @Override
  1183             public void visitTree(JCTree tree) { /* no-op */ }
  1185             @Override
  1186             public void visitVarDef(JCVariableDecl tree) {
  1187                 if ((tree.mods.flags & ENUM) != 0) {
  1188                     if (tree.init instanceof JCNewClass &&
  1189                         ((JCNewClass) tree.init).def != null) {
  1190                         specialized = true;
  1196         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1197         JCClassDecl cdef = (JCClassDecl) tree;
  1198         for (JCTree defs: cdef.defs) {
  1199             defs.accept(sts);
  1200             if (sts.specialized) return 0;
  1202         return FINAL;
  1205 /* *************************************************************************
  1206  * Type Validation
  1207  **************************************************************************/
  1209     /** Validate a type expression. That is,
  1210      *  check that all type arguments of a parametric type are within
  1211      *  their bounds. This must be done in a second phase after type attributon
  1212      *  since a class might have a subclass as type parameter bound. E.g:
  1214      *  <pre>{@code
  1215      *  class B<A extends C> { ... }
  1216      *  class C extends B<C> { ... }
  1217      *  }</pre>
  1219      *  and we can't make sure that the bound is already attributed because
  1220      *  of possible cycles.
  1222      * Visitor method: Validate a type expression, if it is not null, catching
  1223      *  and reporting any completion failures.
  1224      */
  1225     void validate(JCTree tree, Env<AttrContext> env) {
  1226         validate(tree, env, true);
  1228     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1229         new Validator(env).validateTree(tree, checkRaw, true);
  1232     /** Visitor method: Validate a list of type expressions.
  1233      */
  1234     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1235         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1236             validate(l.head, env);
  1239     /** A visitor class for type validation.
  1240      */
  1241     class Validator extends JCTree.Visitor {
  1243         boolean isOuter;
  1244         Env<AttrContext> env;
  1246         Validator(Env<AttrContext> env) {
  1247             this.env = env;
  1250         @Override
  1251         public void visitTypeArray(JCArrayTypeTree tree) {
  1252             tree.elemtype.accept(this);
  1255         @Override
  1256         public void visitTypeApply(JCTypeApply tree) {
  1257             if (tree.type.hasTag(CLASS)) {
  1258                 List<JCExpression> args = tree.arguments;
  1259                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1261                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1262                 if (incompatibleArg != null) {
  1263                     for (JCTree arg : tree.arguments) {
  1264                         if (arg.type == incompatibleArg) {
  1265                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1267                         forms = forms.tail;
  1271                 forms = tree.type.tsym.type.getTypeArguments();
  1273                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1275                 // For matching pairs of actual argument types `a' and
  1276                 // formal type parameters with declared bound `b' ...
  1277                 while (args.nonEmpty() && forms.nonEmpty()) {
  1278                     validateTree(args.head,
  1279                             !(isOuter && is_java_lang_Class),
  1280                             false);
  1281                     args = args.tail;
  1282                     forms = forms.tail;
  1285                 // Check that this type is either fully parameterized, or
  1286                 // not parameterized at all.
  1287                 if (tree.type.getEnclosingType().isRaw())
  1288                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1289                 if (tree.clazz.hasTag(SELECT))
  1290                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1294         @Override
  1295         public void visitTypeParameter(JCTypeParameter tree) {
  1296             validateTrees(tree.bounds, true, isOuter);
  1297             checkClassBounds(tree.pos(), tree.type);
  1300         @Override
  1301         public void visitWildcard(JCWildcard tree) {
  1302             if (tree.inner != null)
  1303                 validateTree(tree.inner, true, isOuter);
  1306         @Override
  1307         public void visitSelect(JCFieldAccess tree) {
  1308             if (tree.type.hasTag(CLASS)) {
  1309                 visitSelectInternal(tree);
  1311                 // Check that this type is either fully parameterized, or
  1312                 // not parameterized at all.
  1313                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1314                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1318         public void visitSelectInternal(JCFieldAccess tree) {
  1319             if (tree.type.tsym.isStatic() &&
  1320                 tree.selected.type.isParameterized()) {
  1321                 // The enclosing type is not a class, so we are
  1322                 // looking at a static member type.  However, the
  1323                 // qualifying expression is parameterized.
  1324                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1325             } else {
  1326                 // otherwise validate the rest of the expression
  1327                 tree.selected.accept(this);
  1331         /** Default visitor method: do nothing.
  1332          */
  1333         @Override
  1334         public void visitTree(JCTree tree) {
  1337         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1338             try {
  1339                 if (tree != null) {
  1340                     this.isOuter = isOuter;
  1341                     tree.accept(this);
  1342                     if (checkRaw)
  1343                         checkRaw(tree, env);
  1345             } catch (CompletionFailure ex) {
  1346                 completionError(tree.pos(), ex);
  1350         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1351             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1352                 validateTree(l.head, checkRaw, isOuter);
  1355         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1356             if (lint.isEnabled(LintCategory.RAW) &&
  1357                 tree.type.hasTag(CLASS) &&
  1358                 !TreeInfo.isDiamond(tree) &&
  1359                 !withinAnonConstr(env) &&
  1360                 tree.type.isRaw()) {
  1361                 log.warning(LintCategory.RAW,
  1362                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1366         boolean withinAnonConstr(Env<AttrContext> env) {
  1367             return env.enclClass.name.isEmpty() &&
  1368                     env.enclMethod != null && env.enclMethod.name == names.init;
  1372 /* *************************************************************************
  1373  * Exception checking
  1374  **************************************************************************/
  1376     /* The following methods treat classes as sets that contain
  1377      * the class itself and all their subclasses
  1378      */
  1380     /** Is given type a subtype of some of the types in given list?
  1381      */
  1382     boolean subset(Type t, List<Type> ts) {
  1383         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1384             if (types.isSubtype(t, l.head)) return true;
  1385         return false;
  1388     /** Is given type a subtype or supertype of
  1389      *  some of the types in given list?
  1390      */
  1391     boolean intersects(Type t, List<Type> ts) {
  1392         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1393             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1394         return false;
  1397     /** Add type set to given type list, unless it is a subclass of some class
  1398      *  in the list.
  1399      */
  1400     List<Type> incl(Type t, List<Type> ts) {
  1401         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1404     /** Remove type set from type set list.
  1405      */
  1406     List<Type> excl(Type t, List<Type> ts) {
  1407         if (ts.isEmpty()) {
  1408             return ts;
  1409         } else {
  1410             List<Type> ts1 = excl(t, ts.tail);
  1411             if (types.isSubtype(ts.head, t)) return ts1;
  1412             else if (ts1 == ts.tail) return ts;
  1413             else return ts1.prepend(ts.head);
  1417     /** Form the union of two type set lists.
  1418      */
  1419     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1420         List<Type> ts = ts1;
  1421         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1422             ts = incl(l.head, ts);
  1423         return ts;
  1426     /** Form the difference of two type lists.
  1427      */
  1428     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1429         List<Type> ts = ts1;
  1430         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1431             ts = excl(l.head, ts);
  1432         return ts;
  1435     /** Form the intersection of two type lists.
  1436      */
  1437     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1438         List<Type> ts = List.nil();
  1439         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1440             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1441         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1442             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1443         return ts;
  1446     /** Is exc an exception symbol that need not be declared?
  1447      */
  1448     boolean isUnchecked(ClassSymbol exc) {
  1449         return
  1450             exc.kind == ERR ||
  1451             exc.isSubClass(syms.errorType.tsym, types) ||
  1452             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1455     /** Is exc an exception type that need not be declared?
  1456      */
  1457     boolean isUnchecked(Type exc) {
  1458         return
  1459             (exc.hasTag(TYPEVAR)) ? isUnchecked(types.supertype(exc)) :
  1460             (exc.hasTag(CLASS)) ? isUnchecked((ClassSymbol)exc.tsym) :
  1461             exc.hasTag(BOT);
  1464     /** Same, but handling completion failures.
  1465      */
  1466     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1467         try {
  1468             return isUnchecked(exc);
  1469         } catch (CompletionFailure ex) {
  1470             completionError(pos, ex);
  1471             return true;
  1475     /** Is exc handled by given exception list?
  1476      */
  1477     boolean isHandled(Type exc, List<Type> handled) {
  1478         return isUnchecked(exc) || subset(exc, handled);
  1481     /** Return all exceptions in thrown list that are not in handled list.
  1482      *  @param thrown     The list of thrown exceptions.
  1483      *  @param handled    The list of handled exceptions.
  1484      */
  1485     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1486         List<Type> unhandled = List.nil();
  1487         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1488             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1489         return unhandled;
  1492 /* *************************************************************************
  1493  * Overriding/Implementation checking
  1494  **************************************************************************/
  1496     /** The level of access protection given by a flag set,
  1497      *  where PRIVATE is highest and PUBLIC is lowest.
  1498      */
  1499     static int protection(long flags) {
  1500         switch ((short)(flags & AccessFlags)) {
  1501         case PRIVATE: return 3;
  1502         case PROTECTED: return 1;
  1503         default:
  1504         case PUBLIC: return 0;
  1505         case 0: return 2;
  1509     /** A customized "cannot override" error message.
  1510      *  @param m      The overriding method.
  1511      *  @param other  The overridden method.
  1512      *  @return       An internationalized string.
  1513      */
  1514     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1515         String key;
  1516         if ((other.owner.flags() & INTERFACE) == 0)
  1517             key = "cant.override";
  1518         else if ((m.owner.flags() & INTERFACE) == 0)
  1519             key = "cant.implement";
  1520         else
  1521             key = "clashes.with";
  1522         return diags.fragment(key, m, m.location(), other, other.location());
  1525     /** A customized "override" warning message.
  1526      *  @param m      The overriding method.
  1527      *  @param other  The overridden method.
  1528      *  @return       An internationalized string.
  1529      */
  1530     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1531         String key;
  1532         if ((other.owner.flags() & INTERFACE) == 0)
  1533             key = "unchecked.override";
  1534         else if ((m.owner.flags() & INTERFACE) == 0)
  1535             key = "unchecked.implement";
  1536         else
  1537             key = "unchecked.clash.with";
  1538         return diags.fragment(key, m, m.location(), other, other.location());
  1541     /** A customized "override" warning message.
  1542      *  @param m      The overriding method.
  1543      *  @param other  The overridden method.
  1544      *  @return       An internationalized string.
  1545      */
  1546     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1547         String key;
  1548         if ((other.owner.flags() & INTERFACE) == 0)
  1549             key = "varargs.override";
  1550         else  if ((m.owner.flags() & INTERFACE) == 0)
  1551             key = "varargs.implement";
  1552         else
  1553             key = "varargs.clash.with";
  1554         return diags.fragment(key, m, m.location(), other, other.location());
  1557     /** Check that this method conforms with overridden method 'other'.
  1558      *  where `origin' is the class where checking started.
  1559      *  Complications:
  1560      *  (1) Do not check overriding of synthetic methods
  1561      *      (reason: they might be final).
  1562      *      todo: check whether this is still necessary.
  1563      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1564      *      than the method it implements. Augment the proxy methods with the
  1565      *      undeclared exceptions in this case.
  1566      *  (3) When generics are enabled, admit the case where an interface proxy
  1567      *      has a result type
  1568      *      extended by the result type of the method it implements.
  1569      *      Change the proxies result type to the smaller type in this case.
  1571      *  @param tree         The tree from which positions
  1572      *                      are extracted for errors.
  1573      *  @param m            The overriding method.
  1574      *  @param other        The overridden method.
  1575      *  @param origin       The class of which the overriding method
  1576      *                      is a member.
  1577      */
  1578     void checkOverride(JCTree tree,
  1579                        MethodSymbol m,
  1580                        MethodSymbol other,
  1581                        ClassSymbol origin) {
  1582         // Don't check overriding of synthetic methods or by bridge methods.
  1583         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1584             return;
  1587         // Error if static method overrides instance method (JLS 8.4.6.2).
  1588         if ((m.flags() & STATIC) != 0 &&
  1589                    (other.flags() & STATIC) == 0) {
  1590             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1591                       cannotOverride(m, other));
  1592             return;
  1595         // Error if instance method overrides static or final
  1596         // method (JLS 8.4.6.1).
  1597         if ((other.flags() & FINAL) != 0 ||
  1598                  (m.flags() & STATIC) == 0 &&
  1599                  (other.flags() & STATIC) != 0) {
  1600             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1601                       cannotOverride(m, other),
  1602                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1603             return;
  1606         if ((m.owner.flags() & ANNOTATION) != 0) {
  1607             // handled in validateAnnotationMethod
  1608             return;
  1611         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1612         if ((origin.flags() & INTERFACE) == 0 &&
  1613                  protection(m.flags()) > protection(other.flags())) {
  1614             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1615                       cannotOverride(m, other),
  1616                       other.flags() == 0 ?
  1617                           Flag.PACKAGE :
  1618                           asFlagSet(other.flags() & AccessFlags));
  1619             return;
  1622         Type mt = types.memberType(origin.type, m);
  1623         Type ot = types.memberType(origin.type, other);
  1624         // Error if overriding result type is different
  1625         // (or, in the case of generics mode, not a subtype) of
  1626         // overridden result type. We have to rename any type parameters
  1627         // before comparing types.
  1628         List<Type> mtvars = mt.getTypeArguments();
  1629         List<Type> otvars = ot.getTypeArguments();
  1630         Type mtres = mt.getReturnType();
  1631         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1633         overrideWarner.clear();
  1634         boolean resultTypesOK =
  1635             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1636         if (!resultTypesOK) {
  1637             if (!allowCovariantReturns &&
  1638                 m.owner != origin &&
  1639                 m.owner.isSubClass(other.owner, types)) {
  1640                 // allow limited interoperability with covariant returns
  1641             } else {
  1642                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1643                           "override.incompatible.ret",
  1644                           cannotOverride(m, other),
  1645                           mtres, otres);
  1646                 return;
  1648         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1649             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1650                     "override.unchecked.ret",
  1651                     uncheckedOverrides(m, other),
  1652                     mtres, otres);
  1655         // Error if overriding method throws an exception not reported
  1656         // by overridden method.
  1657         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1658         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1659         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1660         if (unhandledErased.nonEmpty()) {
  1661             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1662                       "override.meth.doesnt.throw",
  1663                       cannotOverride(m, other),
  1664                       unhandledUnerased.head);
  1665             return;
  1667         else if (unhandledUnerased.nonEmpty()) {
  1668             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1669                           "override.unchecked.thrown",
  1670                          cannotOverride(m, other),
  1671                          unhandledUnerased.head);
  1672             return;
  1675         // Optional warning if varargs don't agree
  1676         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1677             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1678             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1679                         ((m.flags() & Flags.VARARGS) != 0)
  1680                         ? "override.varargs.missing"
  1681                         : "override.varargs.extra",
  1682                         varargsOverrides(m, other));
  1685         // Warn if instance method overrides bridge method (compiler spec ??)
  1686         if ((other.flags() & BRIDGE) != 0) {
  1687             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1688                         uncheckedOverrides(m, other));
  1691         // Warn if a deprecated method overridden by a non-deprecated one.
  1692         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1693             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1696     // where
  1697         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1698             // If the method, m, is defined in an interface, then ignore the issue if the method
  1699             // is only inherited via a supertype and also implemented in the supertype,
  1700             // because in that case, we will rediscover the issue when examining the method
  1701             // in the supertype.
  1702             // If the method, m, is not defined in an interface, then the only time we need to
  1703             // address the issue is when the method is the supertype implemementation: any other
  1704             // case, we will have dealt with when examining the supertype classes
  1705             ClassSymbol mc = m.enclClass();
  1706             Type st = types.supertype(origin.type);
  1707             if (!st.hasTag(CLASS))
  1708                 return true;
  1709             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1711             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1712                 List<Type> intfs = types.interfaces(origin.type);
  1713                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1715             else
  1716                 return (stimpl != m);
  1720     // used to check if there were any unchecked conversions
  1721     Warner overrideWarner = new Warner();
  1723     /** Check that a class does not inherit two concrete methods
  1724      *  with the same signature.
  1725      *  @param pos          Position to be used for error reporting.
  1726      *  @param site         The class type to be checked.
  1727      */
  1728     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1729         Type sup = types.supertype(site);
  1730         if (!sup.hasTag(CLASS)) return;
  1732         for (Type t1 = sup;
  1733              t1.tsym.type.isParameterized();
  1734              t1 = types.supertype(t1)) {
  1735             for (Scope.Entry e1 = t1.tsym.members().elems;
  1736                  e1 != null;
  1737                  e1 = e1.sibling) {
  1738                 Symbol s1 = e1.sym;
  1739                 if (s1.kind != MTH ||
  1740                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1741                     !s1.isInheritedIn(site.tsym, types) ||
  1742                     ((MethodSymbol)s1).implementation(site.tsym,
  1743                                                       types,
  1744                                                       true) != s1)
  1745                     continue;
  1746                 Type st1 = types.memberType(t1, s1);
  1747                 int s1ArgsLength = st1.getParameterTypes().length();
  1748                 if (st1 == s1.type) continue;
  1750                 for (Type t2 = sup;
  1751                      t2.hasTag(CLASS);
  1752                      t2 = types.supertype(t2)) {
  1753                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1754                          e2.scope != null;
  1755                          e2 = e2.next()) {
  1756                         Symbol s2 = e2.sym;
  1757                         if (s2 == s1 ||
  1758                             s2.kind != MTH ||
  1759                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1760                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1761                             !s2.isInheritedIn(site.tsym, types) ||
  1762                             ((MethodSymbol)s2).implementation(site.tsym,
  1763                                                               types,
  1764                                                               true) != s2)
  1765                             continue;
  1766                         Type st2 = types.memberType(t2, s2);
  1767                         if (types.overrideEquivalent(st1, st2))
  1768                             log.error(pos, "concrete.inheritance.conflict",
  1769                                       s1, t1, s2, t2, sup);
  1776     /** Check that classes (or interfaces) do not each define an abstract
  1777      *  method with same name and arguments but incompatible return types.
  1778      *  @param pos          Position to be used for error reporting.
  1779      *  @param t1           The first argument type.
  1780      *  @param t2           The second argument type.
  1781      */
  1782     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1783                                             Type t1,
  1784                                             Type t2) {
  1785         return checkCompatibleAbstracts(pos, t1, t2,
  1786                                         types.makeCompoundType(t1, t2));
  1789     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1790                                             Type t1,
  1791                                             Type t2,
  1792                                             Type site) {
  1793         return firstIncompatibility(pos, t1, t2, site) == null;
  1796     /** Return the first method which is defined with same args
  1797      *  but different return types in two given interfaces, or null if none
  1798      *  exists.
  1799      *  @param t1     The first type.
  1800      *  @param t2     The second type.
  1801      *  @param site   The most derived type.
  1802      *  @returns symbol from t2 that conflicts with one in t1.
  1803      */
  1804     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1805         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1806         closure(t1, interfaces1);
  1807         Map<TypeSymbol,Type> interfaces2;
  1808         if (t1 == t2)
  1809             interfaces2 = interfaces1;
  1810         else
  1811             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1813         for (Type t3 : interfaces1.values()) {
  1814             for (Type t4 : interfaces2.values()) {
  1815                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1816                 if (s != null) return s;
  1819         return null;
  1822     /** Compute all the supertypes of t, indexed by type symbol. */
  1823     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1824         if (!t.hasTag(CLASS)) return;
  1825         if (typeMap.put(t.tsym, t) == null) {
  1826             closure(types.supertype(t), typeMap);
  1827             for (Type i : types.interfaces(t))
  1828                 closure(i, typeMap);
  1832     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1833     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1834         if (!t.hasTag(CLASS)) return;
  1835         if (typesSkip.get(t.tsym) != null) return;
  1836         if (typeMap.put(t.tsym, t) == null) {
  1837             closure(types.supertype(t), typesSkip, typeMap);
  1838             for (Type i : types.interfaces(t))
  1839                 closure(i, typesSkip, typeMap);
  1843     /** Return the first method in t2 that conflicts with a method from t1. */
  1844     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1845         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1846             Symbol s1 = e1.sym;
  1847             Type st1 = null;
  1848             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types) ||
  1849                     (s1.flags() & SYNTHETIC) != 0) continue;
  1850             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1851             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1852             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1853                 Symbol s2 = e2.sym;
  1854                 if (s1 == s2) continue;
  1855                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types) ||
  1856                         (s2.flags() & SYNTHETIC) != 0) continue;
  1857                 if (st1 == null) st1 = types.memberType(t1, s1);
  1858                 Type st2 = types.memberType(t2, s2);
  1859                 if (types.overrideEquivalent(st1, st2)) {
  1860                     List<Type> tvars1 = st1.getTypeArguments();
  1861                     List<Type> tvars2 = st2.getTypeArguments();
  1862                     Type rt1 = st1.getReturnType();
  1863                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1864                     boolean compat =
  1865                         types.isSameType(rt1, rt2) ||
  1866                         !rt1.isPrimitiveOrVoid() &&
  1867                         !rt2.isPrimitiveOrVoid() &&
  1868                         (types.covariantReturnType(rt1, rt2, types.noWarnings) ||
  1869                          types.covariantReturnType(rt2, rt1, types.noWarnings)) ||
  1870                          checkCommonOverriderIn(s1,s2,site);
  1871                     if (!compat) {
  1872                         log.error(pos, "types.incompatible.diff.ret",
  1873                             t1, t2, s2.name +
  1874                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1875                         return s2;
  1877                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1878                         !checkCommonOverriderIn(s1, s2, site)) {
  1879                     log.error(pos,
  1880                             "name.clash.same.erasure.no.override",
  1881                             s1, s1.location(),
  1882                             s2, s2.location());
  1883                     return s2;
  1887         return null;
  1889     //WHERE
  1890     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1891         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1892         Type st1 = types.memberType(site, s1);
  1893         Type st2 = types.memberType(site, s2);
  1894         closure(site, supertypes);
  1895         for (Type t : supertypes.values()) {
  1896             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1897                 Symbol s3 = e.sym;
  1898                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1899                 Type st3 = types.memberType(site,s3);
  1900                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1901                     if (s3.owner == site.tsym) {
  1902                         return true;
  1904                     List<Type> tvars1 = st1.getTypeArguments();
  1905                     List<Type> tvars2 = st2.getTypeArguments();
  1906                     List<Type> tvars3 = st3.getTypeArguments();
  1907                     Type rt1 = st1.getReturnType();
  1908                     Type rt2 = st2.getReturnType();
  1909                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1910                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1911                     boolean compat =
  1912                         !rt13.isPrimitiveOrVoid() &&
  1913                         !rt23.isPrimitiveOrVoid() &&
  1914                         (types.covariantReturnType(rt13, rt1, types.noWarnings) &&
  1915                          types.covariantReturnType(rt23, rt2, types.noWarnings));
  1916                     if (compat)
  1917                         return true;
  1921         return false;
  1924     /** Check that a given method conforms with any method it overrides.
  1925      *  @param tree         The tree from which positions are extracted
  1926      *                      for errors.
  1927      *  @param m            The overriding method.
  1928      */
  1929     void checkOverride(JCTree tree, MethodSymbol m) {
  1930         ClassSymbol origin = (ClassSymbol)m.owner;
  1931         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1932             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1933                 log.error(tree.pos(), "enum.no.finalize");
  1934                 return;
  1936         for (Type t = origin.type; t.hasTag(CLASS);
  1937              t = types.supertype(t)) {
  1938             if (t != origin.type) {
  1939                 checkOverride(tree, t, origin, m);
  1941             for (Type t2 : types.interfaces(t)) {
  1942                 checkOverride(tree, t2, origin, m);
  1947     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1948         TypeSymbol c = site.tsym;
  1949         Scope.Entry e = c.members().lookup(m.name);
  1950         while (e.scope != null) {
  1951             if (m.overrides(e.sym, origin, types, false)) {
  1952                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1953                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1956             e = e.next();
  1960     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1961         ClashFilter cf = new ClashFilter(origin.type);
  1962         return (cf.accepts(s1) &&
  1963                 cf.accepts(s2) &&
  1964                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1968     /** Check that all abstract members of given class have definitions.
  1969      *  @param pos          Position to be used for error reporting.
  1970      *  @param c            The class.
  1971      */
  1972     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1973         try {
  1974             MethodSymbol undef = firstUndef(c, c);
  1975             if (undef != null) {
  1976                 if ((c.flags() & ENUM) != 0 &&
  1977                     types.supertype(c.type).tsym == syms.enumSym &&
  1978                     (c.flags() & FINAL) == 0) {
  1979                     // add the ABSTRACT flag to an enum
  1980                     c.flags_field |= ABSTRACT;
  1981                 } else {
  1982                     MethodSymbol undef1 =
  1983                         new MethodSymbol(undef.flags(), undef.name,
  1984                                          types.memberType(c.type, undef), undef.owner);
  1985                     log.error(pos, "does.not.override.abstract",
  1986                               c, undef1, undef1.location());
  1989         } catch (CompletionFailure ex) {
  1990             completionError(pos, ex);
  1993 //where
  1994         /** Return first abstract member of class `c' that is not defined
  1995          *  in `impl', null if there is none.
  1996          */
  1997         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1998             MethodSymbol undef = null;
  1999             // Do not bother to search in classes that are not abstract,
  2000             // since they cannot have abstract members.
  2001             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2002                 Scope s = c.members();
  2003                 for (Scope.Entry e = s.elems;
  2004                      undef == null && e != null;
  2005                      e = e.sibling) {
  2006                     if (e.sym.kind == MTH &&
  2007                         (e.sym.flags() & (ABSTRACT|IPROXY|DEFAULT)) == ABSTRACT) {
  2008                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2009                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2010                         if (implmeth == null || implmeth == absmeth) {
  2011                             //look for default implementations
  2012                             if (allowDefaultMethods) {
  2013                                 MethodSymbol prov = types.interfaceCandidates(impl.type, absmeth).head;
  2014                                 if (prov != null && prov.overrides(absmeth, impl, types, true)) {
  2015                                     implmeth = prov;
  2019                         if (implmeth == null || implmeth == absmeth) {
  2020                             undef = absmeth;
  2024                 if (undef == null) {
  2025                     Type st = types.supertype(c.type);
  2026                     if (st.hasTag(CLASS))
  2027                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2029                 for (List<Type> l = types.interfaces(c.type);
  2030                      undef == null && l.nonEmpty();
  2031                      l = l.tail) {
  2032                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2035             return undef;
  2038     void checkNonCyclicDecl(JCClassDecl tree) {
  2039         CycleChecker cc = new CycleChecker();
  2040         cc.scan(tree);
  2041         if (!cc.errorFound && !cc.partialCheck) {
  2042             tree.sym.flags_field |= ACYCLIC;
  2046     class CycleChecker extends TreeScanner {
  2048         List<Symbol> seenClasses = List.nil();
  2049         boolean errorFound = false;
  2050         boolean partialCheck = false;
  2052         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2053             if (sym != null && sym.kind == TYP) {
  2054                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2055                 if (classEnv != null) {
  2056                     DiagnosticSource prevSource = log.currentSource();
  2057                     try {
  2058                         log.useSource(classEnv.toplevel.sourcefile);
  2059                         scan(classEnv.tree);
  2061                     finally {
  2062                         log.useSource(prevSource.getFile());
  2064                 } else if (sym.kind == TYP) {
  2065                     checkClass(pos, sym, List.<JCTree>nil());
  2067             } else {
  2068                 //not completed yet
  2069                 partialCheck = true;
  2073         @Override
  2074         public void visitSelect(JCFieldAccess tree) {
  2075             super.visitSelect(tree);
  2076             checkSymbol(tree.pos(), tree.sym);
  2079         @Override
  2080         public void visitIdent(JCIdent tree) {
  2081             checkSymbol(tree.pos(), tree.sym);
  2084         @Override
  2085         public void visitTypeApply(JCTypeApply tree) {
  2086             scan(tree.clazz);
  2089         @Override
  2090         public void visitTypeArray(JCArrayTypeTree tree) {
  2091             scan(tree.elemtype);
  2094         @Override
  2095         public void visitClassDef(JCClassDecl tree) {
  2096             List<JCTree> supertypes = List.nil();
  2097             if (tree.getExtendsClause() != null) {
  2098                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2100             if (tree.getImplementsClause() != null) {
  2101                 for (JCTree intf : tree.getImplementsClause()) {
  2102                     supertypes = supertypes.prepend(intf);
  2105             checkClass(tree.pos(), tree.sym, supertypes);
  2108         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2109             if ((c.flags_field & ACYCLIC) != 0)
  2110                 return;
  2111             if (seenClasses.contains(c)) {
  2112                 errorFound = true;
  2113                 noteCyclic(pos, (ClassSymbol)c);
  2114             } else if (!c.type.isErroneous()) {
  2115                 try {
  2116                     seenClasses = seenClasses.prepend(c);
  2117                     if (c.type.hasTag(CLASS)) {
  2118                         if (supertypes.nonEmpty()) {
  2119                             scan(supertypes);
  2121                         else {
  2122                             ClassType ct = (ClassType)c.type;
  2123                             if (ct.supertype_field == null ||
  2124                                     ct.interfaces_field == null) {
  2125                                 //not completed yet
  2126                                 partialCheck = true;
  2127                                 return;
  2129                             checkSymbol(pos, ct.supertype_field.tsym);
  2130                             for (Type intf : ct.interfaces_field) {
  2131                                 checkSymbol(pos, intf.tsym);
  2134                         if (c.owner.kind == TYP) {
  2135                             checkSymbol(pos, c.owner);
  2138                 } finally {
  2139                     seenClasses = seenClasses.tail;
  2145     /** Check for cyclic references. Issue an error if the
  2146      *  symbol of the type referred to has a LOCKED flag set.
  2148      *  @param pos      Position to be used for error reporting.
  2149      *  @param t        The type referred to.
  2150      */
  2151     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2152         checkNonCyclicInternal(pos, t);
  2156     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2157         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2160     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2161         final TypeVar tv;
  2162         if  (t.hasTag(TYPEVAR) && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2163             return;
  2164         if (seen.contains(t)) {
  2165             tv = (TypeVar)t;
  2166             tv.bound = types.createErrorType(t);
  2167             log.error(pos, "cyclic.inheritance", t);
  2168         } else if (t.hasTag(TYPEVAR)) {
  2169             tv = (TypeVar)t;
  2170             seen = seen.prepend(tv);
  2171             for (Type b : types.getBounds(tv))
  2172                 checkNonCyclic1(pos, b, seen);
  2176     /** Check for cyclic references. Issue an error if the
  2177      *  symbol of the type referred to has a LOCKED flag set.
  2179      *  @param pos      Position to be used for error reporting.
  2180      *  @param t        The type referred to.
  2181      *  @returns        True if the check completed on all attributed classes
  2182      */
  2183     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2184         boolean complete = true; // was the check complete?
  2185         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2186         Symbol c = t.tsym;
  2187         if ((c.flags_field & ACYCLIC) != 0) return true;
  2189         if ((c.flags_field & LOCKED) != 0) {
  2190             noteCyclic(pos, (ClassSymbol)c);
  2191         } else if (!c.type.isErroneous()) {
  2192             try {
  2193                 c.flags_field |= LOCKED;
  2194                 if (c.type.hasTag(CLASS)) {
  2195                     ClassType clazz = (ClassType)c.type;
  2196                     if (clazz.interfaces_field != null)
  2197                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2198                             complete &= checkNonCyclicInternal(pos, l.head);
  2199                     if (clazz.supertype_field != null) {
  2200                         Type st = clazz.supertype_field;
  2201                         if (st != null && st.hasTag(CLASS))
  2202                             complete &= checkNonCyclicInternal(pos, st);
  2204                     if (c.owner.kind == TYP)
  2205                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2207             } finally {
  2208                 c.flags_field &= ~LOCKED;
  2211         if (complete)
  2212             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2213         if (complete) c.flags_field |= ACYCLIC;
  2214         return complete;
  2217     /** Note that we found an inheritance cycle. */
  2218     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2219         log.error(pos, "cyclic.inheritance", c);
  2220         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2221             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2222         Type st = types.supertype(c.type);
  2223         if (st.hasTag(CLASS))
  2224             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2225         c.type = types.createErrorType(c, c.type);
  2226         c.flags_field |= ACYCLIC;
  2229     /**
  2230      * Check that functional interface methods would make sense when seen
  2231      * from the perspective of the implementing class
  2232      */
  2233     void checkFunctionalInterface(JCTree tree, Type funcInterface) {
  2234         ClassType c = new ClassType(Type.noType, List.<Type>nil(), null);
  2235         ClassSymbol csym = new ClassSymbol(0, names.empty, c, syms.noSymbol);
  2236         c.interfaces_field = List.of(funcInterface);
  2237         c.supertype_field = syms.objectType;
  2238         c.tsym = csym;
  2239         csym.members_field = new Scope(csym);
  2240         csym.completer = null;
  2241         checkImplementations(tree, csym, csym);
  2244     /** Check that all methods which implement some
  2245      *  method conform to the method they implement.
  2246      *  @param tree         The class definition whose members are checked.
  2247      */
  2248     void checkImplementations(JCClassDecl tree) {
  2249         checkImplementations(tree, tree.sym, tree.sym);
  2251 //where
  2252         /** Check that all methods which implement some
  2253          *  method in `ic' conform to the method they implement.
  2254          */
  2255         void checkImplementations(JCTree tree, ClassSymbol origin, ClassSymbol ic) {
  2256             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2257                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2258                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2259                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2260                         if (e.sym.kind == MTH &&
  2261                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2262                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2263                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2264                             if (implmeth != null && implmeth != absmeth &&
  2265                                 (implmeth.owner.flags() & INTERFACE) ==
  2266                                 (origin.flags() & INTERFACE)) {
  2267                                 // don't check if implmeth is in a class, yet
  2268                                 // origin is an interface. This case arises only
  2269                                 // if implmeth is declared in Object. The reason is
  2270                                 // that interfaces really don't inherit from
  2271                                 // Object it's just that the compiler represents
  2272                                 // things that way.
  2273                                 checkOverride(tree, implmeth, absmeth, origin);
  2281     /** Check that all abstract methods implemented by a class are
  2282      *  mutually compatible.
  2283      *  @param pos          Position to be used for error reporting.
  2284      *  @param c            The class whose interfaces are checked.
  2285      */
  2286     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2287         List<Type> supertypes = types.interfaces(c);
  2288         Type supertype = types.supertype(c);
  2289         if (supertype.hasTag(CLASS) &&
  2290             (supertype.tsym.flags() & ABSTRACT) != 0)
  2291             supertypes = supertypes.prepend(supertype);
  2292         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2293             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2294                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2295                 return;
  2296             for (List<Type> m = supertypes; m != l; m = m.tail)
  2297                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2298                     return;
  2300         checkCompatibleConcretes(pos, c);
  2303     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2304         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2305             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2306                 // VM allows methods and variables with differing types
  2307                 if (sym.kind == e.sym.kind &&
  2308                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2309                     sym != e.sym &&
  2310                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2311                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2312                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2313                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2314                     return;
  2320     /** Check that all non-override equivalent methods accessible from 'site'
  2321      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2323      *  @param pos  Position to be used for error reporting.
  2324      *  @param site The class whose methods are checked.
  2325      *  @param sym  The method symbol to be checked.
  2326      */
  2327     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2328          ClashFilter cf = new ClashFilter(site);
  2329         //for each method m1 that is overridden (directly or indirectly)
  2330         //by method 'sym' in 'site'...
  2331         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2332             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2333              //...check each method m2 that is a member of 'site'
  2334              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2335                 if (m2 == m1) continue;
  2336                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2337                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2338                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), allowStrictMethodClashCheck) &&
  2339                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2340                     sym.flags_field |= CLASH;
  2341                     String key = m1 == sym ?
  2342                             "name.clash.same.erasure.no.override" :
  2343                             "name.clash.same.erasure.no.override.1";
  2344                     log.error(pos,
  2345                             key,
  2346                             sym, sym.location(),
  2347                             m2, m2.location(),
  2348                             m1, m1.location());
  2349                     return;
  2357     /** Check that all static methods accessible from 'site' are
  2358      *  mutually compatible (JLS 8.4.8).
  2360      *  @param pos  Position to be used for error reporting.
  2361      *  @param site The class whose methods are checked.
  2362      *  @param sym  The method symbol to be checked.
  2363      */
  2364     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2365         ClashFilter cf = new ClashFilter(site);
  2366         //for each method m1 that is a member of 'site'...
  2367         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2368             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2369             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2370             if (!types.isSubSignature(sym.type, types.memberType(site, s), allowStrictMethodClashCheck) &&
  2371                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2372                 log.error(pos,
  2373                         "name.clash.same.erasure.no.hide",
  2374                         sym, sym.location(),
  2375                         s, s.location());
  2376                 return;
  2381      //where
  2382      private class ClashFilter implements Filter<Symbol> {
  2384          Type site;
  2386          ClashFilter(Type site) {
  2387              this.site = site;
  2390          boolean shouldSkip(Symbol s) {
  2391              return (s.flags() & CLASH) != 0 &&
  2392                 s.owner == site.tsym;
  2395          public boolean accepts(Symbol s) {
  2396              return s.kind == MTH &&
  2397                      (s.flags() & SYNTHETIC) == 0 &&
  2398                      !shouldSkip(s) &&
  2399                      s.isInheritedIn(site.tsym, types) &&
  2400                      !s.isConstructor();
  2404     void checkDefaultMethodClashes(DiagnosticPosition pos, Type site) {
  2405         DefaultMethodClashFilter dcf = new DefaultMethodClashFilter(site);
  2406         for (Symbol m : types.membersClosure(site, false).getElements(dcf)) {
  2407             Assert.check(m.kind == MTH);
  2408             List<MethodSymbol> prov = types.interfaceCandidates(site, (MethodSymbol)m);
  2409             if (prov.size() > 1) {
  2410                 ListBuffer<Symbol> abstracts = ListBuffer.lb();
  2411                 ListBuffer<Symbol> defaults = ListBuffer.lb();
  2412                 for (MethodSymbol provSym : prov) {
  2413                     if ((provSym.flags() & DEFAULT) != 0) {
  2414                         defaults = defaults.append(provSym);
  2415                     } else if ((provSym.flags() & ABSTRACT) != 0) {
  2416                         abstracts = abstracts.append(provSym);
  2418                     if (defaults.nonEmpty() && defaults.size() + abstracts.size() >= 2) {
  2419                         //strong semantics - issue an error if two sibling interfaces
  2420                         //have two override-equivalent defaults - or if one is abstract
  2421                         //and the other is default
  2422                         String errKey;
  2423                         Symbol s1 = defaults.first();
  2424                         Symbol s2;
  2425                         if (defaults.size() > 1) {
  2426                             errKey = "types.incompatible.unrelated.defaults";
  2427                             s2 = defaults.toList().tail.head;
  2428                         } else {
  2429                             errKey = "types.incompatible.abstract.default";
  2430                             s2 = abstracts.first();
  2432                         log.error(pos, errKey,
  2433                                 Kinds.kindName(site.tsym), site,
  2434                                 m.name, types.memberType(site, m).getParameterTypes(),
  2435                                 s1.location(), s2.location());
  2436                         break;
  2443     //where
  2444      private class DefaultMethodClashFilter implements Filter<Symbol> {
  2446          Type site;
  2448          DefaultMethodClashFilter(Type site) {
  2449              this.site = site;
  2452          public boolean accepts(Symbol s) {
  2453              return s.kind == MTH &&
  2454                      (s.flags() & DEFAULT) != 0 &&
  2455                      s.isInheritedIn(site.tsym, types) &&
  2456                      !s.isConstructor();
  2460     /** Report a conflict between a user symbol and a synthetic symbol.
  2461      */
  2462     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2463         if (!sym.type.isErroneous()) {
  2464             if (warnOnSyntheticConflicts) {
  2465                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2467             else {
  2468                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2473     /** Check that class c does not implement directly or indirectly
  2474      *  the same parameterized interface with two different argument lists.
  2475      *  @param pos          Position to be used for error reporting.
  2476      *  @param type         The type whose interfaces are checked.
  2477      */
  2478     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2479         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2481 //where
  2482         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2483          *  with their class symbol as key and their type as value. Make
  2484          *  sure no class is entered with two different types.
  2485          */
  2486         void checkClassBounds(DiagnosticPosition pos,
  2487                               Map<TypeSymbol,Type> seensofar,
  2488                               Type type) {
  2489             if (type.isErroneous()) return;
  2490             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2491                 Type it = l.head;
  2492                 Type oldit = seensofar.put(it.tsym, it);
  2493                 if (oldit != null) {
  2494                     List<Type> oldparams = oldit.allparams();
  2495                     List<Type> newparams = it.allparams();
  2496                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2497                         log.error(pos, "cant.inherit.diff.arg",
  2498                                   it.tsym, Type.toString(oldparams),
  2499                                   Type.toString(newparams));
  2501                 checkClassBounds(pos, seensofar, it);
  2503             Type st = types.supertype(type);
  2504             if (st != null) checkClassBounds(pos, seensofar, st);
  2507     /** Enter interface into into set.
  2508      *  If it existed already, issue a "repeated interface" error.
  2509      */
  2510     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2511         if (its.contains(it))
  2512             log.error(pos, "repeated.interface");
  2513         else {
  2514             its.add(it);
  2518 /* *************************************************************************
  2519  * Check annotations
  2520  **************************************************************************/
  2522     /**
  2523      * Recursively validate annotations values
  2524      */
  2525     void validateAnnotationTree(JCTree tree) {
  2526         class AnnotationValidator extends TreeScanner {
  2527             @Override
  2528             public void visitAnnotation(JCAnnotation tree) {
  2529                 if (!tree.type.isErroneous()) {
  2530                     super.visitAnnotation(tree);
  2531                     validateAnnotation(tree);
  2535         tree.accept(new AnnotationValidator());
  2538     /**
  2539      *  {@literal
  2540      *  Annotation types are restricted to primitives, String, an
  2541      *  enum, an annotation, Class, Class<?>, Class<? extends
  2542      *  Anything>, arrays of the preceding.
  2543      *  }
  2544      */
  2545     void validateAnnotationType(JCTree restype) {
  2546         // restype may be null if an error occurred, so don't bother validating it
  2547         if (restype != null) {
  2548             validateAnnotationType(restype.pos(), restype.type);
  2552     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2553         if (type.isPrimitive()) return;
  2554         if (types.isSameType(type, syms.stringType)) return;
  2555         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2556         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2557         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2558         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2559             validateAnnotationType(pos, types.elemtype(type));
  2560             return;
  2562         log.error(pos, "invalid.annotation.member.type");
  2565     /**
  2566      * "It is also a compile-time error if any method declared in an
  2567      * annotation type has a signature that is override-equivalent to
  2568      * that of any public or protected method declared in class Object
  2569      * or in the interface annotation.Annotation."
  2571      * @jls 9.6 Annotation Types
  2572      */
  2573     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2574         for (Type sup = syms.annotationType; sup.hasTag(CLASS); sup = types.supertype(sup)) {
  2575             Scope s = sup.tsym.members();
  2576             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2577                 if (e.sym.kind == MTH &&
  2578                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2579                     types.overrideEquivalent(m.type, e.sym.type))
  2580                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2585     /** Check the annotations of a symbol.
  2586      */
  2587     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2588         for (JCAnnotation a : annotations)
  2589             validateAnnotation(a, s);
  2592     /** Check an annotation of a symbol.
  2593      */
  2594     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2595         validateAnnotationTree(a);
  2597         if (!annotationApplicable(a, s))
  2598             log.error(a.pos(), "annotation.type.not.applicable");
  2600         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2601             if (!isOverrider(s))
  2602                 log.error(a.pos(), "method.does.not.override.superclass");
  2606     /**
  2607      * Validate the proposed container 'repeatable' on the
  2608      * annotation type symbol 's'. Report errors at position
  2609      * 'pos'.
  2611      * @param s The (annotation)type declaration annotated with a @Repeatable
  2612      * @param repeatable the @Repeatable on 's'
  2613      * @param pos where to report errors
  2614      */
  2615     public void validateRepeatable(TypeSymbol s, Attribute.Compound repeatable, DiagnosticPosition pos) {
  2616         Assert.check(types.isSameType(repeatable.type, syms.repeatableType));
  2618         Type t = null;
  2619         List<Pair<MethodSymbol,Attribute>> l = repeatable.values;
  2620         if (!l.isEmpty()) {
  2621             Assert.check(l.head.fst.name == names.value);
  2622             t = ((Attribute.Class)l.head.snd).getValue();
  2625         if (t == null) {
  2626             // errors should already have been reported during Annotate
  2627             return;
  2630         validateValue(t.tsym, s, pos);
  2631         validateRetention(t.tsym, s, pos);
  2632         validateDocumented(t.tsym, s, pos);
  2633         validateInherited(t.tsym, s, pos);
  2634         validateTarget(t.tsym, s, pos);
  2635         validateDefault(t.tsym, s, pos);
  2638     private void validateValue(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2639         Scope.Entry e = container.members().lookup(names.value);
  2640         if (e.scope != null && e.sym.kind == MTH) {
  2641             MethodSymbol m = (MethodSymbol) e.sym;
  2642             Type ret = m.getReturnType();
  2643             if (!(ret.hasTag(ARRAY) && types.isSameType(((ArrayType)ret).elemtype, contained.type))) {
  2644                 log.error(pos, "invalid.repeatable.annotation.value.return",
  2645                         container, ret, types.makeArrayType(contained.type));
  2647         } else {
  2648             log.error(pos, "invalid.repeatable.annotation.no.value", container);
  2652     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2653         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2654         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2656         boolean error = false;
  2657         switch (containedRetention) {
  2658         case RUNTIME:
  2659             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2660                 error = true;
  2662             break;
  2663         case CLASS:
  2664             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2665                 error = true;
  2668         if (error ) {
  2669             log.error(pos, "invalid.repeatable.annotation.retention",
  2670                       container, containerRetention,
  2671                       contained, containedRetention);
  2675     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2676         if (contained.attribute(syms.documentedType.tsym) != null) {
  2677             if (container.attribute(syms.documentedType.tsym) == null) {
  2678                 log.error(pos, "invalid.repeatable.annotation.not.documented", container, contained);
  2683     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2684         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2685             if (container.attribute(syms.inheritedType.tsym) == null) {
  2686                 log.error(pos, "invalid.repeatable.annotation.not.inherited", container, contained);
  2691     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2692         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2694         // If contained has no Target, we are done
  2695         if (containedTarget == null) {
  2696             return;
  2699         // If contained has Target m1, container must have a Target
  2700         // annotation, m2, and m2 must be a subset of m1. (This is
  2701         // trivially true if contained has no target as per above).
  2703         // contained has target, but container has not, error
  2704         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2705         if (containerTarget == null) {
  2706             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2707             return;
  2710         Set<Name> containerTargets = new HashSet<Name>();
  2711         for (Attribute app : containerTarget.values) {
  2712             if (!(app instanceof Attribute.Enum)) {
  2713                 continue; // recovery
  2715             Attribute.Enum e = (Attribute.Enum)app;
  2716             containerTargets.add(e.value.name);
  2719         Set<Name> containedTargets = new HashSet<Name>();
  2720         for (Attribute app : containedTarget.values) {
  2721             if (!(app instanceof Attribute.Enum)) {
  2722                 continue; // recovery
  2724             Attribute.Enum e = (Attribute.Enum)app;
  2725             containedTargets.add(e.value.name);
  2728         if (!isTargetSubset(containedTargets, containerTargets)) {
  2729             log.error(pos, "invalid.repeatable.annotation.incompatible.target", container, contained);
  2733     /** Checks that t is a subset of s, with respect to ElementType
  2734      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2735      */
  2736     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2737         // Check that all elements in t are present in s
  2738         for (Name n2 : t) {
  2739             boolean currentElementOk = false;
  2740             for (Name n1 : s) {
  2741                 if (n1 == n2) {
  2742                     currentElementOk = true;
  2743                     break;
  2744                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2745                     currentElementOk = true;
  2746                     break;
  2749             if (!currentElementOk)
  2750                 return false;
  2752         return true;
  2755     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2756         // validate that all other elements of containing type has defaults
  2757         Scope scope = container.members();
  2758         for(Symbol elm : scope.getElements()) {
  2759             if (elm.name != names.value &&
  2760                 elm.kind == Kinds.MTH &&
  2761                 ((MethodSymbol)elm).defaultValue == null) {
  2762                 log.error(pos,
  2763                           "invalid.repeatable.annotation.elem.nondefault",
  2764                           container,
  2765                           elm);
  2770     /** Is s a method symbol that overrides a method in a superclass? */
  2771     boolean isOverrider(Symbol s) {
  2772         if (s.kind != MTH || s.isStatic())
  2773             return false;
  2774         MethodSymbol m = (MethodSymbol)s;
  2775         TypeSymbol owner = (TypeSymbol)m.owner;
  2776         for (Type sup : types.closure(owner.type)) {
  2777             if (sup == owner.type)
  2778                 continue; // skip "this"
  2779             Scope scope = sup.tsym.members();
  2780             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2781                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2782                     return true;
  2785         return false;
  2788     /** Is the annotation applicable to the symbol? */
  2789     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2790         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2791         if (arr == null) {
  2792             return true;
  2794         for (Attribute app : arr.values) {
  2795             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2796             Attribute.Enum e = (Attribute.Enum) app;
  2797             if (e.value.name == names.TYPE)
  2798                 { if (s.kind == TYP) return true; }
  2799             else if (e.value.name == names.FIELD)
  2800                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2801             else if (e.value.name == names.METHOD)
  2802                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2803             else if (e.value.name == names.PARAMETER)
  2804                 { if (s.kind == VAR &&
  2805                       s.owner.kind == MTH &&
  2806                       (s.flags() & PARAMETER) != 0)
  2807                     return true;
  2809             else if (e.value.name == names.CONSTRUCTOR)
  2810                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2811             else if (e.value.name == names.LOCAL_VARIABLE)
  2812                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2813                       (s.flags() & PARAMETER) == 0)
  2814                     return true;
  2816             else if (e.value.name == names.ANNOTATION_TYPE)
  2817                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2818                     return true;
  2820             else if (e.value.name == names.PACKAGE)
  2821                 { if (s.kind == PCK) return true; }
  2822             else if (e.value.name == names.TYPE_USE)
  2823                 { if (s.kind == TYP ||
  2824                       s.kind == VAR ||
  2825                       (s.kind == MTH && !s.isConstructor() &&
  2826                        !s.type.getReturnType().hasTag(VOID)))
  2827                     return true;
  2829             else
  2830                 return true; // recovery
  2832         return false;
  2836     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2837         Attribute.Compound atTarget =
  2838             s.attribute(syms.annotationTargetType.tsym);
  2839         if (atTarget == null) return null; // ok, is applicable
  2840         Attribute atValue = atTarget.member(names.value);
  2841         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2842         return (Attribute.Array) atValue;
  2845     /** Check an annotation value.
  2847      * @param a The annotation tree to check
  2848      * @return true if this annotation tree is valid, otherwise false
  2849      */
  2850     public boolean validateAnnotationDeferErrors(JCAnnotation a) {
  2851         boolean res = false;
  2852         final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
  2853         try {
  2854             res = validateAnnotation(a);
  2855         } finally {
  2856             log.popDiagnosticHandler(diagHandler);
  2858         return res;
  2861     private boolean validateAnnotation(JCAnnotation a) {
  2862         boolean isValid = true;
  2863         // collect an inventory of the annotation elements
  2864         Set<MethodSymbol> members = new LinkedHashSet<MethodSymbol>();
  2865         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2866              e != null;
  2867              e = e.sibling)
  2868             if (e.sym.kind == MTH)
  2869                 members.add((MethodSymbol) e.sym);
  2871         // remove the ones that are assigned values
  2872         for (JCTree arg : a.args) {
  2873             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2874             JCAssign assign = (JCAssign) arg;
  2875             Symbol m = TreeInfo.symbol(assign.lhs);
  2876             if (m == null || m.type.isErroneous()) continue;
  2877             if (!members.remove(m)) {
  2878                 isValid = false;
  2879                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2880                           m.name, a.type);
  2884         // all the remaining ones better have default values
  2885         List<Name> missingDefaults = List.nil();
  2886         for (MethodSymbol m : members) {
  2887             if (m.defaultValue == null && !m.type.isErroneous()) {
  2888                 missingDefaults = missingDefaults.append(m.name);
  2891         missingDefaults = missingDefaults.reverse();
  2892         if (missingDefaults.nonEmpty()) {
  2893             isValid = false;
  2894             String key = (missingDefaults.size() > 1)
  2895                     ? "annotation.missing.default.value.1"
  2896                     : "annotation.missing.default.value";
  2897             log.error(a.pos(), key, a.type, missingDefaults);
  2900         // special case: java.lang.annotation.Target must not have
  2901         // repeated values in its value member
  2902         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2903             a.args.tail == null)
  2904             return isValid;
  2906         if (!a.args.head.hasTag(ASSIGN)) return false; // error recovery
  2907         JCAssign assign = (JCAssign) a.args.head;
  2908         Symbol m = TreeInfo.symbol(assign.lhs);
  2909         if (m.name != names.value) return false;
  2910         JCTree rhs = assign.rhs;
  2911         if (!rhs.hasTag(NEWARRAY)) return false;
  2912         JCNewArray na = (JCNewArray) rhs;
  2913         Set<Symbol> targets = new HashSet<Symbol>();
  2914         for (JCTree elem : na.elems) {
  2915             if (!targets.add(TreeInfo.symbol(elem))) {
  2916                 isValid = false;
  2917                 log.error(elem.pos(), "repeated.annotation.target");
  2920         return isValid;
  2923     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2924         if (allowAnnotations &&
  2925             lint.isEnabled(LintCategory.DEP_ANN) &&
  2926             (s.flags() & DEPRECATED) != 0 &&
  2927             !syms.deprecatedType.isErroneous() &&
  2928             s.attribute(syms.deprecatedType.tsym) == null) {
  2929             log.warning(LintCategory.DEP_ANN,
  2930                     pos, "missing.deprecated.annotation");
  2934     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2935         if ((s.flags() & DEPRECATED) != 0 &&
  2936                 (other.flags() & DEPRECATED) == 0 &&
  2937                 s.outermostClass() != other.outermostClass()) {
  2938             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2939                 @Override
  2940                 public void report() {
  2941                     warnDeprecated(pos, s);
  2943             });
  2947     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2948         if ((s.flags() & PROPRIETARY) != 0) {
  2949             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2950                 public void report() {
  2951                     if (enableSunApiLintControl)
  2952                       warnSunApi(pos, "sun.proprietary", s);
  2953                     else
  2954                       log.mandatoryWarning(pos, "sun.proprietary", s);
  2956             });
  2960 /* *************************************************************************
  2961  * Check for recursive annotation elements.
  2962  **************************************************************************/
  2964     /** Check for cycles in the graph of annotation elements.
  2965      */
  2966     void checkNonCyclicElements(JCClassDecl tree) {
  2967         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2968         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2969         try {
  2970             tree.sym.flags_field |= LOCKED;
  2971             for (JCTree def : tree.defs) {
  2972                 if (!def.hasTag(METHODDEF)) continue;
  2973                 JCMethodDecl meth = (JCMethodDecl)def;
  2974                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2976         } finally {
  2977             tree.sym.flags_field &= ~LOCKED;
  2978             tree.sym.flags_field |= ACYCLIC_ANN;
  2982     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2983         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2984             return;
  2985         if ((tsym.flags_field & LOCKED) != 0) {
  2986             log.error(pos, "cyclic.annotation.element");
  2987             return;
  2989         try {
  2990             tsym.flags_field |= LOCKED;
  2991             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2992                 Symbol s = e.sym;
  2993                 if (s.kind != Kinds.MTH)
  2994                     continue;
  2995                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2997         } finally {
  2998             tsym.flags_field &= ~LOCKED;
  2999             tsym.flags_field |= ACYCLIC_ANN;
  3003     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3004         switch (type.getTag()) {
  3005         case CLASS:
  3006             if ((type.tsym.flags() & ANNOTATION) != 0)
  3007                 checkNonCyclicElementsInternal(pos, type.tsym);
  3008             break;
  3009         case ARRAY:
  3010             checkAnnotationResType(pos, types.elemtype(type));
  3011             break;
  3012         default:
  3013             break; // int etc
  3017 /* *************************************************************************
  3018  * Check for cycles in the constructor call graph.
  3019  **************************************************************************/
  3021     /** Check for cycles in the graph of constructors calling other
  3022      *  constructors.
  3023      */
  3024     void checkCyclicConstructors(JCClassDecl tree) {
  3025         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3027         // enter each constructor this-call into the map
  3028         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3029             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3030             if (app == null) continue;
  3031             JCMethodDecl meth = (JCMethodDecl) l.head;
  3032             if (TreeInfo.name(app.meth) == names._this) {
  3033                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3034             } else {
  3035                 meth.sym.flags_field |= ACYCLIC;
  3039         // Check for cycles in the map
  3040         Symbol[] ctors = new Symbol[0];
  3041         ctors = callMap.keySet().toArray(ctors);
  3042         for (Symbol caller : ctors) {
  3043             checkCyclicConstructor(tree, caller, callMap);
  3047     /** Look in the map to see if the given constructor is part of a
  3048      *  call cycle.
  3049      */
  3050     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3051                                         Map<Symbol,Symbol> callMap) {
  3052         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3053             if ((ctor.flags_field & LOCKED) != 0) {
  3054                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3055                           "recursive.ctor.invocation");
  3056             } else {
  3057                 ctor.flags_field |= LOCKED;
  3058                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3059                 ctor.flags_field &= ~LOCKED;
  3061             ctor.flags_field |= ACYCLIC;
  3065 /* *************************************************************************
  3066  * Miscellaneous
  3067  **************************************************************************/
  3069     /**
  3070      * Return the opcode of the operator but emit an error if it is an
  3071      * error.
  3072      * @param pos        position for error reporting.
  3073      * @param operator   an operator
  3074      * @param tag        a tree tag
  3075      * @param left       type of left hand side
  3076      * @param right      type of right hand side
  3077      */
  3078     int checkOperator(DiagnosticPosition pos,
  3079                        OperatorSymbol operator,
  3080                        JCTree.Tag tag,
  3081                        Type left,
  3082                        Type right) {
  3083         if (operator.opcode == ByteCodes.error) {
  3084             log.error(pos,
  3085                       "operator.cant.be.applied.1",
  3086                       treeinfo.operatorName(tag),
  3087                       left, right);
  3089         return operator.opcode;
  3093     /**
  3094      *  Check for division by integer constant zero
  3095      *  @param pos           Position for error reporting.
  3096      *  @param operator      The operator for the expression
  3097      *  @param operand       The right hand operand for the expression
  3098      */
  3099     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3100         if (operand.constValue() != null
  3101             && lint.isEnabled(LintCategory.DIVZERO)
  3102             && (operand.getTag().isSubRangeOf(LONG))
  3103             && ((Number) (operand.constValue())).longValue() == 0) {
  3104             int opc = ((OperatorSymbol)operator).opcode;
  3105             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3106                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3107                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3112     /**
  3113      * Check for empty statements after if
  3114      */
  3115     void checkEmptyIf(JCIf tree) {
  3116         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3117                 lint.isEnabled(LintCategory.EMPTY))
  3118             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3121     /** Check that symbol is unique in given scope.
  3122      *  @param pos           Position for error reporting.
  3123      *  @param sym           The symbol.
  3124      *  @param s             The scope.
  3125      */
  3126     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3127         if (sym.type.isErroneous())
  3128             return true;
  3129         if (sym.owner.name == names.any) return false;
  3130         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3131             if (sym != e.sym &&
  3132                     (e.sym.flags() & CLASH) == 0 &&
  3133                     sym.kind == e.sym.kind &&
  3134                     sym.name != names.error &&
  3135                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3136                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3137                     varargsDuplicateError(pos, sym, e.sym);
  3138                     return true;
  3139                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3140                     duplicateErasureError(pos, sym, e.sym);
  3141                     sym.flags_field |= CLASH;
  3142                     return true;
  3143                 } else {
  3144                     duplicateError(pos, e.sym);
  3145                     return false;
  3149         return true;
  3152     /** Report duplicate declaration error.
  3153      */
  3154     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3155         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3156             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3160     /** Check that single-type import is not already imported or top-level defined,
  3161      *  but make an exception for two single-type imports which denote the same type.
  3162      *  @param pos           Position for error reporting.
  3163      *  @param sym           The symbol.
  3164      *  @param s             The scope
  3165      */
  3166     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3167         return checkUniqueImport(pos, sym, s, false);
  3170     /** Check that static single-type import is not already imported or top-level defined,
  3171      *  but make an exception for two single-type imports which denote the same type.
  3172      *  @param pos           Position for error reporting.
  3173      *  @param sym           The symbol.
  3174      *  @param s             The scope
  3175      */
  3176     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3177         return checkUniqueImport(pos, sym, s, true);
  3180     /** Check that single-type import is not already imported or top-level defined,
  3181      *  but make an exception for two single-type imports which denote the same type.
  3182      *  @param pos           Position for error reporting.
  3183      *  @param sym           The symbol.
  3184      *  @param s             The scope.
  3185      *  @param staticImport  Whether or not this was a static import
  3186      */
  3187     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3188         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3189             // is encountered class entered via a class declaration?
  3190             boolean isClassDecl = e.scope == s;
  3191             if ((isClassDecl || sym != e.sym) &&
  3192                 sym.kind == e.sym.kind &&
  3193                 sym.name != names.error) {
  3194                 if (!e.sym.type.isErroneous()) {
  3195                     String what = e.sym.toString();
  3196                     if (!isClassDecl) {
  3197                         if (staticImport)
  3198                             log.error(pos, "already.defined.static.single.import", what);
  3199                         else
  3200                             log.error(pos, "already.defined.single.import", what);
  3202                     else if (sym != e.sym)
  3203                         log.error(pos, "already.defined.this.unit", what);
  3205                 return false;
  3208         return true;
  3211     /** Check that a qualified name is in canonical form (for import decls).
  3212      */
  3213     public void checkCanonical(JCTree tree) {
  3214         if (!isCanonical(tree))
  3215             log.error(tree.pos(), "import.requires.canonical",
  3216                       TreeInfo.symbol(tree));
  3218         // where
  3219         private boolean isCanonical(JCTree tree) {
  3220             while (tree.hasTag(SELECT)) {
  3221                 JCFieldAccess s = (JCFieldAccess) tree;
  3222                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3223                     return false;
  3224                 tree = s.selected;
  3226             return true;
  3229     /** Check that an auxiliary class is not accessed from any other file than its own.
  3230      */
  3231     void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
  3232         if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
  3233             (c.flags() & AUXILIARY) != 0 &&
  3234             rs.isAccessible(env, c) &&
  3235             !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
  3237             log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
  3238                         c, c.sourcefile);
  3242     private class ConversionWarner extends Warner {
  3243         final String uncheckedKey;
  3244         final Type found;
  3245         final Type expected;
  3246         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3247             super(pos);
  3248             this.uncheckedKey = uncheckedKey;
  3249             this.found = found;
  3250             this.expected = expected;
  3253         @Override
  3254         public void warn(LintCategory lint) {
  3255             boolean warned = this.warned;
  3256             super.warn(lint);
  3257             if (warned) return; // suppress redundant diagnostics
  3258             switch (lint) {
  3259                 case UNCHECKED:
  3260                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3261                     break;
  3262                 case VARARGS:
  3263                     if (method != null &&
  3264                             method.attribute(syms.trustMeType.tsym) != null &&
  3265                             isTrustMeAllowedOnMethod(method) &&
  3266                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3267                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3269                     break;
  3270                 default:
  3271                     throw new AssertionError("Unexpected lint: " + lint);
  3276     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3277         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3280     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3281         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial