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

Wed, 17 Oct 2012 16:43:26 +0100

author
mcimadamore
date
Wed, 17 Oct 2012 16:43:26 +0100
changeset 1366
12cf6bfd8c05
parent 1358
fc123bdeddb8
child 1374
c002fdee76fd
permissions
-rw-r--r--

7192245: Add parser support for default methods
Summary: Add support for 'default' keyword in modifier position
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, 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;
    31 import com.sun.tools.javac.code.*;
    32 import com.sun.tools.javac.jvm.*;
    33 import com.sun.tools.javac.tree.*;
    34 import com.sun.tools.javac.util.*;
    35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    36 import com.sun.tools.javac.util.List;
    38 import com.sun.tools.javac.tree.JCTree.*;
    39 import com.sun.tools.javac.code.Lint;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.comp.DeferredAttr.DeferredAttrContext;
    44 import com.sun.tools.javac.comp.Infer.InferenceContext;
    45 import com.sun.tools.javac.comp.Infer.InferenceContext.FreeTypeListener;
    47 import static com.sun.tools.javac.code.Flags.*;
    48 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    49 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    50 import static com.sun.tools.javac.code.Kinds.*;
    51 import static com.sun.tools.javac.code.TypeTags.*;
    52 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
    54 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    56 /** Type checking helper class for the attribution phase.
    57  *
    58  *  <p><b>This is NOT part of any supported API.
    59  *  If you write code that depends on this, you do so at your own risk.
    60  *  This code and its internal interfaces are subject to change or
    61  *  deletion without notice.</b>
    62  */
    63 public class Check {
    64     protected static final Context.Key<Check> checkKey =
    65         new Context.Key<Check>();
    67     private final Names names;
    68     private final Log log;
    69     private final Resolve rs;
    70     private final Symtab syms;
    71     private final Enter enter;
    72     private final DeferredAttr deferredAttr;
    73     private final Infer infer;
    74     private final Types types;
    75     private final JCDiagnostic.Factory diags;
    76     private boolean warnOnSyntheticConflicts;
    77     private boolean suppressAbortOnBadClassFile;
    78     private boolean enableSunApiLintControl;
    79     private final TreeInfo treeinfo;
    81     // The set of lint options currently in effect. It is initialized
    82     // from the context, and then is set/reset as needed by Attr as it
    83     // visits all the various parts of the trees during attribution.
    84     private Lint lint;
    86     // The method being analyzed in Attr - it is set/reset as needed by
    87     // Attr as it visits new method declarations.
    88     private MethodSymbol method;
    90     public static Check instance(Context context) {
    91         Check instance = context.get(checkKey);
    92         if (instance == null)
    93             instance = new Check(context);
    94         return instance;
    95     }
    97     protected Check(Context context) {
    98         context.put(checkKey, this);
   100         names = Names.instance(context);
   101         log = Log.instance(context);
   102         rs = Resolve.instance(context);
   103         syms = Symtab.instance(context);
   104         enter = Enter.instance(context);
   105         deferredAttr = DeferredAttr.instance(context);
   106         infer = Infer.instance(context);
   107         this.types = Types.instance(context);
   108         diags = JCDiagnostic.Factory.instance(context);
   109         Options options = Options.instance(context);
   110         lint = Lint.instance(context);
   111         treeinfo = TreeInfo.instance(context);
   113         Source source = Source.instance(context);
   114         allowGenerics = source.allowGenerics();
   115         allowVarargs = source.allowVarargs();
   116         allowAnnotations = source.allowAnnotations();
   117         allowCovariantReturns = source.allowCovariantReturns();
   118         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   119         complexInference = options.isSet("complexinference");
   120         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   121         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   122         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   124         Target target = Target.instance(context);
   125         syntheticNameChar = target.syntheticNameChar();
   127         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   128         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   129         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   130         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   132         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   133                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   134         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   135                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   136         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   137                 enforceMandatoryWarnings, "sunapi", null);
   139         deferredLintHandler = DeferredLintHandler.immediateHandler;
   140     }
   142     /** Switch: generics enabled?
   143      */
   144     boolean allowGenerics;
   146     /** Switch: varargs enabled?
   147      */
   148     boolean allowVarargs;
   150     /** Switch: annotations enabled?
   151      */
   152     boolean allowAnnotations;
   154     /** Switch: covariant returns enabled?
   155      */
   156     boolean allowCovariantReturns;
   158     /** Switch: simplified varargs enabled?
   159      */
   160     boolean allowSimplifiedVarargs;
   162     /** Switch: -complexinference option set?
   163      */
   164     boolean complexInference;
   166     /** Character for synthetic names
   167      */
   168     char syntheticNameChar;
   170     /** A table mapping flat names of all compiled classes in this run to their
   171      *  symbols; maintained from outside.
   172      */
   173     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   175     /** A handler for messages about deprecated usage.
   176      */
   177     private MandatoryWarningHandler deprecationHandler;
   179     /** A handler for messages about unchecked or unsafe usage.
   180      */
   181     private MandatoryWarningHandler uncheckedHandler;
   183     /** A handler for messages about using proprietary API.
   184      */
   185     private MandatoryWarningHandler sunApiHandler;
   187     /** A handler for deferred lint warnings.
   188      */
   189     private DeferredLintHandler deferredLintHandler;
   191 /* *************************************************************************
   192  * Errors and Warnings
   193  **************************************************************************/
   195     Lint setLint(Lint newLint) {
   196         Lint prev = lint;
   197         lint = newLint;
   198         return prev;
   199     }
   201     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   202         DeferredLintHandler prev = deferredLintHandler;
   203         deferredLintHandler = newDeferredLintHandler;
   204         return prev;
   205     }
   207     MethodSymbol setMethod(MethodSymbol newMethod) {
   208         MethodSymbol prev = method;
   209         method = newMethod;
   210         return prev;
   211     }
   213     /** Warn about deprecated symbol.
   214      *  @param pos        Position to be used for error reporting.
   215      *  @param sym        The deprecated symbol.
   216      */
   217     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   218         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   219             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   220     }
   222     /** Warn about unchecked operation.
   223      *  @param pos        Position to be used for error reporting.
   224      *  @param msg        A string describing the problem.
   225      */
   226     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   227         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   228             uncheckedHandler.report(pos, msg, args);
   229     }
   231     /** Warn about unsafe vararg method decl.
   232      *  @param pos        Position to be used for error reporting.
   233      */
   234     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   235         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   236             log.warning(LintCategory.VARARGS, pos, key, args);
   237     }
   239     /** Warn about using proprietary API.
   240      *  @param pos        Position to be used for error reporting.
   241      *  @param msg        A string describing the problem.
   242      */
   243     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   244         if (!lint.isSuppressed(LintCategory.SUNAPI))
   245             sunApiHandler.report(pos, msg, args);
   246     }
   248     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   249         if (lint.isEnabled(LintCategory.STATIC))
   250             log.warning(LintCategory.STATIC, pos, msg, args);
   251     }
   253     /**
   254      * Report any deferred diagnostics.
   255      */
   256     public void reportDeferredDiagnostics() {
   257         deprecationHandler.reportDeferredDiagnostic();
   258         uncheckedHandler.reportDeferredDiagnostic();
   259         sunApiHandler.reportDeferredDiagnostic();
   260     }
   263     /** Report a failure to complete a class.
   264      *  @param pos        Position to be used for error reporting.
   265      *  @param ex         The failure to report.
   266      */
   267     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   268         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   269         if (ex instanceof ClassReader.BadClassFile
   270                 && !suppressAbortOnBadClassFile) throw new Abort();
   271         else return syms.errType;
   272     }
   274     /** Report an error that wrong type tag was found.
   275      *  @param pos        Position to be used for error reporting.
   276      *  @param required   An internationalized string describing the type tag
   277      *                    required.
   278      *  @param found      The type that was found.
   279      */
   280     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   281         // this error used to be raised by the parser,
   282         // but has been delayed to this point:
   283         if (found instanceof Type && ((Type)found).tag == VOID) {
   284             log.error(pos, "illegal.start.of.type");
   285             return syms.errType;
   286         }
   287         log.error(pos, "type.found.req", found, required);
   288         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   289     }
   291     /** Report an error that symbol cannot be referenced before super
   292      *  has been called.
   293      *  @param pos        Position to be used for error reporting.
   294      *  @param sym        The referenced symbol.
   295      */
   296     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   297         log.error(pos, "cant.ref.before.ctor.called", sym);
   298     }
   300     /** Report duplicate declaration error.
   301      */
   302     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   303         if (!sym.type.isErroneous()) {
   304             Symbol location = sym.location();
   305             if (location.kind == MTH &&
   306                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   307                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   308                         kindName(sym.location()), kindName(sym.location().enclClass()),
   309                         sym.location().enclClass());
   310             } else {
   311                 log.error(pos, "already.defined", kindName(sym), sym,
   312                         kindName(sym.location()), sym.location());
   313             }
   314         }
   315     }
   317     /** Report array/varargs duplicate declaration
   318      */
   319     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   320         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   321             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   322         }
   323     }
   325 /* ************************************************************************
   326  * duplicate declaration checking
   327  *************************************************************************/
   329     /** Check that variable does not hide variable with same name in
   330      *  immediately enclosing local scope.
   331      *  @param pos           Position for error reporting.
   332      *  @param v             The symbol.
   333      *  @param s             The scope.
   334      */
   335     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   336         if (s.next != null) {
   337             for (Scope.Entry e = s.next.lookup(v.name);
   338                  e.scope != null && e.sym.owner == v.owner;
   339                  e = e.next()) {
   340                 if (e.sym.kind == VAR &&
   341                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   342                     v.name != names.error) {
   343                     duplicateError(pos, e.sym);
   344                     return;
   345                 }
   346             }
   347         }
   348     }
   350     /** Check that a class or interface does not hide a class or
   351      *  interface with same name in immediately enclosing local scope.
   352      *  @param pos           Position for error reporting.
   353      *  @param c             The symbol.
   354      *  @param s             The scope.
   355      */
   356     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   357         if (s.next != null) {
   358             for (Scope.Entry e = s.next.lookup(c.name);
   359                  e.scope != null && e.sym.owner == c.owner;
   360                  e = e.next()) {
   361                 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
   362                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   363                     c.name != names.error) {
   364                     duplicateError(pos, e.sym);
   365                     return;
   366                 }
   367             }
   368         }
   369     }
   371     /** Check that class does not have the same name as one of
   372      *  its enclosing classes, or as a class defined in its enclosing scope.
   373      *  return true if class is unique in its enclosing scope.
   374      *  @param pos           Position for error reporting.
   375      *  @param name          The class name.
   376      *  @param s             The enclosing scope.
   377      */
   378     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   379         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   380             if (e.sym.kind == TYP && e.sym.name != names.error) {
   381                 duplicateError(pos, e.sym);
   382                 return false;
   383             }
   384         }
   385         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   386             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   387                 duplicateError(pos, sym);
   388                 return true;
   389             }
   390         }
   391         return true;
   392     }
   394 /* *************************************************************************
   395  * Class name generation
   396  **************************************************************************/
   398     /** Return name of local class.
   399      *  This is of the form   {@code <enclClass> $ n <classname> }
   400      *  where
   401      *    enclClass is the flat name of the enclosing class,
   402      *    classname is the simple name of the local class
   403      */
   404     Name localClassName(ClassSymbol c) {
   405         for (int i=1; ; i++) {
   406             Name flatname = names.
   407                 fromString("" + c.owner.enclClass().flatname +
   408                            syntheticNameChar + i +
   409                            c.name);
   410             if (compiled.get(flatname) == null) return flatname;
   411         }
   412     }
   414 /* *************************************************************************
   415  * Type Checking
   416  **************************************************************************/
   418     /**
   419      * A check context is an object that can be used to perform compatibility
   420      * checks - depending on the check context, meaning of 'compatibility' might
   421      * vary significantly.
   422      */
   423     public interface CheckContext {
   424         /**
   425          * Is type 'found' compatible with type 'req' in given context
   426          */
   427         boolean compatible(Type found, Type req, Warner warn);
   428         /**
   429          * Report a check error
   430          */
   431         void report(DiagnosticPosition pos, JCDiagnostic details);
   432         /**
   433          * Obtain a warner for this check context
   434          */
   435         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   437         public Infer.InferenceContext inferenceContext();
   439         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   441         public boolean allowBoxing();
   442     }
   444     /**
   445      * This class represent a check context that is nested within another check
   446      * context - useful to check sub-expressions. The default behavior simply
   447      * redirects all method calls to the enclosing check context leveraging
   448      * the forwarding pattern.
   449      */
   450     static class NestedCheckContext implements CheckContext {
   451         CheckContext enclosingContext;
   453         NestedCheckContext(CheckContext enclosingContext) {
   454             this.enclosingContext = enclosingContext;
   455         }
   457         public boolean compatible(Type found, Type req, Warner warn) {
   458             return enclosingContext.compatible(found, req, warn);
   459         }
   461         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   462             enclosingContext.report(pos, details);
   463         }
   465         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   466             return enclosingContext.checkWarner(pos, found, req);
   467         }
   469         public Infer.InferenceContext inferenceContext() {
   470             return enclosingContext.inferenceContext();
   471         }
   473         public DeferredAttrContext deferredAttrContext() {
   474             return enclosingContext.deferredAttrContext();
   475         }
   477         public boolean allowBoxing() {
   478             return enclosingContext.allowBoxing();
   479         }
   480     }
   482     /**
   483      * Check context to be used when evaluating assignment/return statements
   484      */
   485     CheckContext basicHandler = new CheckContext() {
   486         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   487             log.error(pos, "prob.found.req", details);
   488         }
   489         public boolean compatible(Type found, Type req, Warner warn) {
   490             return types.isAssignable(found, req, warn);
   491         }
   493         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   494             return convertWarner(pos, found, req);
   495         }
   497         public InferenceContext inferenceContext() {
   498             return infer.emptyContext;
   499         }
   501         public DeferredAttrContext deferredAttrContext() {
   502             return deferredAttr.emptyDeferredAttrContext;
   503         }
   505         public boolean allowBoxing() {
   506             return true;
   507         }
   508     };
   510     /** Check that a given type is assignable to a given proto-type.
   511      *  If it is, return the type, otherwise return errType.
   512      *  @param pos        Position to be used for error reporting.
   513      *  @param found      The type that was found.
   514      *  @param req        The type that was required.
   515      */
   516     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   517         return checkType(pos, found, req, basicHandler);
   518     }
   520     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   521         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   522         if (inferenceContext.free(req)) {
   523             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   524                 @Override
   525                 public void typesInferred(InferenceContext inferenceContext) {
   526                     checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
   527                 }
   528             });
   529         }
   530         if (req.tag == ERROR)
   531             return req;
   532         if (req.tag == NONE)
   533             return found;
   534         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   535             return found;
   536         } else {
   537             if (found.tag <= DOUBLE && req.tag <= DOUBLE) {
   538                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   539                 return types.createErrorType(found);
   540             }
   541             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   542             return types.createErrorType(found);
   543         }
   544     }
   546     /** Check that a given type can be cast to a given target type.
   547      *  Return the result of the cast.
   548      *  @param pos        Position to be used for error reporting.
   549      *  @param found      The type that is being cast.
   550      *  @param req        The target type of the cast.
   551      */
   552     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   553         return checkCastable(pos, found, req, basicHandler);
   554     }
   555     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   556         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   557             return req;
   558         } else {
   559             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   560             return types.createErrorType(found);
   561         }
   562     }
   564     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   565      * The problem should only be reported for non-292 cast
   566      */
   567     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   568         if (!tree.type.isErroneous() &&
   569                 (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   570                 && types.isSameType(tree.expr.type, tree.clazz.type)
   571                 && !is292targetTypeCast(tree)) {
   572             log.warning(Lint.LintCategory.CAST,
   573                     tree.pos(), "redundant.cast", tree.expr.type);
   574         }
   575     }
   576     //where
   577             private boolean is292targetTypeCast(JCTypeCast tree) {
   578                 boolean is292targetTypeCast = false;
   579                 JCExpression expr = TreeInfo.skipParens(tree.expr);
   580                 if (expr.hasTag(APPLY)) {
   581                     JCMethodInvocation apply = (JCMethodInvocation)expr;
   582                     Symbol sym = TreeInfo.symbol(apply.meth);
   583                     is292targetTypeCast = sym != null &&
   584                         sym.kind == MTH &&
   585                         (sym.flags() & HYPOTHETICAL) != 0;
   586                 }
   587                 return is292targetTypeCast;
   588             }
   592 //where
   593         /** Is type a type variable, or a (possibly multi-dimensional) array of
   594          *  type variables?
   595          */
   596         boolean isTypeVar(Type t) {
   597             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   598         }
   600     /** Check that a type is within some bounds.
   601      *
   602      *  Used in TypeApply to verify that, e.g., X in {@code V<X>} is a valid
   603      *  type argument.
   604      *  @param a             The type that should be bounded by bs.
   605      *  @param bound         The bound.
   606      */
   607     private boolean checkExtends(Type a, Type bound) {
   608          if (a.isUnbound()) {
   609              return true;
   610          } else if (a.tag != WILDCARD) {
   611              a = types.upperBound(a);
   612              return types.isSubtype(a, bound);
   613          } else if (a.isExtendsBound()) {
   614              return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
   615          } else if (a.isSuperBound()) {
   616              return !types.notSoftSubtype(types.lowerBound(a), bound);
   617          }
   618          return true;
   619      }
   621     /** Check that type is different from 'void'.
   622      *  @param pos           Position to be used for error reporting.
   623      *  @param t             The type to be checked.
   624      */
   625     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   626         if (t.tag == VOID) {
   627             log.error(pos, "void.not.allowed.here");
   628             return types.createErrorType(t);
   629         } else {
   630             return t;
   631         }
   632     }
   634     /** Check that type is a class or interface type.
   635      *  @param pos           Position to be used for error reporting.
   636      *  @param t             The type to be checked.
   637      */
   638     Type checkClassType(DiagnosticPosition pos, Type t) {
   639         if (t.tag != CLASS && t.tag != ERROR)
   640             return typeTagError(pos,
   641                                 diags.fragment("type.req.class"),
   642                                 (t.tag == TYPEVAR)
   643                                 ? diags.fragment("type.parameter", t)
   644                                 : t);
   645         else
   646             return t;
   647     }
   649     /** Check that type is a valid qualifier for a constructor reference expression
   650      */
   651     Type checkConstructorRefType(DiagnosticPosition pos, Type t) {
   652         t = checkClassType(pos, t);
   653         if (t.tag == CLASS) {
   654             if ((t.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) {
   655                 log.error(pos, "abstract.cant.be.instantiated");
   656                 t = types.createErrorType(t);
   657             } else if ((t.tsym.flags() & ENUM) != 0) {
   658                 log.error(pos, "enum.cant.be.instantiated");
   659                 t = types.createErrorType(t);
   660             }
   661         }
   662         return t;
   663     }
   665     /** Check that type is a class or interface type.
   666      *  @param pos           Position to be used for error reporting.
   667      *  @param t             The type to be checked.
   668      *  @param noBounds    True if type bounds are illegal here.
   669      */
   670     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   671         t = checkClassType(pos, t);
   672         if (noBounds && t.isParameterized()) {
   673             List<Type> args = t.getTypeArguments();
   674             while (args.nonEmpty()) {
   675                 if (args.head.tag == WILDCARD)
   676                     return typeTagError(pos,
   677                                         diags.fragment("type.req.exact"),
   678                                         args.head);
   679                 args = args.tail;
   680             }
   681         }
   682         return t;
   683     }
   685     /** Check that type is a reifiable class, interface or array type.
   686      *  @param pos           Position to be used for error reporting.
   687      *  @param t             The type to be checked.
   688      */
   689     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   690         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   691             return typeTagError(pos,
   692                                 diags.fragment("type.req.class.array"),
   693                                 t);
   694         } else if (!types.isReifiable(t)) {
   695             log.error(pos, "illegal.generic.type.for.instof");
   696             return types.createErrorType(t);
   697         } else {
   698             return t;
   699         }
   700     }
   702     /** Check that type is a reference type, i.e. a class, interface or array type
   703      *  or a type variable.
   704      *  @param pos           Position to be used for error reporting.
   705      *  @param t             The type to be checked.
   706      */
   707     Type checkRefType(DiagnosticPosition pos, Type t) {
   708         switch (t.tag) {
   709         case CLASS:
   710         case ARRAY:
   711         case TYPEVAR:
   712         case WILDCARD:
   713         case ERROR:
   714             return t;
   715         default:
   716             return typeTagError(pos,
   717                                 diags.fragment("type.req.ref"),
   718                                 t);
   719         }
   720     }
   722     /** Check that each type is a reference type, i.e. a class, interface or array type
   723      *  or a type variable.
   724      *  @param trees         Original trees, used for error reporting.
   725      *  @param types         The types to be checked.
   726      */
   727     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   728         List<JCExpression> tl = trees;
   729         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   730             l.head = checkRefType(tl.head.pos(), l.head);
   731             tl = tl.tail;
   732         }
   733         return types;
   734     }
   736     /** Check that type is a null or reference type.
   737      *  @param pos           Position to be used for error reporting.
   738      *  @param t             The type to be checked.
   739      */
   740     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   741         switch (t.tag) {
   742         case CLASS:
   743         case ARRAY:
   744         case TYPEVAR:
   745         case WILDCARD:
   746         case BOT:
   747         case ERROR:
   748             return t;
   749         default:
   750             return typeTagError(pos,
   751                                 diags.fragment("type.req.ref"),
   752                                 t);
   753         }
   754     }
   756     /** Check that flag set does not contain elements of two conflicting sets. s
   757      *  Return true if it doesn't.
   758      *  @param pos           Position to be used for error reporting.
   759      *  @param flags         The set of flags to be checked.
   760      *  @param set1          Conflicting flags set #1.
   761      *  @param set2          Conflicting flags set #2.
   762      */
   763     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   764         if ((flags & set1) != 0 && (flags & set2) != 0) {
   765             log.error(pos,
   766                       "illegal.combination.of.modifiers",
   767                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   768                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   769             return false;
   770         } else
   771             return true;
   772     }
   774     /** Check that usage of diamond operator is correct (i.e. diamond should not
   775      * be used with non-generic classes or in anonymous class creation expressions)
   776      */
   777     Type checkDiamond(JCNewClass tree, Type t) {
   778         if (!TreeInfo.isDiamond(tree) ||
   779                 t.isErroneous()) {
   780             return checkClassType(tree.clazz.pos(), t, true);
   781         } else if (tree.def != null) {
   782             log.error(tree.clazz.pos(),
   783                     "cant.apply.diamond.1",
   784                     t, diags.fragment("diamond.and.anon.class", t));
   785             return types.createErrorType(t);
   786         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   787             log.error(tree.clazz.pos(),
   788                 "cant.apply.diamond.1",
   789                 t, diags.fragment("diamond.non.generic", t));
   790             return types.createErrorType(t);
   791         } else if (tree.typeargs != null &&
   792                 tree.typeargs.nonEmpty()) {
   793             log.error(tree.clazz.pos(),
   794                 "cant.apply.diamond.1",
   795                 t, diags.fragment("diamond.and.explicit.params", t));
   796             return types.createErrorType(t);
   797         } else {
   798             return t;
   799         }
   800     }
   802     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   803         MethodSymbol m = tree.sym;
   804         if (!allowSimplifiedVarargs) return;
   805         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   806         Type varargElemType = null;
   807         if (m.isVarArgs()) {
   808             varargElemType = types.elemtype(tree.params.last().type);
   809         }
   810         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   811             if (varargElemType != null) {
   812                 log.error(tree,
   813                         "varargs.invalid.trustme.anno",
   814                         syms.trustMeType.tsym,
   815                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   816             } else {
   817                 log.error(tree,
   818                             "varargs.invalid.trustme.anno",
   819                             syms.trustMeType.tsym,
   820                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   821             }
   822         } else if (hasTrustMeAnno && varargElemType != null &&
   823                             types.isReifiable(varargElemType)) {
   824             warnUnsafeVararg(tree,
   825                             "varargs.redundant.trustme.anno",
   826                             syms.trustMeType.tsym,
   827                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   828         }
   829         else if (!hasTrustMeAnno && varargElemType != null &&
   830                 !types.isReifiable(varargElemType)) {
   831             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   832         }
   833     }
   834     //where
   835         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   836             return (s.flags() & VARARGS) != 0 &&
   837                 (s.isConstructor() ||
   838                     (s.flags() & (STATIC | FINAL)) != 0);
   839         }
   841     Type checkMethod(Type owntype,
   842                             Symbol sym,
   843                             Env<AttrContext> env,
   844                             final List<JCExpression> argtrees,
   845                             List<Type> argtypes,
   846                             boolean useVarargs,
   847                             boolean unchecked) {
   848         // System.out.println("call   : " + env.tree);
   849         // System.out.println("method : " + owntype);
   850         // System.out.println("actuals: " + argtypes);
   851         List<Type> formals = owntype.getParameterTypes();
   852         Type last = useVarargs ? formals.last() : null;
   853         if (sym.name==names.init &&
   854                 sym.owner == syms.enumSym)
   855                 formals = formals.tail.tail;
   856         List<JCExpression> args = argtrees;
   857         DeferredAttr.DeferredTypeMap checkDeferredMap =
   858                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   859         if (args != null) {
   860             //this is null when type-checking a method reference
   861             while (formals.head != last) {
   862                 JCTree arg = args.head;
   863                 Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   864                 assertConvertible(arg, arg.type, formals.head, warn);
   865                 args = args.tail;
   866                 formals = formals.tail;
   867             }
   868             if (useVarargs) {
   869                 Type varArg = types.elemtype(last);
   870                 while (args.tail != null) {
   871                     JCTree arg = args.head;
   872                     Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   873                     assertConvertible(arg, arg.type, varArg, warn);
   874                     args = args.tail;
   875                 }
   876             } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   877                 // non-varargs call to varargs method
   878                 Type varParam = owntype.getParameterTypes().last();
   879                 Type lastArg = checkDeferredMap.apply(argtypes.last());
   880                 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   881                         !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   882                     log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   883                             types.elemtype(varParam), varParam);
   884             }
   885         }
   886         if (unchecked) {
   887             warnUnchecked(env.tree.pos(),
   888                     "unchecked.meth.invocation.applied",
   889                     kindName(sym),
   890                     sym.name,
   891                     rs.methodArguments(sym.type.getParameterTypes()),
   892                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   893                     kindName(sym.location()),
   894                     sym.location());
   895            owntype = new MethodType(owntype.getParameterTypes(),
   896                    types.erasure(owntype.getReturnType()),
   897                    types.erasure(owntype.getThrownTypes()),
   898                    syms.methodClass);
   899         }
   900         if (useVarargs) {
   901             JCTree tree = env.tree;
   902             Type argtype = owntype.getParameterTypes().last();
   903             if (!types.isReifiable(argtype) &&
   904                     (!allowSimplifiedVarargs ||
   905                     sym.attribute(syms.trustMeType.tsym) == null ||
   906                     !isTrustMeAllowedOnMethod(sym))) {
   907                 warnUnchecked(env.tree.pos(),
   908                                   "unchecked.generic.array.creation",
   909                                   argtype);
   910             }
   911             Type elemtype = types.elemtype(argtype);
   912             switch (tree.getTag()) {
   913                 case APPLY:
   914                     ((JCMethodInvocation) tree).varargsElement = elemtype;
   915                     break;
   916                 case NEWCLASS:
   917                     ((JCNewClass) tree).varargsElement = elemtype;
   918                     break;
   919                 case REFERENCE:
   920                     ((JCMemberReference) tree).varargsElement = elemtype;
   921                     break;
   922                 default:
   923                     throw new AssertionError(""+tree);
   924             }
   925          }
   926          return owntype;
   927     }
   928     //where
   929         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   930             if (types.isConvertible(actual, formal, warn))
   931                 return;
   933             if (formal.isCompound()
   934                 && types.isSubtype(actual, types.supertype(formal))
   935                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   936                 return;
   937         }
   939         void checkAccessibleFunctionalDescriptor(DiagnosticPosition pos, Env<AttrContext> env, Type desc) {
   940             AccessChecker accessChecker = new AccessChecker(env);
   941             //check args accessibility (only if implicit parameter types)
   942             for (Type arg : desc.getParameterTypes()) {
   943                 if (!accessChecker.visit(arg)) {
   944                     log.error(pos, "cant.access.arg.type.in.functional.desc", arg);
   945                     return;
   946                 }
   947             }
   948             //check return type accessibility
   949             if (!accessChecker.visit(desc.getReturnType())) {
   950                 log.error(pos, "cant.access.return.in.functional.desc", desc.getReturnType());
   951                 return;
   952             }
   953             //check thrown types accessibility
   954             for (Type thrown : desc.getThrownTypes()) {
   955                 if (!accessChecker.visit(thrown)) {
   956                     log.error(pos, "cant.access.thrown.in.functional.desc", thrown);
   957                     return;
   958                 }
   959             }
   960         }
   962         class AccessChecker extends Types.UnaryVisitor<Boolean> {
   964             Env<AttrContext> env;
   966             AccessChecker(Env<AttrContext> env) {
   967                 this.env = env;
   968             }
   970             Boolean visit(List<Type> ts) {
   971                 for (Type t : ts) {
   972                     if (!visit(t))
   973                         return false;
   974                 }
   975                 return true;
   976             }
   978             public Boolean visitType(Type t, Void s) {
   979                 return true;
   980             }
   982             @Override
   983             public Boolean visitArrayType(ArrayType t, Void s) {
   984                 return visit(t.elemtype);
   985             }
   987             @Override
   988             public Boolean visitClassType(ClassType t, Void s) {
   989                 return rs.isAccessible(env, t, true) &&
   990                         visit(t.getTypeArguments());
   991             }
   993             @Override
   994             public Boolean visitWildcardType(WildcardType t, Void s) {
   995                 return visit(t.type);
   996             }
   997         };
   998     /**
   999      * Check that type 't' is a valid instantiation of a generic class
  1000      * (see JLS 4.5)
  1002      * @param t class type to be checked
  1003      * @return true if 't' is well-formed
  1004      */
  1005     public boolean checkValidGenericType(Type t) {
  1006         return firstIncompatibleTypeArg(t) == null;
  1008     //WHERE
  1009         private Type firstIncompatibleTypeArg(Type type) {
  1010             List<Type> formals = type.tsym.type.allparams();
  1011             List<Type> actuals = type.allparams();
  1012             List<Type> args = type.getTypeArguments();
  1013             List<Type> forms = type.tsym.type.getTypeArguments();
  1014             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
  1016             // For matching pairs of actual argument types `a' and
  1017             // formal type parameters with declared bound `b' ...
  1018             while (args.nonEmpty() && forms.nonEmpty()) {
  1019                 // exact type arguments needs to know their
  1020                 // bounds (for upper and lower bound
  1021                 // calculations).  So we create new bounds where
  1022                 // type-parameters are replaced with actuals argument types.
  1023                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
  1024                 args = args.tail;
  1025                 forms = forms.tail;
  1028             args = type.getTypeArguments();
  1029             List<Type> tvars_cap = types.substBounds(formals,
  1030                                       formals,
  1031                                       types.capture(type).allparams());
  1032             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
  1033                 // Let the actual arguments know their bound
  1034                 args.head.withTypeVar((TypeVar)tvars_cap.head);
  1035                 args = args.tail;
  1036                 tvars_cap = tvars_cap.tail;
  1039             args = type.getTypeArguments();
  1040             List<Type> bounds = bounds_buf.toList();
  1042             while (args.nonEmpty() && bounds.nonEmpty()) {
  1043                 Type actual = args.head;
  1044                 if (!isTypeArgErroneous(actual) &&
  1045                         !bounds.head.isErroneous() &&
  1046                         !checkExtends(actual, bounds.head)) {
  1047                     return args.head;
  1049                 args = args.tail;
  1050                 bounds = bounds.tail;
  1053             args = type.getTypeArguments();
  1054             bounds = bounds_buf.toList();
  1056             for (Type arg : types.capture(type).getTypeArguments()) {
  1057                 if (arg.tag == TYPEVAR &&
  1058                         arg.getUpperBound().isErroneous() &&
  1059                         !bounds.head.isErroneous() &&
  1060                         !isTypeArgErroneous(args.head)) {
  1061                     return args.head;
  1063                 bounds = bounds.tail;
  1064                 args = args.tail;
  1067             return null;
  1069         //where
  1070         boolean isTypeArgErroneous(Type t) {
  1071             return isTypeArgErroneous.visit(t);
  1074         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
  1075             public Boolean visitType(Type t, Void s) {
  1076                 return t.isErroneous();
  1078             @Override
  1079             public Boolean visitTypeVar(TypeVar t, Void s) {
  1080                 return visit(t.getUpperBound());
  1082             @Override
  1083             public Boolean visitCapturedType(CapturedType t, Void s) {
  1084                 return visit(t.getUpperBound()) ||
  1085                         visit(t.getLowerBound());
  1087             @Override
  1088             public Boolean visitWildcardType(WildcardType t, Void s) {
  1089                 return visit(t.type);
  1091         };
  1093     /** Check that given modifiers are legal for given symbol and
  1094      *  return modifiers together with any implicit modififiers for that symbol.
  1095      *  Warning: we can't use flags() here since this method
  1096      *  is called during class enter, when flags() would cause a premature
  1097      *  completion.
  1098      *  @param pos           Position to be used for error reporting.
  1099      *  @param flags         The set of modifiers given in a definition.
  1100      *  @param sym           The defined symbol.
  1101      */
  1102     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1103         long mask;
  1104         long implicit = 0;
  1105         switch (sym.kind) {
  1106         case VAR:
  1107             if (sym.owner.kind != TYP)
  1108                 mask = LocalVarFlags;
  1109             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1110                 mask = implicit = InterfaceVarFlags;
  1111             else
  1112                 mask = VarFlags;
  1113             break;
  1114         case MTH:
  1115             if (sym.name == names.init) {
  1116                 if ((sym.owner.flags_field & ENUM) != 0) {
  1117                     // enum constructors cannot be declared public or
  1118                     // protected and must be implicitly or explicitly
  1119                     // private
  1120                     implicit = PRIVATE;
  1121                     mask = PRIVATE;
  1122                 } else
  1123                     mask = ConstructorFlags;
  1124             }  else if ((sym.owner.flags_field & INTERFACE) != 0) {
  1125                 if ((flags & DEFAULT) != 0) {
  1126                     mask = InterfaceDefaultMethodMask;
  1127                     implicit = PUBLIC;
  1128                 } else {
  1129                     mask = implicit = InterfaceMethodFlags;
  1132             else {
  1133                 mask = MethodFlags;
  1135             // Imply STRICTFP if owner has STRICTFP set.
  1136             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1137               implicit |= sym.owner.flags_field & STRICTFP;
  1138             break;
  1139         case TYP:
  1140             if (sym.isLocal()) {
  1141                 mask = LocalClassFlags;
  1142                 if (sym.name.isEmpty()) { // Anonymous class
  1143                     // Anonymous classes in static methods are themselves static;
  1144                     // that's why we admit STATIC here.
  1145                     mask |= STATIC;
  1146                     // JLS: Anonymous classes are final.
  1147                     implicit |= FINAL;
  1149                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1150                     (flags & ENUM) != 0)
  1151                     log.error(pos, "enums.must.be.static");
  1152             } else if (sym.owner.kind == TYP) {
  1153                 mask = MemberClassFlags;
  1154                 if (sym.owner.owner.kind == PCK ||
  1155                     (sym.owner.flags_field & STATIC) != 0)
  1156                     mask |= STATIC;
  1157                 else if ((flags & ENUM) != 0)
  1158                     log.error(pos, "enums.must.be.static");
  1159                 // Nested interfaces and enums are always STATIC (Spec ???)
  1160                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1161             } else {
  1162                 mask = ClassFlags;
  1164             // Interfaces are always ABSTRACT
  1165             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1167             if ((flags & ENUM) != 0) {
  1168                 // enums can't be declared abstract or final
  1169                 mask &= ~(ABSTRACT | FINAL);
  1170                 implicit |= implicitEnumFinalFlag(tree);
  1172             // Imply STRICTFP if owner has STRICTFP set.
  1173             implicit |= sym.owner.flags_field & STRICTFP;
  1174             break;
  1175         default:
  1176             throw new AssertionError();
  1178         long illegal = flags & ExtendedStandardFlags & ~mask;
  1179         if (illegal != 0) {
  1180             if ((illegal & INTERFACE) != 0) {
  1181                 log.error(pos, "intf.not.allowed.here");
  1182                 mask |= INTERFACE;
  1184             else {
  1185                 log.error(pos,
  1186                           "mod.not.allowed.here", asFlagSet(illegal));
  1189         else if ((sym.kind == TYP ||
  1190                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1191                   // in the presence of inner classes. Should it be deleted here?
  1192                   checkDisjoint(pos, flags,
  1193                                 ABSTRACT,
  1194                                 PRIVATE | STATIC | DEFAULT))
  1195                  &&
  1196                  checkDisjoint(pos, flags,
  1197                                ABSTRACT | INTERFACE,
  1198                                FINAL | NATIVE | SYNCHRONIZED)
  1199                  &&
  1200                  checkDisjoint(pos, flags,
  1201                                PUBLIC,
  1202                                PRIVATE | PROTECTED)
  1203                  &&
  1204                  checkDisjoint(pos, flags,
  1205                                PRIVATE,
  1206                                PUBLIC | PROTECTED)
  1207                  &&
  1208                  checkDisjoint(pos, flags,
  1209                                FINAL,
  1210                                VOLATILE)
  1211                  &&
  1212                  (sym.kind == TYP ||
  1213                   checkDisjoint(pos, flags,
  1214                                 ABSTRACT | NATIVE,
  1215                                 STRICTFP))) {
  1216             // skip
  1218         return flags & (mask | ~ExtendedStandardFlags) | implicit;
  1222     /** Determine if this enum should be implicitly final.
  1224      *  If the enum has no specialized enum contants, it is final.
  1226      *  If the enum does have specialized enum contants, it is
  1227      *  <i>not</i> final.
  1228      */
  1229     private long implicitEnumFinalFlag(JCTree tree) {
  1230         if (!tree.hasTag(CLASSDEF)) return 0;
  1231         class SpecialTreeVisitor extends JCTree.Visitor {
  1232             boolean specialized;
  1233             SpecialTreeVisitor() {
  1234                 this.specialized = false;
  1235             };
  1237             @Override
  1238             public void visitTree(JCTree tree) { /* no-op */ }
  1240             @Override
  1241             public void visitVarDef(JCVariableDecl tree) {
  1242                 if ((tree.mods.flags & ENUM) != 0) {
  1243                     if (tree.init instanceof JCNewClass &&
  1244                         ((JCNewClass) tree.init).def != null) {
  1245                         specialized = true;
  1251         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1252         JCClassDecl cdef = (JCClassDecl) tree;
  1253         for (JCTree defs: cdef.defs) {
  1254             defs.accept(sts);
  1255             if (sts.specialized) return 0;
  1257         return FINAL;
  1260 /* *************************************************************************
  1261  * Type Validation
  1262  **************************************************************************/
  1264     /** Validate a type expression. That is,
  1265      *  check that all type arguments of a parametric type are within
  1266      *  their bounds. This must be done in a second phase after type attributon
  1267      *  since a class might have a subclass as type parameter bound. E.g:
  1269      *  <pre>{@code
  1270      *  class B<A extends C> { ... }
  1271      *  class C extends B<C> { ... }
  1272      *  }</pre>
  1274      *  and we can't make sure that the bound is already attributed because
  1275      *  of possible cycles.
  1277      * Visitor method: Validate a type expression, if it is not null, catching
  1278      *  and reporting any completion failures.
  1279      */
  1280     void validate(JCTree tree, Env<AttrContext> env) {
  1281         validate(tree, env, true);
  1283     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1284         new Validator(env).validateTree(tree, checkRaw, true);
  1287     /** Visitor method: Validate a list of type expressions.
  1288      */
  1289     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1290         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1291             validate(l.head, env);
  1294     /** A visitor class for type validation.
  1295      */
  1296     class Validator extends JCTree.Visitor {
  1298         boolean isOuter;
  1299         Env<AttrContext> env;
  1301         Validator(Env<AttrContext> env) {
  1302             this.env = env;
  1305         @Override
  1306         public void visitTypeArray(JCArrayTypeTree tree) {
  1307             tree.elemtype.accept(this);
  1310         @Override
  1311         public void visitTypeApply(JCTypeApply tree) {
  1312             if (tree.type.tag == CLASS) {
  1313                 List<JCExpression> args = tree.arguments;
  1314                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1316                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1317                 if (incompatibleArg != null) {
  1318                     for (JCTree arg : tree.arguments) {
  1319                         if (arg.type == incompatibleArg) {
  1320                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1322                         forms = forms.tail;
  1326                 forms = tree.type.tsym.type.getTypeArguments();
  1328                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1330                 // For matching pairs of actual argument types `a' and
  1331                 // formal type parameters with declared bound `b' ...
  1332                 while (args.nonEmpty() && forms.nonEmpty()) {
  1333                     validateTree(args.head,
  1334                             !(isOuter && is_java_lang_Class),
  1335                             false);
  1336                     args = args.tail;
  1337                     forms = forms.tail;
  1340                 // Check that this type is either fully parameterized, or
  1341                 // not parameterized at all.
  1342                 if (tree.type.getEnclosingType().isRaw())
  1343                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1344                 if (tree.clazz.hasTag(SELECT))
  1345                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1349         @Override
  1350         public void visitTypeParameter(JCTypeParameter tree) {
  1351             validateTrees(tree.bounds, true, isOuter);
  1352             checkClassBounds(tree.pos(), tree.type);
  1355         @Override
  1356         public void visitWildcard(JCWildcard tree) {
  1357             if (tree.inner != null)
  1358                 validateTree(tree.inner, true, isOuter);
  1361         @Override
  1362         public void visitSelect(JCFieldAccess tree) {
  1363             if (tree.type.tag == CLASS) {
  1364                 visitSelectInternal(tree);
  1366                 // Check that this type is either fully parameterized, or
  1367                 // not parameterized at all.
  1368                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1369                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1373         public void visitSelectInternal(JCFieldAccess tree) {
  1374             if (tree.type.tsym.isStatic() &&
  1375                 tree.selected.type.isParameterized()) {
  1376                 // The enclosing type is not a class, so we are
  1377                 // looking at a static member type.  However, the
  1378                 // qualifying expression is parameterized.
  1379                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1380             } else {
  1381                 // otherwise validate the rest of the expression
  1382                 tree.selected.accept(this);
  1386         /** Default visitor method: do nothing.
  1387          */
  1388         @Override
  1389         public void visitTree(JCTree tree) {
  1392         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1393             try {
  1394                 if (tree != null) {
  1395                     this.isOuter = isOuter;
  1396                     tree.accept(this);
  1397                     if (checkRaw)
  1398                         checkRaw(tree, env);
  1400             } catch (CompletionFailure ex) {
  1401                 completionError(tree.pos(), ex);
  1405         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1406             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1407                 validateTree(l.head, checkRaw, isOuter);
  1410         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1411             if (lint.isEnabled(LintCategory.RAW) &&
  1412                 tree.type.tag == CLASS &&
  1413                 !TreeInfo.isDiamond(tree) &&
  1414                 !withinAnonConstr(env) &&
  1415                 tree.type.isRaw()) {
  1416                 log.warning(LintCategory.RAW,
  1417                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1421         boolean withinAnonConstr(Env<AttrContext> env) {
  1422             return env.enclClass.name.isEmpty() &&
  1423                     env.enclMethod != null && env.enclMethod.name == names.init;
  1427 /* *************************************************************************
  1428  * Exception checking
  1429  **************************************************************************/
  1431     /* The following methods treat classes as sets that contain
  1432      * the class itself and all their subclasses
  1433      */
  1435     /** Is given type a subtype of some of the types in given list?
  1436      */
  1437     boolean subset(Type t, List<Type> ts) {
  1438         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1439             if (types.isSubtype(t, l.head)) return true;
  1440         return false;
  1443     /** Is given type a subtype or supertype of
  1444      *  some of the types in given list?
  1445      */
  1446     boolean intersects(Type t, List<Type> ts) {
  1447         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1448             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1449         return false;
  1452     /** Add type set to given type list, unless it is a subclass of some class
  1453      *  in the list.
  1454      */
  1455     List<Type> incl(Type t, List<Type> ts) {
  1456         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1459     /** Remove type set from type set list.
  1460      */
  1461     List<Type> excl(Type t, List<Type> ts) {
  1462         if (ts.isEmpty()) {
  1463             return ts;
  1464         } else {
  1465             List<Type> ts1 = excl(t, ts.tail);
  1466             if (types.isSubtype(ts.head, t)) return ts1;
  1467             else if (ts1 == ts.tail) return ts;
  1468             else return ts1.prepend(ts.head);
  1472     /** Form the union of two type set lists.
  1473      */
  1474     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1475         List<Type> ts = ts1;
  1476         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1477             ts = incl(l.head, ts);
  1478         return ts;
  1481     /** Form the difference of two type lists.
  1482      */
  1483     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1484         List<Type> ts = ts1;
  1485         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1486             ts = excl(l.head, ts);
  1487         return ts;
  1490     /** Form the intersection of two type lists.
  1491      */
  1492     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1493         List<Type> ts = List.nil();
  1494         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1495             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1496         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1497             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1498         return ts;
  1501     /** Is exc an exception symbol that need not be declared?
  1502      */
  1503     boolean isUnchecked(ClassSymbol exc) {
  1504         return
  1505             exc.kind == ERR ||
  1506             exc.isSubClass(syms.errorType.tsym, types) ||
  1507             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1510     /** Is exc an exception type that need not be declared?
  1511      */
  1512     boolean isUnchecked(Type exc) {
  1513         return
  1514             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1515             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1516             exc.tag == BOT;
  1519     /** Same, but handling completion failures.
  1520      */
  1521     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1522         try {
  1523             return isUnchecked(exc);
  1524         } catch (CompletionFailure ex) {
  1525             completionError(pos, ex);
  1526             return true;
  1530     /** Is exc handled by given exception list?
  1531      */
  1532     boolean isHandled(Type exc, List<Type> handled) {
  1533         return isUnchecked(exc) || subset(exc, handled);
  1536     /** Return all exceptions in thrown list that are not in handled list.
  1537      *  @param thrown     The list of thrown exceptions.
  1538      *  @param handled    The list of handled exceptions.
  1539      */
  1540     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1541         List<Type> unhandled = List.nil();
  1542         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1543             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1544         return unhandled;
  1547 /* *************************************************************************
  1548  * Overriding/Implementation checking
  1549  **************************************************************************/
  1551     /** The level of access protection given by a flag set,
  1552      *  where PRIVATE is highest and PUBLIC is lowest.
  1553      */
  1554     static int protection(long flags) {
  1555         switch ((short)(flags & AccessFlags)) {
  1556         case PRIVATE: return 3;
  1557         case PROTECTED: return 1;
  1558         default:
  1559         case PUBLIC: return 0;
  1560         case 0: return 2;
  1564     /** A customized "cannot override" error message.
  1565      *  @param m      The overriding method.
  1566      *  @param other  The overridden method.
  1567      *  @return       An internationalized string.
  1568      */
  1569     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1570         String key;
  1571         if ((other.owner.flags() & INTERFACE) == 0)
  1572             key = "cant.override";
  1573         else if ((m.owner.flags() & INTERFACE) == 0)
  1574             key = "cant.implement";
  1575         else
  1576             key = "clashes.with";
  1577         return diags.fragment(key, m, m.location(), other, other.location());
  1580     /** A customized "override" warning message.
  1581      *  @param m      The overriding method.
  1582      *  @param other  The overridden method.
  1583      *  @return       An internationalized string.
  1584      */
  1585     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1586         String key;
  1587         if ((other.owner.flags() & INTERFACE) == 0)
  1588             key = "unchecked.override";
  1589         else if ((m.owner.flags() & INTERFACE) == 0)
  1590             key = "unchecked.implement";
  1591         else
  1592             key = "unchecked.clash.with";
  1593         return diags.fragment(key, m, m.location(), other, other.location());
  1596     /** A customized "override" warning message.
  1597      *  @param m      The overriding method.
  1598      *  @param other  The overridden method.
  1599      *  @return       An internationalized string.
  1600      */
  1601     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1602         String key;
  1603         if ((other.owner.flags() & INTERFACE) == 0)
  1604             key = "varargs.override";
  1605         else  if ((m.owner.flags() & INTERFACE) == 0)
  1606             key = "varargs.implement";
  1607         else
  1608             key = "varargs.clash.with";
  1609         return diags.fragment(key, m, m.location(), other, other.location());
  1612     /** Check that this method conforms with overridden method 'other'.
  1613      *  where `origin' is the class where checking started.
  1614      *  Complications:
  1615      *  (1) Do not check overriding of synthetic methods
  1616      *      (reason: they might be final).
  1617      *      todo: check whether this is still necessary.
  1618      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1619      *      than the method it implements. Augment the proxy methods with the
  1620      *      undeclared exceptions in this case.
  1621      *  (3) When generics are enabled, admit the case where an interface proxy
  1622      *      has a result type
  1623      *      extended by the result type of the method it implements.
  1624      *      Change the proxies result type to the smaller type in this case.
  1626      *  @param tree         The tree from which positions
  1627      *                      are extracted for errors.
  1628      *  @param m            The overriding method.
  1629      *  @param other        The overridden method.
  1630      *  @param origin       The class of which the overriding method
  1631      *                      is a member.
  1632      */
  1633     void checkOverride(JCTree tree,
  1634                        MethodSymbol m,
  1635                        MethodSymbol other,
  1636                        ClassSymbol origin) {
  1637         // Don't check overriding of synthetic methods or by bridge methods.
  1638         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1639             return;
  1642         // Error if static method overrides instance method (JLS 8.4.6.2).
  1643         if ((m.flags() & STATIC) != 0 &&
  1644                    (other.flags() & STATIC) == 0) {
  1645             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1646                       cannotOverride(m, other));
  1647             return;
  1650         // Error if instance method overrides static or final
  1651         // method (JLS 8.4.6.1).
  1652         if ((other.flags() & FINAL) != 0 ||
  1653                  (m.flags() & STATIC) == 0 &&
  1654                  (other.flags() & STATIC) != 0) {
  1655             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1656                       cannotOverride(m, other),
  1657                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1658             return;
  1661         if ((m.owner.flags() & ANNOTATION) != 0) {
  1662             // handled in validateAnnotationMethod
  1663             return;
  1666         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1667         if ((origin.flags() & INTERFACE) == 0 &&
  1668                  protection(m.flags()) > protection(other.flags())) {
  1669             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1670                       cannotOverride(m, other),
  1671                       other.flags() == 0 ?
  1672                           Flag.PACKAGE :
  1673                           asFlagSet(other.flags() & AccessFlags));
  1674             return;
  1677         Type mt = types.memberType(origin.type, m);
  1678         Type ot = types.memberType(origin.type, other);
  1679         // Error if overriding result type is different
  1680         // (or, in the case of generics mode, not a subtype) of
  1681         // overridden result type. We have to rename any type parameters
  1682         // before comparing types.
  1683         List<Type> mtvars = mt.getTypeArguments();
  1684         List<Type> otvars = ot.getTypeArguments();
  1685         Type mtres = mt.getReturnType();
  1686         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1688         overrideWarner.clear();
  1689         boolean resultTypesOK =
  1690             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1691         if (!resultTypesOK) {
  1692             if (!allowCovariantReturns &&
  1693                 m.owner != origin &&
  1694                 m.owner.isSubClass(other.owner, types)) {
  1695                 // allow limited interoperability with covariant returns
  1696             } else {
  1697                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1698                           "override.incompatible.ret",
  1699                           cannotOverride(m, other),
  1700                           mtres, otres);
  1701                 return;
  1703         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1704             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1705                     "override.unchecked.ret",
  1706                     uncheckedOverrides(m, other),
  1707                     mtres, otres);
  1710         // Error if overriding method throws an exception not reported
  1711         // by overridden method.
  1712         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1713         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1714         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1715         if (unhandledErased.nonEmpty()) {
  1716             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1717                       "override.meth.doesnt.throw",
  1718                       cannotOverride(m, other),
  1719                       unhandledUnerased.head);
  1720             return;
  1722         else if (unhandledUnerased.nonEmpty()) {
  1723             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1724                           "override.unchecked.thrown",
  1725                          cannotOverride(m, other),
  1726                          unhandledUnerased.head);
  1727             return;
  1730         // Optional warning if varargs don't agree
  1731         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1732             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1733             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1734                         ((m.flags() & Flags.VARARGS) != 0)
  1735                         ? "override.varargs.missing"
  1736                         : "override.varargs.extra",
  1737                         varargsOverrides(m, other));
  1740         // Warn if instance method overrides bridge method (compiler spec ??)
  1741         if ((other.flags() & BRIDGE) != 0) {
  1742             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1743                         uncheckedOverrides(m, other));
  1746         // Warn if a deprecated method overridden by a non-deprecated one.
  1747         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1748             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1751     // where
  1752         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1753             // If the method, m, is defined in an interface, then ignore the issue if the method
  1754             // is only inherited via a supertype and also implemented in the supertype,
  1755             // because in that case, we will rediscover the issue when examining the method
  1756             // in the supertype.
  1757             // If the method, m, is not defined in an interface, then the only time we need to
  1758             // address the issue is when the method is the supertype implemementation: any other
  1759             // case, we will have dealt with when examining the supertype classes
  1760             ClassSymbol mc = m.enclClass();
  1761             Type st = types.supertype(origin.type);
  1762             if (st.tag != CLASS)
  1763                 return true;
  1764             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1766             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1767                 List<Type> intfs = types.interfaces(origin.type);
  1768                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1770             else
  1771                 return (stimpl != m);
  1775     // used to check if there were any unchecked conversions
  1776     Warner overrideWarner = new Warner();
  1778     /** Check that a class does not inherit two concrete methods
  1779      *  with the same signature.
  1780      *  @param pos          Position to be used for error reporting.
  1781      *  @param site         The class type to be checked.
  1782      */
  1783     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1784         Type sup = types.supertype(site);
  1785         if (sup.tag != CLASS) return;
  1787         for (Type t1 = sup;
  1788              t1.tsym.type.isParameterized();
  1789              t1 = types.supertype(t1)) {
  1790             for (Scope.Entry e1 = t1.tsym.members().elems;
  1791                  e1 != null;
  1792                  e1 = e1.sibling) {
  1793                 Symbol s1 = e1.sym;
  1794                 if (s1.kind != MTH ||
  1795                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1796                     !s1.isInheritedIn(site.tsym, types) ||
  1797                     ((MethodSymbol)s1).implementation(site.tsym,
  1798                                                       types,
  1799                                                       true) != s1)
  1800                     continue;
  1801                 Type st1 = types.memberType(t1, s1);
  1802                 int s1ArgsLength = st1.getParameterTypes().length();
  1803                 if (st1 == s1.type) continue;
  1805                 for (Type t2 = sup;
  1806                      t2.tag == CLASS;
  1807                      t2 = types.supertype(t2)) {
  1808                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1809                          e2.scope != null;
  1810                          e2 = e2.next()) {
  1811                         Symbol s2 = e2.sym;
  1812                         if (s2 == s1 ||
  1813                             s2.kind != MTH ||
  1814                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1815                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1816                             !s2.isInheritedIn(site.tsym, types) ||
  1817                             ((MethodSymbol)s2).implementation(site.tsym,
  1818                                                               types,
  1819                                                               true) != s2)
  1820                             continue;
  1821                         Type st2 = types.memberType(t2, s2);
  1822                         if (types.overrideEquivalent(st1, st2))
  1823                             log.error(pos, "concrete.inheritance.conflict",
  1824                                       s1, t1, s2, t2, sup);
  1831     /** Check that classes (or interfaces) do not each define an abstract
  1832      *  method with same name and arguments but incompatible return types.
  1833      *  @param pos          Position to be used for error reporting.
  1834      *  @param t1           The first argument type.
  1835      *  @param t2           The second argument type.
  1836      */
  1837     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1838                                             Type t1,
  1839                                             Type t2) {
  1840         return checkCompatibleAbstracts(pos, t1, t2,
  1841                                         types.makeCompoundType(t1, t2));
  1844     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1845                                             Type t1,
  1846                                             Type t2,
  1847                                             Type site) {
  1848         return firstIncompatibility(pos, t1, t2, site) == null;
  1851     /** Return the first method which is defined with same args
  1852      *  but different return types in two given interfaces, or null if none
  1853      *  exists.
  1854      *  @param t1     The first type.
  1855      *  @param t2     The second type.
  1856      *  @param site   The most derived type.
  1857      *  @returns symbol from t2 that conflicts with one in t1.
  1858      */
  1859     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1860         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1861         closure(t1, interfaces1);
  1862         Map<TypeSymbol,Type> interfaces2;
  1863         if (t1 == t2)
  1864             interfaces2 = interfaces1;
  1865         else
  1866             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1868         for (Type t3 : interfaces1.values()) {
  1869             for (Type t4 : interfaces2.values()) {
  1870                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1871                 if (s != null) return s;
  1874         return null;
  1877     /** Compute all the supertypes of t, indexed by type symbol. */
  1878     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1879         if (t.tag != CLASS) return;
  1880         if (typeMap.put(t.tsym, t) == null) {
  1881             closure(types.supertype(t), typeMap);
  1882             for (Type i : types.interfaces(t))
  1883                 closure(i, typeMap);
  1887     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1888     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1889         if (t.tag != CLASS) return;
  1890         if (typesSkip.get(t.tsym) != null) return;
  1891         if (typeMap.put(t.tsym, t) == null) {
  1892             closure(types.supertype(t), typesSkip, typeMap);
  1893             for (Type i : types.interfaces(t))
  1894                 closure(i, typesSkip, typeMap);
  1898     /** Return the first method in t2 that conflicts with a method from t1. */
  1899     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1900         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1901             Symbol s1 = e1.sym;
  1902             Type st1 = null;
  1903             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1904             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1905             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1906             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1907                 Symbol s2 = e2.sym;
  1908                 if (s1 == s2) continue;
  1909                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1910                 if (st1 == null) st1 = types.memberType(t1, s1);
  1911                 Type st2 = types.memberType(t2, s2);
  1912                 if (types.overrideEquivalent(st1, st2)) {
  1913                     List<Type> tvars1 = st1.getTypeArguments();
  1914                     List<Type> tvars2 = st2.getTypeArguments();
  1915                     Type rt1 = st1.getReturnType();
  1916                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1917                     boolean compat =
  1918                         types.isSameType(rt1, rt2) ||
  1919                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1920                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1921                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1922                          checkCommonOverriderIn(s1,s2,site);
  1923                     if (!compat) {
  1924                         log.error(pos, "types.incompatible.diff.ret",
  1925                             t1, t2, s2.name +
  1926                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1927                         return s2;
  1929                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1930                         !checkCommonOverriderIn(s1, s2, site)) {
  1931                     log.error(pos,
  1932                             "name.clash.same.erasure.no.override",
  1933                             s1, s1.location(),
  1934                             s2, s2.location());
  1935                     return s2;
  1939         return null;
  1941     //WHERE
  1942     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1943         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1944         Type st1 = types.memberType(site, s1);
  1945         Type st2 = types.memberType(site, s2);
  1946         closure(site, supertypes);
  1947         for (Type t : supertypes.values()) {
  1948             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1949                 Symbol s3 = e.sym;
  1950                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1951                 Type st3 = types.memberType(site,s3);
  1952                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1953                     if (s3.owner == site.tsym) {
  1954                         return true;
  1956                     List<Type> tvars1 = st1.getTypeArguments();
  1957                     List<Type> tvars2 = st2.getTypeArguments();
  1958                     List<Type> tvars3 = st3.getTypeArguments();
  1959                     Type rt1 = st1.getReturnType();
  1960                     Type rt2 = st2.getReturnType();
  1961                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1962                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1963                     boolean compat =
  1964                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1965                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1966                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1967                     if (compat)
  1968                         return true;
  1972         return false;
  1975     /** Check that a given method conforms with any method it overrides.
  1976      *  @param tree         The tree from which positions are extracted
  1977      *                      for errors.
  1978      *  @param m            The overriding method.
  1979      */
  1980     void checkOverride(JCTree tree, MethodSymbol m) {
  1981         ClassSymbol origin = (ClassSymbol)m.owner;
  1982         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1983             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1984                 log.error(tree.pos(), "enum.no.finalize");
  1985                 return;
  1987         for (Type t = origin.type; t.tag == CLASS;
  1988              t = types.supertype(t)) {
  1989             if (t != origin.type) {
  1990                 checkOverride(tree, t, origin, m);
  1992             for (Type t2 : types.interfaces(t)) {
  1993                 checkOverride(tree, t2, origin, m);
  1998     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1999         TypeSymbol c = site.tsym;
  2000         Scope.Entry e = c.members().lookup(m.name);
  2001         while (e.scope != null) {
  2002             if (m.overrides(e.sym, origin, types, false)) {
  2003                 if ((e.sym.flags() & ABSTRACT) == 0) {
  2004                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  2007             e = e.next();
  2011     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  2012         ClashFilter cf = new ClashFilter(origin.type);
  2013         return (cf.accepts(s1) &&
  2014                 cf.accepts(s2) &&
  2015                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  2019     /** Check that all abstract members of given class have definitions.
  2020      *  @param pos          Position to be used for error reporting.
  2021      *  @param c            The class.
  2022      */
  2023     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  2024         try {
  2025             MethodSymbol undef = firstUndef(c, c);
  2026             if (undef != null) {
  2027                 if ((c.flags() & ENUM) != 0 &&
  2028                     types.supertype(c.type).tsym == syms.enumSym &&
  2029                     (c.flags() & FINAL) == 0) {
  2030                     // add the ABSTRACT flag to an enum
  2031                     c.flags_field |= ABSTRACT;
  2032                 } else {
  2033                     MethodSymbol undef1 =
  2034                         new MethodSymbol(undef.flags(), undef.name,
  2035                                          types.memberType(c.type, undef), undef.owner);
  2036                     log.error(pos, "does.not.override.abstract",
  2037                               c, undef1, undef1.location());
  2040         } catch (CompletionFailure ex) {
  2041             completionError(pos, ex);
  2044 //where
  2045         /** Return first abstract member of class `c' that is not defined
  2046          *  in `impl', null if there is none.
  2047          */
  2048         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  2049             MethodSymbol undef = null;
  2050             // Do not bother to search in classes that are not abstract,
  2051             // since they cannot have abstract members.
  2052             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  2053                 Scope s = c.members();
  2054                 for (Scope.Entry e = s.elems;
  2055                      undef == null && e != null;
  2056                      e = e.sibling) {
  2057                     if (e.sym.kind == MTH &&
  2058                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  2059                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  2060                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  2061                         if (implmeth == null || implmeth == absmeth)
  2062                             undef = absmeth;
  2065                 if (undef == null) {
  2066                     Type st = types.supertype(c.type);
  2067                     if (st.tag == CLASS)
  2068                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  2070                 for (List<Type> l = types.interfaces(c.type);
  2071                      undef == null && l.nonEmpty();
  2072                      l = l.tail) {
  2073                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  2076             return undef;
  2079     void checkNonCyclicDecl(JCClassDecl tree) {
  2080         CycleChecker cc = new CycleChecker();
  2081         cc.scan(tree);
  2082         if (!cc.errorFound && !cc.partialCheck) {
  2083             tree.sym.flags_field |= ACYCLIC;
  2087     class CycleChecker extends TreeScanner {
  2089         List<Symbol> seenClasses = List.nil();
  2090         boolean errorFound = false;
  2091         boolean partialCheck = false;
  2093         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  2094             if (sym != null && sym.kind == TYP) {
  2095                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  2096                 if (classEnv != null) {
  2097                     DiagnosticSource prevSource = log.currentSource();
  2098                     try {
  2099                         log.useSource(classEnv.toplevel.sourcefile);
  2100                         scan(classEnv.tree);
  2102                     finally {
  2103                         log.useSource(prevSource.getFile());
  2105                 } else if (sym.kind == TYP) {
  2106                     checkClass(pos, sym, List.<JCTree>nil());
  2108             } else {
  2109                 //not completed yet
  2110                 partialCheck = true;
  2114         @Override
  2115         public void visitSelect(JCFieldAccess tree) {
  2116             super.visitSelect(tree);
  2117             checkSymbol(tree.pos(), tree.sym);
  2120         @Override
  2121         public void visitIdent(JCIdent tree) {
  2122             checkSymbol(tree.pos(), tree.sym);
  2125         @Override
  2126         public void visitTypeApply(JCTypeApply tree) {
  2127             scan(tree.clazz);
  2130         @Override
  2131         public void visitTypeArray(JCArrayTypeTree tree) {
  2132             scan(tree.elemtype);
  2135         @Override
  2136         public void visitClassDef(JCClassDecl tree) {
  2137             List<JCTree> supertypes = List.nil();
  2138             if (tree.getExtendsClause() != null) {
  2139                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2141             if (tree.getImplementsClause() != null) {
  2142                 for (JCTree intf : tree.getImplementsClause()) {
  2143                     supertypes = supertypes.prepend(intf);
  2146             checkClass(tree.pos(), tree.sym, supertypes);
  2149         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2150             if ((c.flags_field & ACYCLIC) != 0)
  2151                 return;
  2152             if (seenClasses.contains(c)) {
  2153                 errorFound = true;
  2154                 noteCyclic(pos, (ClassSymbol)c);
  2155             } else if (!c.type.isErroneous()) {
  2156                 try {
  2157                     seenClasses = seenClasses.prepend(c);
  2158                     if (c.type.tag == CLASS) {
  2159                         if (supertypes.nonEmpty()) {
  2160                             scan(supertypes);
  2162                         else {
  2163                             ClassType ct = (ClassType)c.type;
  2164                             if (ct.supertype_field == null ||
  2165                                     ct.interfaces_field == null) {
  2166                                 //not completed yet
  2167                                 partialCheck = true;
  2168                                 return;
  2170                             checkSymbol(pos, ct.supertype_field.tsym);
  2171                             for (Type intf : ct.interfaces_field) {
  2172                                 checkSymbol(pos, intf.tsym);
  2175                         if (c.owner.kind == TYP) {
  2176                             checkSymbol(pos, c.owner);
  2179                 } finally {
  2180                     seenClasses = seenClasses.tail;
  2186     /** Check for cyclic references. Issue an error if the
  2187      *  symbol of the type referred to has a LOCKED flag set.
  2189      *  @param pos      Position to be used for error reporting.
  2190      *  @param t        The type referred to.
  2191      */
  2192     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2193         checkNonCyclicInternal(pos, t);
  2197     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2198         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2201     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2202         final TypeVar tv;
  2203         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2204             return;
  2205         if (seen.contains(t)) {
  2206             tv = (TypeVar)t;
  2207             tv.bound = types.createErrorType(t);
  2208             log.error(pos, "cyclic.inheritance", t);
  2209         } else if (t.tag == TYPEVAR) {
  2210             tv = (TypeVar)t;
  2211             seen = seen.prepend(tv);
  2212             for (Type b : types.getBounds(tv))
  2213                 checkNonCyclic1(pos, b, seen);
  2217     /** Check for cyclic references. Issue an error if the
  2218      *  symbol of the type referred to has a LOCKED flag set.
  2220      *  @param pos      Position to be used for error reporting.
  2221      *  @param t        The type referred to.
  2222      *  @returns        True if the check completed on all attributed classes
  2223      */
  2224     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2225         boolean complete = true; // was the check complete?
  2226         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2227         Symbol c = t.tsym;
  2228         if ((c.flags_field & ACYCLIC) != 0) return true;
  2230         if ((c.flags_field & LOCKED) != 0) {
  2231             noteCyclic(pos, (ClassSymbol)c);
  2232         } else if (!c.type.isErroneous()) {
  2233             try {
  2234                 c.flags_field |= LOCKED;
  2235                 if (c.type.tag == CLASS) {
  2236                     ClassType clazz = (ClassType)c.type;
  2237                     if (clazz.interfaces_field != null)
  2238                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2239                             complete &= checkNonCyclicInternal(pos, l.head);
  2240                     if (clazz.supertype_field != null) {
  2241                         Type st = clazz.supertype_field;
  2242                         if (st != null && st.tag == CLASS)
  2243                             complete &= checkNonCyclicInternal(pos, st);
  2245                     if (c.owner.kind == TYP)
  2246                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2248             } finally {
  2249                 c.flags_field &= ~LOCKED;
  2252         if (complete)
  2253             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2254         if (complete) c.flags_field |= ACYCLIC;
  2255         return complete;
  2258     /** Note that we found an inheritance cycle. */
  2259     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2260         log.error(pos, "cyclic.inheritance", c);
  2261         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2262             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2263         Type st = types.supertype(c.type);
  2264         if (st.tag == CLASS)
  2265             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2266         c.type = types.createErrorType(c, c.type);
  2267         c.flags_field |= ACYCLIC;
  2270     /** Check that all methods which implement some
  2271      *  method conform to the method they implement.
  2272      *  @param tree         The class definition whose members are checked.
  2273      */
  2274     void checkImplementations(JCClassDecl tree) {
  2275         checkImplementations(tree, tree.sym);
  2277 //where
  2278         /** Check that all methods which implement some
  2279          *  method in `ic' conform to the method they implement.
  2280          */
  2281         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  2282             ClassSymbol origin = tree.sym;
  2283             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2284                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2285                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2286                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2287                         if (e.sym.kind == MTH &&
  2288                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2289                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2290                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2291                             if (implmeth != null && implmeth != absmeth &&
  2292                                 (implmeth.owner.flags() & INTERFACE) ==
  2293                                 (origin.flags() & INTERFACE)) {
  2294                                 // don't check if implmeth is in a class, yet
  2295                                 // origin is an interface. This case arises only
  2296                                 // if implmeth is declared in Object. The reason is
  2297                                 // that interfaces really don't inherit from
  2298                                 // Object it's just that the compiler represents
  2299                                 // things that way.
  2300                                 checkOverride(tree, implmeth, absmeth, origin);
  2308     /** Check that all abstract methods implemented by a class are
  2309      *  mutually compatible.
  2310      *  @param pos          Position to be used for error reporting.
  2311      *  @param c            The class whose interfaces are checked.
  2312      */
  2313     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2314         List<Type> supertypes = types.interfaces(c);
  2315         Type supertype = types.supertype(c);
  2316         if (supertype.tag == CLASS &&
  2317             (supertype.tsym.flags() & ABSTRACT) != 0)
  2318             supertypes = supertypes.prepend(supertype);
  2319         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2320             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2321                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2322                 return;
  2323             for (List<Type> m = supertypes; m != l; m = m.tail)
  2324                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2325                     return;
  2327         checkCompatibleConcretes(pos, c);
  2330     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2331         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2332             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2333                 // VM allows methods and variables with differing types
  2334                 if (sym.kind == e.sym.kind &&
  2335                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2336                     sym != e.sym &&
  2337                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2338                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2339                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2340                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2341                     return;
  2347     /** Check that all non-override equivalent methods accessible from 'site'
  2348      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2350      *  @param pos  Position to be used for error reporting.
  2351      *  @param site The class whose methods are checked.
  2352      *  @param sym  The method symbol to be checked.
  2353      */
  2354     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2355          ClashFilter cf = new ClashFilter(site);
  2356         //for each method m1 that is overridden (directly or indirectly)
  2357         //by method 'sym' in 'site'...
  2358         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2359             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2360              //...check each method m2 that is a member of 'site'
  2361              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2362                 if (m2 == m1) continue;
  2363                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2364                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2365                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
  2366                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2367                     sym.flags_field |= CLASH;
  2368                     String key = m1 == sym ?
  2369                             "name.clash.same.erasure.no.override" :
  2370                             "name.clash.same.erasure.no.override.1";
  2371                     log.error(pos,
  2372                             key,
  2373                             sym, sym.location(),
  2374                             m2, m2.location(),
  2375                             m1, m1.location());
  2376                     return;
  2384     /** Check that all static methods accessible from 'site' are
  2385      *  mutually compatible (JLS 8.4.8).
  2387      *  @param pos  Position to be used for error reporting.
  2388      *  @param site The class whose methods are checked.
  2389      *  @param sym  The method symbol to be checked.
  2390      */
  2391     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2392         ClashFilter cf = new ClashFilter(site);
  2393         //for each method m1 that is a member of 'site'...
  2394         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2395             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2396             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2397             if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
  2398                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2399                 log.error(pos,
  2400                         "name.clash.same.erasure.no.hide",
  2401                         sym, sym.location(),
  2402                         s, s.location());
  2403                 return;
  2408      //where
  2409      private class ClashFilter implements Filter<Symbol> {
  2411          Type site;
  2413          ClashFilter(Type site) {
  2414              this.site = site;
  2417          boolean shouldSkip(Symbol s) {
  2418              return (s.flags() & CLASH) != 0 &&
  2419                 s.owner == site.tsym;
  2422          public boolean accepts(Symbol s) {
  2423              return s.kind == MTH &&
  2424                      (s.flags() & SYNTHETIC) == 0 &&
  2425                      !shouldSkip(s) &&
  2426                      s.isInheritedIn(site.tsym, types) &&
  2427                      !s.isConstructor();
  2431     /** Report a conflict between a user symbol and a synthetic symbol.
  2432      */
  2433     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2434         if (!sym.type.isErroneous()) {
  2435             if (warnOnSyntheticConflicts) {
  2436                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2438             else {
  2439                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2444     /** Check that class c does not implement directly or indirectly
  2445      *  the same parameterized interface with two different argument lists.
  2446      *  @param pos          Position to be used for error reporting.
  2447      *  @param type         The type whose interfaces are checked.
  2448      */
  2449     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2450         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2452 //where
  2453         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2454          *  with their class symbol as key and their type as value. Make
  2455          *  sure no class is entered with two different types.
  2456          */
  2457         void checkClassBounds(DiagnosticPosition pos,
  2458                               Map<TypeSymbol,Type> seensofar,
  2459                               Type type) {
  2460             if (type.isErroneous()) return;
  2461             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2462                 Type it = l.head;
  2463                 Type oldit = seensofar.put(it.tsym, it);
  2464                 if (oldit != null) {
  2465                     List<Type> oldparams = oldit.allparams();
  2466                     List<Type> newparams = it.allparams();
  2467                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2468                         log.error(pos, "cant.inherit.diff.arg",
  2469                                   it.tsym, Type.toString(oldparams),
  2470                                   Type.toString(newparams));
  2472                 checkClassBounds(pos, seensofar, it);
  2474             Type st = types.supertype(type);
  2475             if (st != null) checkClassBounds(pos, seensofar, st);
  2478     /** Enter interface into into set.
  2479      *  If it existed already, issue a "repeated interface" error.
  2480      */
  2481     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2482         if (its.contains(it))
  2483             log.error(pos, "repeated.interface");
  2484         else {
  2485             its.add(it);
  2489 /* *************************************************************************
  2490  * Check annotations
  2491  **************************************************************************/
  2493     /**
  2494      * Recursively validate annotations values
  2495      */
  2496     void validateAnnotationTree(JCTree tree) {
  2497         class AnnotationValidator extends TreeScanner {
  2498             @Override
  2499             public void visitAnnotation(JCAnnotation tree) {
  2500                 if (!tree.type.isErroneous()) {
  2501                     super.visitAnnotation(tree);
  2502                     validateAnnotation(tree);
  2506         tree.accept(new AnnotationValidator());
  2509     /**
  2510      *  {@literal
  2511      *  Annotation types are restricted to primitives, String, an
  2512      *  enum, an annotation, Class, Class<?>, Class<? extends
  2513      *  Anything>, arrays of the preceding.
  2514      *  }
  2515      */
  2516     void validateAnnotationType(JCTree restype) {
  2517         // restype may be null if an error occurred, so don't bother validating it
  2518         if (restype != null) {
  2519             validateAnnotationType(restype.pos(), restype.type);
  2523     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2524         if (type.isPrimitive()) return;
  2525         if (types.isSameType(type, syms.stringType)) return;
  2526         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2527         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2528         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2529         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2530             validateAnnotationType(pos, types.elemtype(type));
  2531             return;
  2533         log.error(pos, "invalid.annotation.member.type");
  2536     /**
  2537      * "It is also a compile-time error if any method declared in an
  2538      * annotation type has a signature that is override-equivalent to
  2539      * that of any public or protected method declared in class Object
  2540      * or in the interface annotation.Annotation."
  2542      * @jls 9.6 Annotation Types
  2543      */
  2544     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2545         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2546             Scope s = sup.tsym.members();
  2547             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2548                 if (e.sym.kind == MTH &&
  2549                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2550                     types.overrideEquivalent(m.type, e.sym.type))
  2551                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2556     /** Check the annotations of a symbol.
  2557      */
  2558     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2559         for (JCAnnotation a : annotations)
  2560             validateAnnotation(a, s);
  2563     /** Check an annotation of a symbol.
  2564      */
  2565     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2566         validateAnnotationTree(a);
  2568         if (!annotationApplicable(a, s))
  2569             log.error(a.pos(), "annotation.type.not.applicable");
  2571         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2572             if (!isOverrider(s))
  2573                 log.error(a.pos(), "method.does.not.override.superclass");
  2577     /**
  2578      * Validate the proposed container 'containedBy' on the
  2579      * annotation type symbol 's'. Report errors at position
  2580      * 'pos'.
  2582      * @param s The (annotation)type declaration annotated with a @ContainedBy
  2583      * @param containedBy the @ContainedBy on 's'
  2584      * @param pos where to report errors
  2585      */
  2586     public void validateContainedBy(TypeSymbol s, Attribute.Compound containedBy, DiagnosticPosition pos) {
  2587         Assert.check(types.isSameType(containedBy.type, syms.containedByType));
  2589         Type t = null;
  2590         List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
  2591         if (!l.isEmpty()) {
  2592             Assert.check(l.head.fst.name == names.value);
  2593             t = ((Attribute.Class)l.head.snd).getValue();
  2596         if (t == null) {
  2597             log.error(pos, "invalid.container.wrong.containedby", s, containedBy);
  2598             return;
  2601         validateHasContainerFor(t.tsym, s, pos);
  2602         validateRetention(t.tsym, s, pos);
  2603         validateDocumented(t.tsym, s, pos);
  2604         validateInherited(t.tsym, s, pos);
  2605         validateTarget(t.tsym, s, pos);
  2606         validateDefault(t.tsym, s, pos);
  2609     /**
  2610      * Validate the proposed container 'containerFor' on the
  2611      * annotation type symbol 's'. Report errors at position
  2612      * 'pos'.
  2614      * @param s The (annotation)type declaration annotated with a @ContainerFor
  2615      * @param containerFor the @ContainedFor on 's'
  2616      * @param pos where to report errors
  2617      */
  2618     public void validateContainerFor(TypeSymbol s, Attribute.Compound containerFor, DiagnosticPosition pos) {
  2619         Assert.check(types.isSameType(containerFor.type, syms.containerForType));
  2621         Type t = null;
  2622         List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
  2623         if (!l.isEmpty()) {
  2624             Assert.check(l.head.fst.name == names.value);
  2625             t = ((Attribute.Class)l.head.snd).getValue();
  2628         if (t == null) {
  2629             log.error(pos, "invalid.container.wrong.containerfor", s, containerFor);
  2630             return;
  2633         validateHasContainedBy(t.tsym, s, pos);
  2636     private void validateHasContainedBy(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2637         Attribute.Compound containedBy = container.attribute(syms.containedByType.tsym);
  2639         if (containedBy == null) {
  2640             log.error(pos, "invalid.container.no.containedby", container, syms.containedByType.tsym);
  2641             return;
  2644         Type t = null;
  2645         List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
  2646         if (!l.isEmpty()) {
  2647             Assert.check(l.head.fst.name == names.value);
  2648             t = ((Attribute.Class)l.head.snd).getValue();
  2651         if (t == null) {
  2652             log.error(pos, "invalid.container.wrong.containedby", container, contained);
  2653             return;
  2656         if (!types.isSameType(t, contained.type))
  2657             log.error(pos, "invalid.container.wrong.containedby", t.tsym, contained);
  2660     private void validateHasContainerFor(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2661         Attribute.Compound containerFor = container.attribute(syms.containerForType.tsym);
  2663         if (containerFor == null) {
  2664             log.error(pos, "invalid.container.no.containerfor", container, syms.containerForType.tsym);
  2665             return;
  2668         Type t = null;
  2669         List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
  2670         if (!l.isEmpty()) {
  2671             Assert.check(l.head.fst.name == names.value);
  2672             t = ((Attribute.Class)l.head.snd).getValue();
  2675         if (t == null) {
  2676             log.error(pos, "invalid.container.wrong.containerfor", container, contained);
  2677             return;
  2680         if (!types.isSameType(t, contained.type))
  2681             log.error(pos, "invalid.container.wrong.containerfor", t.tsym, contained);
  2684     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2685         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2686         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2688         boolean error = false;
  2689         switch (containedRetention) {
  2690         case RUNTIME:
  2691             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2692                 error = true;
  2694             break;
  2695         case CLASS:
  2696             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2697                 error = true;
  2700         if (error ) {
  2701             log.error(pos, "invalid.containedby.annotation.retention",
  2702                       container, containerRetention,
  2703                       contained, containedRetention);
  2707     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2708         if (contained.attribute(syms.documentedType.tsym) != null) {
  2709             if (container.attribute(syms.documentedType.tsym) == null) {
  2710                 log.error(pos, "invalid.containedby.annotation.not.documented", container, contained);
  2715     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2716         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2717             if (container.attribute(syms.inheritedType.tsym) == null) {
  2718                 log.error(pos, "invalid.containedby.annotation.not.inherited", container, contained);
  2723     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2724         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2726         // If contained has no Target, we are done
  2727         if (containedTarget == null) {
  2728             return;
  2731         // If contained has Target m1, container must have a Target
  2732         // annotation, m2, and m2 must be a subset of m1. (This is
  2733         // trivially true if contained has no target as per above).
  2735         // contained has target, but container has not, error
  2736         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2737         if (containerTarget == null) {
  2738             log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
  2739             return;
  2742         Set<Name> containerTargets = new HashSet<Name>();
  2743         for (Attribute app : containerTarget.values) {
  2744             if (!(app instanceof Attribute.Enum)) {
  2745                 continue; // recovery
  2747             Attribute.Enum e = (Attribute.Enum)app;
  2748             containerTargets.add(e.value.name);
  2751         Set<Name> containedTargets = new HashSet<Name>();
  2752         for (Attribute app : containedTarget.values) {
  2753             if (!(app instanceof Attribute.Enum)) {
  2754                 continue; // recovery
  2756             Attribute.Enum e = (Attribute.Enum)app;
  2757             containedTargets.add(e.value.name);
  2760         if (!isTargetSubset(containedTargets, containerTargets)) {
  2761             log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
  2765     /** Checks that t is a subset of s, with respect to ElementType
  2766      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2767      */
  2768     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2769         // Check that all elements in t are present in s
  2770         for (Name n2 : t) {
  2771             boolean currentElementOk = false;
  2772             for (Name n1 : s) {
  2773                 if (n1 == n2) {
  2774                     currentElementOk = true;
  2775                     break;
  2776                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2777                     currentElementOk = true;
  2778                     break;
  2781             if (!currentElementOk)
  2782                 return false;
  2784         return true;
  2787     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2788         // validate that all other elements of containing type has defaults
  2789         Scope scope = container.members();
  2790         for(Symbol elm : scope.getElements()) {
  2791             if (elm.name != names.value &&
  2792                 elm.kind == Kinds.MTH &&
  2793                 ((MethodSymbol)elm).defaultValue == null) {
  2794                 log.error(pos,
  2795                           "invalid.containedby.annotation.elem.nondefault",
  2796                           container,
  2797                           elm);
  2802     /** Is s a method symbol that overrides a method in a superclass? */
  2803     boolean isOverrider(Symbol s) {
  2804         if (s.kind != MTH || s.isStatic())
  2805             return false;
  2806         MethodSymbol m = (MethodSymbol)s;
  2807         TypeSymbol owner = (TypeSymbol)m.owner;
  2808         for (Type sup : types.closure(owner.type)) {
  2809             if (sup == owner.type)
  2810                 continue; // skip "this"
  2811             Scope scope = sup.tsym.members();
  2812             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2813                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2814                     return true;
  2817         return false;
  2820     /** Is the annotation applicable to the symbol? */
  2821     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2822         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2823         if (arr == null) {
  2824             return true;
  2826         for (Attribute app : arr.values) {
  2827             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2828             Attribute.Enum e = (Attribute.Enum) app;
  2829             if (e.value.name == names.TYPE)
  2830                 { if (s.kind == TYP) return true; }
  2831             else if (e.value.name == names.FIELD)
  2832                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2833             else if (e.value.name == names.METHOD)
  2834                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2835             else if (e.value.name == names.PARAMETER)
  2836                 { if (s.kind == VAR &&
  2837                       s.owner.kind == MTH &&
  2838                       (s.flags() & PARAMETER) != 0)
  2839                     return true;
  2841             else if (e.value.name == names.CONSTRUCTOR)
  2842                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2843             else if (e.value.name == names.LOCAL_VARIABLE)
  2844                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2845                       (s.flags() & PARAMETER) == 0)
  2846                     return true;
  2848             else if (e.value.name == names.ANNOTATION_TYPE)
  2849                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2850                     return true;
  2852             else if (e.value.name == names.PACKAGE)
  2853                 { if (s.kind == PCK) return true; }
  2854             else if (e.value.name == names.TYPE_USE)
  2855                 { if (s.kind == TYP ||
  2856                       s.kind == VAR ||
  2857                       (s.kind == MTH && !s.isConstructor() &&
  2858                        s.type.getReturnType().tag != VOID))
  2859                     return true;
  2861             else
  2862                 return true; // recovery
  2864         return false;
  2868     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2869         Attribute.Compound atTarget =
  2870             s.attribute(syms.annotationTargetType.tsym);
  2871         if (atTarget == null) return null; // ok, is applicable
  2872         Attribute atValue = atTarget.member(names.value);
  2873         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2874         return (Attribute.Array) atValue;
  2877     /** Check an annotation value.
  2878      */
  2879     public void validateAnnotation(JCAnnotation a) {
  2880         // collect an inventory of the members (sorted alphabetically)
  2881         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2882             public int compare(Symbol t, Symbol t1) {
  2883                 return t.name.compareTo(t1.name);
  2885         });
  2886         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2887              e != null;
  2888              e = e.sibling)
  2889             if (e.sym.kind == MTH)
  2890                 members.add((MethodSymbol) e.sym);
  2892         // count them off as they're annotated
  2893         for (JCTree arg : a.args) {
  2894             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2895             JCAssign assign = (JCAssign) arg;
  2896             Symbol m = TreeInfo.symbol(assign.lhs);
  2897             if (m == null || m.type.isErroneous()) continue;
  2898             if (!members.remove(m))
  2899                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2900                           m.name, a.type);
  2903         // all the remaining ones better have default values
  2904         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2905         for (MethodSymbol m : members) {
  2906             if (m.defaultValue == null && !m.type.isErroneous()) {
  2907                 missingDefaults.append(m.name);
  2910         if (missingDefaults.nonEmpty()) {
  2911             String key = (missingDefaults.size() > 1)
  2912                     ? "annotation.missing.default.value.1"
  2913                     : "annotation.missing.default.value";
  2914             log.error(a.pos(), key, a.type, missingDefaults);
  2917         // special case: java.lang.annotation.Target must not have
  2918         // repeated values in its value member
  2919         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2920             a.args.tail == null)
  2921             return;
  2923         if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
  2924         JCAssign assign = (JCAssign) a.args.head;
  2925         Symbol m = TreeInfo.symbol(assign.lhs);
  2926         if (m.name != names.value) return;
  2927         JCTree rhs = assign.rhs;
  2928         if (!rhs.hasTag(NEWARRAY)) return;
  2929         JCNewArray na = (JCNewArray) rhs;
  2930         Set<Symbol> targets = new HashSet<Symbol>();
  2931         for (JCTree elem : na.elems) {
  2932             if (!targets.add(TreeInfo.symbol(elem))) {
  2933                 log.error(elem.pos(), "repeated.annotation.target");
  2938     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2939         if (allowAnnotations &&
  2940             lint.isEnabled(LintCategory.DEP_ANN) &&
  2941             (s.flags() & DEPRECATED) != 0 &&
  2942             !syms.deprecatedType.isErroneous() &&
  2943             s.attribute(syms.deprecatedType.tsym) == null) {
  2944             log.warning(LintCategory.DEP_ANN,
  2945                     pos, "missing.deprecated.annotation");
  2949     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2950         if ((s.flags() & DEPRECATED) != 0 &&
  2951                 (other.flags() & DEPRECATED) == 0 &&
  2952                 s.outermostClass() != other.outermostClass()) {
  2953             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2954                 @Override
  2955                 public void report() {
  2956                     warnDeprecated(pos, s);
  2958             });
  2962     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2963         if ((s.flags() & PROPRIETARY) != 0) {
  2964             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2965                 public void report() {
  2966                     if (enableSunApiLintControl)
  2967                       warnSunApi(pos, "sun.proprietary", s);
  2968                     else
  2969                       log.mandatoryWarning(pos, "sun.proprietary", s);
  2971             });
  2975 /* *************************************************************************
  2976  * Check for recursive annotation elements.
  2977  **************************************************************************/
  2979     /** Check for cycles in the graph of annotation elements.
  2980      */
  2981     void checkNonCyclicElements(JCClassDecl tree) {
  2982         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2983         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2984         try {
  2985             tree.sym.flags_field |= LOCKED;
  2986             for (JCTree def : tree.defs) {
  2987                 if (!def.hasTag(METHODDEF)) continue;
  2988                 JCMethodDecl meth = (JCMethodDecl)def;
  2989                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2991         } finally {
  2992             tree.sym.flags_field &= ~LOCKED;
  2993             tree.sym.flags_field |= ACYCLIC_ANN;
  2997     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2998         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2999             return;
  3000         if ((tsym.flags_field & LOCKED) != 0) {
  3001             log.error(pos, "cyclic.annotation.element");
  3002             return;
  3004         try {
  3005             tsym.flags_field |= LOCKED;
  3006             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  3007                 Symbol s = e.sym;
  3008                 if (s.kind != Kinds.MTH)
  3009                     continue;
  3010                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  3012         } finally {
  3013             tsym.flags_field &= ~LOCKED;
  3014             tsym.flags_field |= ACYCLIC_ANN;
  3018     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  3019         switch (type.tag) {
  3020         case TypeTags.CLASS:
  3021             if ((type.tsym.flags() & ANNOTATION) != 0)
  3022                 checkNonCyclicElementsInternal(pos, type.tsym);
  3023             break;
  3024         case TypeTags.ARRAY:
  3025             checkAnnotationResType(pos, types.elemtype(type));
  3026             break;
  3027         default:
  3028             break; // int etc
  3032 /* *************************************************************************
  3033  * Check for cycles in the constructor call graph.
  3034  **************************************************************************/
  3036     /** Check for cycles in the graph of constructors calling other
  3037      *  constructors.
  3038      */
  3039     void checkCyclicConstructors(JCClassDecl tree) {
  3040         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  3042         // enter each constructor this-call into the map
  3043         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  3044             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  3045             if (app == null) continue;
  3046             JCMethodDecl meth = (JCMethodDecl) l.head;
  3047             if (TreeInfo.name(app.meth) == names._this) {
  3048                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  3049             } else {
  3050                 meth.sym.flags_field |= ACYCLIC;
  3054         // Check for cycles in the map
  3055         Symbol[] ctors = new Symbol[0];
  3056         ctors = callMap.keySet().toArray(ctors);
  3057         for (Symbol caller : ctors) {
  3058             checkCyclicConstructor(tree, caller, callMap);
  3062     /** Look in the map to see if the given constructor is part of a
  3063      *  call cycle.
  3064      */
  3065     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  3066                                         Map<Symbol,Symbol> callMap) {
  3067         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  3068             if ((ctor.flags_field & LOCKED) != 0) {
  3069                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  3070                           "recursive.ctor.invocation");
  3071             } else {
  3072                 ctor.flags_field |= LOCKED;
  3073                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  3074                 ctor.flags_field &= ~LOCKED;
  3076             ctor.flags_field |= ACYCLIC;
  3080 /* *************************************************************************
  3081  * Miscellaneous
  3082  **************************************************************************/
  3084     /**
  3085      * Return the opcode of the operator but emit an error if it is an
  3086      * error.
  3087      * @param pos        position for error reporting.
  3088      * @param operator   an operator
  3089      * @param tag        a tree tag
  3090      * @param left       type of left hand side
  3091      * @param right      type of right hand side
  3092      */
  3093     int checkOperator(DiagnosticPosition pos,
  3094                        OperatorSymbol operator,
  3095                        JCTree.Tag tag,
  3096                        Type left,
  3097                        Type right) {
  3098         if (operator.opcode == ByteCodes.error) {
  3099             log.error(pos,
  3100                       "operator.cant.be.applied.1",
  3101                       treeinfo.operatorName(tag),
  3102                       left, right);
  3104         return operator.opcode;
  3108     /**
  3109      *  Check for division by integer constant zero
  3110      *  @param pos           Position for error reporting.
  3111      *  @param operator      The operator for the expression
  3112      *  @param operand       The right hand operand for the expression
  3113      */
  3114     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3115         if (operand.constValue() != null
  3116             && lint.isEnabled(LintCategory.DIVZERO)
  3117             && operand.tag <= LONG
  3118             && ((Number) (operand.constValue())).longValue() == 0) {
  3119             int opc = ((OperatorSymbol)operator).opcode;
  3120             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3121                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3122                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3127     /**
  3128      * Check for empty statements after if
  3129      */
  3130     void checkEmptyIf(JCIf tree) {
  3131         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3132                 lint.isEnabled(LintCategory.EMPTY))
  3133             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3136     /** Check that symbol is unique in given scope.
  3137      *  @param pos           Position for error reporting.
  3138      *  @param sym           The symbol.
  3139      *  @param s             The scope.
  3140      */
  3141     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3142         if (sym.type.isErroneous())
  3143             return true;
  3144         if (sym.owner.name == names.any) return false;
  3145         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3146             if (sym != e.sym &&
  3147                     (e.sym.flags() & CLASH) == 0 &&
  3148                     sym.kind == e.sym.kind &&
  3149                     sym.name != names.error &&
  3150                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3151                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3152                     varargsDuplicateError(pos, sym, e.sym);
  3153                     return true;
  3154                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3155                     duplicateErasureError(pos, sym, e.sym);
  3156                     sym.flags_field |= CLASH;
  3157                     return true;
  3158                 } else {
  3159                     duplicateError(pos, e.sym);
  3160                     return false;
  3164         return true;
  3167     /** Report duplicate declaration error.
  3168      */
  3169     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3170         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3171             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3175     /** Check that single-type import is not already imported or top-level defined,
  3176      *  but make an exception for two single-type imports which denote the same type.
  3177      *  @param pos           Position for error reporting.
  3178      *  @param sym           The symbol.
  3179      *  @param s             The scope
  3180      */
  3181     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3182         return checkUniqueImport(pos, sym, s, false);
  3185     /** Check that static single-type import is not already imported or top-level defined,
  3186      *  but make an exception for two single-type imports which denote the same type.
  3187      *  @param pos           Position for error reporting.
  3188      *  @param sym           The symbol.
  3189      *  @param s             The scope
  3190      */
  3191     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3192         return checkUniqueImport(pos, sym, s, true);
  3195     /** Check that single-type import is not already imported or top-level defined,
  3196      *  but make an exception for two single-type imports which denote the same type.
  3197      *  @param pos           Position for error reporting.
  3198      *  @param sym           The symbol.
  3199      *  @param s             The scope.
  3200      *  @param staticImport  Whether or not this was a static import
  3201      */
  3202     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3203         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3204             // is encountered class entered via a class declaration?
  3205             boolean isClassDecl = e.scope == s;
  3206             if ((isClassDecl || sym != e.sym) &&
  3207                 sym.kind == e.sym.kind &&
  3208                 sym.name != names.error) {
  3209                 if (!e.sym.type.isErroneous()) {
  3210                     String what = e.sym.toString();
  3211                     if (!isClassDecl) {
  3212                         if (staticImport)
  3213                             log.error(pos, "already.defined.static.single.import", what);
  3214                         else
  3215                             log.error(pos, "already.defined.single.import", what);
  3217                     else if (sym != e.sym)
  3218                         log.error(pos, "already.defined.this.unit", what);
  3220                 return false;
  3223         return true;
  3226     /** Check that a qualified name is in canonical form (for import decls).
  3227      */
  3228     public void checkCanonical(JCTree tree) {
  3229         if (!isCanonical(tree))
  3230             log.error(tree.pos(), "import.requires.canonical",
  3231                       TreeInfo.symbol(tree));
  3233         // where
  3234         private boolean isCanonical(JCTree tree) {
  3235             while (tree.hasTag(SELECT)) {
  3236                 JCFieldAccess s = (JCFieldAccess) tree;
  3237                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3238                     return false;
  3239                 tree = s.selected;
  3241             return true;
  3244     private class ConversionWarner extends Warner {
  3245         final String uncheckedKey;
  3246         final Type found;
  3247         final Type expected;
  3248         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3249             super(pos);
  3250             this.uncheckedKey = uncheckedKey;
  3251             this.found = found;
  3252             this.expected = expected;
  3255         @Override
  3256         public void warn(LintCategory lint) {
  3257             boolean warned = this.warned;
  3258             super.warn(lint);
  3259             if (warned) return; // suppress redundant diagnostics
  3260             switch (lint) {
  3261                 case UNCHECKED:
  3262                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3263                     break;
  3264                 case VARARGS:
  3265                     if (method != null &&
  3266                             method.attribute(syms.trustMeType.tsym) != null &&
  3267                             isTrustMeAllowedOnMethod(method) &&
  3268                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3269                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3271                     break;
  3272                 default:
  3273                     throw new AssertionError("Unexpected lint: " + lint);
  3278     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3279         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3282     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3283         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial