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

Thu, 04 Oct 2012 13:04:53 +0100

author
mcimadamore
date
Thu, 04 Oct 2012 13:04:53 +0100
changeset 1347
1408af4cd8b0
parent 1344
73312ec2cf7c
child 1348
573ceb23beeb
permissions
-rw-r--r--

7177387: Add target-typing support in method context
Summary: Add support for deferred types and speculative attribution
Reviewed-by: jjg, dlsmith

     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      *  @param sym        The deprecated symbol.
   234      */
   235     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   236         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   237             log.warning(LintCategory.VARARGS, pos, key, args);
   238     }
   240     /** Warn about using proprietary API.
   241      *  @param pos        Position to be used for error reporting.
   242      *  @param msg        A string describing the problem.
   243      */
   244     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   245         if (!lint.isSuppressed(LintCategory.SUNAPI))
   246             sunApiHandler.report(pos, msg, args);
   247     }
   249     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   250         if (lint.isEnabled(LintCategory.STATIC))
   251             log.warning(LintCategory.STATIC, pos, msg, args);
   252     }
   254     /**
   255      * Report any deferred diagnostics.
   256      */
   257     public void reportDeferredDiagnostics() {
   258         deprecationHandler.reportDeferredDiagnostic();
   259         uncheckedHandler.reportDeferredDiagnostic();
   260         sunApiHandler.reportDeferredDiagnostic();
   261     }
   264     /** Report a failure to complete a class.
   265      *  @param pos        Position to be used for error reporting.
   266      *  @param ex         The failure to report.
   267      */
   268     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   269         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   270         if (ex instanceof ClassReader.BadClassFile
   271                 && !suppressAbortOnBadClassFile) throw new Abort();
   272         else return syms.errType;
   273     }
   275     /** Report an error that wrong type tag was found.
   276      *  @param pos        Position to be used for error reporting.
   277      *  @param required   An internationalized string describing the type tag
   278      *                    required.
   279      *  @param found      The type that was found.
   280      */
   281     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   282         // this error used to be raised by the parser,
   283         // but has been delayed to this point:
   284         if (found instanceof Type && ((Type)found).tag == VOID) {
   285             log.error(pos, "illegal.start.of.type");
   286             return syms.errType;
   287         }
   288         log.error(pos, "type.found.req", found, required);
   289         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   290     }
   292     /** Report an error that symbol cannot be referenced before super
   293      *  has been called.
   294      *  @param pos        Position to be used for error reporting.
   295      *  @param sym        The referenced symbol.
   296      */
   297     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   298         log.error(pos, "cant.ref.before.ctor.called", sym);
   299     }
   301     /** Report duplicate declaration error.
   302      */
   303     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   304         if (!sym.type.isErroneous()) {
   305             Symbol location = sym.location();
   306             if (location.kind == MTH &&
   307                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   308                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   309                         kindName(sym.location()), kindName(sym.location().enclClass()),
   310                         sym.location().enclClass());
   311             } else {
   312                 log.error(pos, "already.defined", kindName(sym), sym,
   313                         kindName(sym.location()), sym.location());
   314             }
   315         }
   316     }
   318     /** Report array/varargs duplicate declaration
   319      */
   320     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   321         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   322             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   323         }
   324     }
   326 /* ************************************************************************
   327  * duplicate declaration checking
   328  *************************************************************************/
   330     /** Check that variable does not hide variable with same name in
   331      *  immediately enclosing local scope.
   332      *  @param pos           Position for error reporting.
   333      *  @param v             The symbol.
   334      *  @param s             The scope.
   335      */
   336     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   337         if (s.next != null) {
   338             for (Scope.Entry e = s.next.lookup(v.name);
   339                  e.scope != null && e.sym.owner == v.owner;
   340                  e = e.next()) {
   341                 if (e.sym.kind == VAR &&
   342                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   343                     v.name != names.error) {
   344                     duplicateError(pos, e.sym);
   345                     return;
   346                 }
   347             }
   348         }
   349     }
   351     /** Check that a class or interface does not hide a class or
   352      *  interface with same name in immediately enclosing local scope.
   353      *  @param pos           Position for error reporting.
   354      *  @param c             The symbol.
   355      *  @param s             The scope.
   356      */
   357     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   358         if (s.next != null) {
   359             for (Scope.Entry e = s.next.lookup(c.name);
   360                  e.scope != null && e.sym.owner == c.owner;
   361                  e = e.next()) {
   362                 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
   363                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   364                     c.name != names.error) {
   365                     duplicateError(pos, e.sym);
   366                     return;
   367                 }
   368             }
   369         }
   370     }
   372     /** Check that class does not have the same name as one of
   373      *  its enclosing classes, or as a class defined in its enclosing scope.
   374      *  return true if class is unique in its enclosing scope.
   375      *  @param pos           Position for error reporting.
   376      *  @param name          The class name.
   377      *  @param s             The enclosing scope.
   378      */
   379     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   380         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   381             if (e.sym.kind == TYP && e.sym.name != names.error) {
   382                 duplicateError(pos, e.sym);
   383                 return false;
   384             }
   385         }
   386         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   387             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   388                 duplicateError(pos, sym);
   389                 return true;
   390             }
   391         }
   392         return true;
   393     }
   395 /* *************************************************************************
   396  * Class name generation
   397  **************************************************************************/
   399     /** Return name of local class.
   400      *  This is of the form    <enclClass> $ n <classname>
   401      *  where
   402      *    enclClass is the flat name of the enclosing class,
   403      *    classname is the simple name of the local class
   404      */
   405     Name localClassName(ClassSymbol c) {
   406         for (int i=1; ; i++) {
   407             Name flatname = names.
   408                 fromString("" + c.owner.enclClass().flatname +
   409                            syntheticNameChar + i +
   410                            c.name);
   411             if (compiled.get(flatname) == null) return flatname;
   412         }
   413     }
   415 /* *************************************************************************
   416  * Type Checking
   417  **************************************************************************/
   419     /**
   420      * A check context is an object that can be used to perform compatibility
   421      * checks - depending on the check context, meaning of 'compatibility' might
   422      * vary significantly.
   423      */
   424     interface CheckContext {
   425         /**
   426          * Is type 'found' compatible with type 'req' in given context
   427          */
   428         boolean compatible(Type found, Type req, Warner warn);
   429         /**
   430          * Report a check error
   431          */
   432         void report(DiagnosticPosition pos, JCDiagnostic details);
   433         /**
   434          * Obtain a warner for this check context
   435          */
   436         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req);
   438         public Infer.InferenceContext inferenceContext();
   440         public DeferredAttr.DeferredAttrContext deferredAttrContext();
   441     }
   443     /**
   444      * This class represent a check context that is nested within another check
   445      * context - useful to check sub-expressions. The default behavior simply
   446      * redirects all method calls to the enclosing check context leveraging
   447      * the forwarding pattern.
   448      */
   449     static class NestedCheckContext implements CheckContext {
   450         CheckContext enclosingContext;
   452         NestedCheckContext(CheckContext enclosingContext) {
   453             this.enclosingContext = enclosingContext;
   454         }
   456         public boolean compatible(Type found, Type req, Warner warn) {
   457             return enclosingContext.compatible(found, req, warn);
   458         }
   460         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   461             enclosingContext.report(pos, details);
   462         }
   464         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   465             return enclosingContext.checkWarner(pos, found, req);
   466         }
   468         public Infer.InferenceContext inferenceContext() {
   469             return enclosingContext.inferenceContext();
   470         }
   472         public DeferredAttrContext deferredAttrContext() {
   473             return enclosingContext.deferredAttrContext();
   474         }
   475     }
   477     /**
   478      * Check context to be used when evaluating assignment/return statements
   479      */
   480     CheckContext basicHandler = new CheckContext() {
   481         public void report(DiagnosticPosition pos, JCDiagnostic details) {
   482             log.error(pos, "prob.found.req", details);
   483         }
   484         public boolean compatible(Type found, Type req, Warner warn) {
   485             return types.isAssignable(found, req, warn);
   486         }
   488         public Warner checkWarner(DiagnosticPosition pos, Type found, Type req) {
   489             return convertWarner(pos, found, req);
   490         }
   492         public InferenceContext inferenceContext() {
   493             return infer.emptyContext;
   494         }
   496         public DeferredAttrContext deferredAttrContext() {
   497             return deferredAttr.emptyDeferredAttrContext;
   498         }
   499     };
   501     /** Check that a given type is assignable to a given proto-type.
   502      *  If it is, return the type, otherwise return errType.
   503      *  @param pos        Position to be used for error reporting.
   504      *  @param found      The type that was found.
   505      *  @param req        The type that was required.
   506      */
   507     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   508         return checkType(pos, found, req, basicHandler);
   509     }
   511     Type checkType(final DiagnosticPosition pos, final Type found, final Type req, final CheckContext checkContext) {
   512         final Infer.InferenceContext inferenceContext = checkContext.inferenceContext();
   513         if (inferenceContext.free(req)) {
   514             inferenceContext.addFreeTypeListener(List.of(req), new FreeTypeListener() {
   515                 @Override
   516                 public void typesInferred(InferenceContext inferenceContext) {
   517                     checkType(pos, found, inferenceContext.asInstType(req, types), checkContext);
   518                 }
   519             });
   520         }
   521         if (req.tag == ERROR)
   522             return req;
   523         if (req.tag == NONE)
   524             return found;
   525         if (checkContext.compatible(found, req, checkContext.checkWarner(pos, found, req))) {
   526             return found;
   527         } else {
   528             if (found.tag <= DOUBLE && req.tag <= DOUBLE) {
   529                 checkContext.report(pos, diags.fragment("possible.loss.of.precision", found, req));
   530                 return types.createErrorType(found);
   531             }
   532             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   533             return types.createErrorType(found);
   534         }
   535     }
   537     /** Check that a given type can be cast to a given target type.
   538      *  Return the result of the cast.
   539      *  @param pos        Position to be used for error reporting.
   540      *  @param found      The type that is being cast.
   541      *  @param req        The target type of the cast.
   542      */
   543     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   544         return checkCastable(pos, found, req, basicHandler);
   545     }
   546     Type checkCastable(DiagnosticPosition pos, Type found, Type req, CheckContext checkContext) {
   547         if (types.isCastable(found, req, castWarner(pos, found, req))) {
   548             return req;
   549         } else {
   550             checkContext.report(pos, diags.fragment("inconvertible.types", found, req));
   551             return types.createErrorType(found);
   552         }
   553     }
   555     /** Check for redundant casts (i.e. where source type is a subtype of target type)
   556      * The problem should only be reported for non-292 cast
   557      */
   558     public void checkRedundantCast(Env<AttrContext> env, JCTypeCast tree) {
   559         if (!tree.type.isErroneous() &&
   560             (env.info.lint == null || env.info.lint.isEnabled(Lint.LintCategory.CAST))
   561             && types.isSameType(tree.expr.type, tree.clazz.type)
   562             && !is292targetTypeCast(tree)) {
   563             log.warning(Lint.LintCategory.CAST,
   564                     tree.pos(), "redundant.cast", tree.expr.type);
   565         }
   566     }
   567     //where
   568             private boolean is292targetTypeCast(JCTypeCast tree) {
   569                 boolean is292targetTypeCast = false;
   570                 JCExpression expr = TreeInfo.skipParens(tree.expr);
   571                 if (expr.hasTag(APPLY)) {
   572                     JCMethodInvocation apply = (JCMethodInvocation)expr;
   573                     Symbol sym = TreeInfo.symbol(apply.meth);
   574                     is292targetTypeCast = sym != null &&
   575                         sym.kind == MTH &&
   576                         (sym.flags() & HYPOTHETICAL) != 0;
   577                 }
   578                 return is292targetTypeCast;
   579             }
   583 //where
   584         /** Is type a type variable, or a (possibly multi-dimensional) array of
   585          *  type variables?
   586          */
   587         boolean isTypeVar(Type t) {
   588             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   589         }
   591     /** Check that a type is within some bounds.
   592      *
   593      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   594      *  type argument.
   595      *  @param pos           Position to be used for error reporting.
   596      *  @param a             The type that should be bounded by bs.
   597      *  @param bs            The bound.
   598      */
   599     private boolean checkExtends(Type a, Type bound) {
   600          if (a.isUnbound()) {
   601              return true;
   602          } else if (a.tag != WILDCARD) {
   603              a = types.upperBound(a);
   604              return types.isSubtype(a, bound);
   605          } else if (a.isExtendsBound()) {
   606              return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
   607          } else if (a.isSuperBound()) {
   608              return !types.notSoftSubtype(types.lowerBound(a), bound);
   609          }
   610          return true;
   611      }
   613     /** Check that type is different from 'void'.
   614      *  @param pos           Position to be used for error reporting.
   615      *  @param t             The type to be checked.
   616      */
   617     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   618         if (t.tag == VOID) {
   619             log.error(pos, "void.not.allowed.here");
   620             return types.createErrorType(t);
   621         } else {
   622             return t;
   623         }
   624     }
   626     /** Check that type is a class or interface type.
   627      *  @param pos           Position to be used for error reporting.
   628      *  @param t             The type to be checked.
   629      */
   630     Type checkClassType(DiagnosticPosition pos, Type t) {
   631         if (t.tag != CLASS && t.tag != ERROR)
   632             return typeTagError(pos,
   633                                 diags.fragment("type.req.class"),
   634                                 (t.tag == TYPEVAR)
   635                                 ? diags.fragment("type.parameter", t)
   636                                 : t);
   637         else
   638             return t;
   639     }
   641     /** Check that type is a class or interface type.
   642      *  @param pos           Position to be used for error reporting.
   643      *  @param t             The type to be checked.
   644      *  @param noBounds    True if type bounds are illegal here.
   645      */
   646     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   647         t = checkClassType(pos, t);
   648         if (noBounds && t.isParameterized()) {
   649             List<Type> args = t.getTypeArguments();
   650             while (args.nonEmpty()) {
   651                 if (args.head.tag == WILDCARD)
   652                     return typeTagError(pos,
   653                                         diags.fragment("type.req.exact"),
   654                                         args.head);
   655                 args = args.tail;
   656             }
   657         }
   658         return t;
   659     }
   661     /** Check that type is a reifiable class, interface or array type.
   662      *  @param pos           Position to be used for error reporting.
   663      *  @param t             The type to be checked.
   664      */
   665     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   666         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   667             return typeTagError(pos,
   668                                 diags.fragment("type.req.class.array"),
   669                                 t);
   670         } else if (!types.isReifiable(t)) {
   671             log.error(pos, "illegal.generic.type.for.instof");
   672             return types.createErrorType(t);
   673         } else {
   674             return t;
   675         }
   676     }
   678     /** Check that type is a reference type, i.e. a class, interface or array type
   679      *  or a type variable.
   680      *  @param pos           Position to be used for error reporting.
   681      *  @param t             The type to be checked.
   682      */
   683     Type checkRefType(DiagnosticPosition pos, Type t) {
   684         switch (t.tag) {
   685         case CLASS:
   686         case ARRAY:
   687         case TYPEVAR:
   688         case WILDCARD:
   689         case ERROR:
   690             return t;
   691         default:
   692             return typeTagError(pos,
   693                                 diags.fragment("type.req.ref"),
   694                                 t);
   695         }
   696     }
   698     /** Check that each type is a reference type, i.e. a class, interface or array type
   699      *  or a type variable.
   700      *  @param trees         Original trees, used for error reporting.
   701      *  @param types         The types to be checked.
   702      */
   703     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   704         List<JCExpression> tl = trees;
   705         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   706             l.head = checkRefType(tl.head.pos(), l.head);
   707             tl = tl.tail;
   708         }
   709         return types;
   710     }
   712     /** Check that type is a null or reference type.
   713      *  @param pos           Position to be used for error reporting.
   714      *  @param t             The type to be checked.
   715      */
   716     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   717         switch (t.tag) {
   718         case CLASS:
   719         case ARRAY:
   720         case TYPEVAR:
   721         case WILDCARD:
   722         case BOT:
   723         case ERROR:
   724             return t;
   725         default:
   726             return typeTagError(pos,
   727                                 diags.fragment("type.req.ref"),
   728                                 t);
   729         }
   730     }
   732     /** Check that flag set does not contain elements of two conflicting sets. s
   733      *  Return true if it doesn't.
   734      *  @param pos           Position to be used for error reporting.
   735      *  @param flags         The set of flags to be checked.
   736      *  @param set1          Conflicting flags set #1.
   737      *  @param set2          Conflicting flags set #2.
   738      */
   739     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   740         if ((flags & set1) != 0 && (flags & set2) != 0) {
   741             log.error(pos,
   742                       "illegal.combination.of.modifiers",
   743                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   744                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   745             return false;
   746         } else
   747             return true;
   748     }
   750     /** Check that usage of diamond operator is correct (i.e. diamond should not
   751      * be used with non-generic classes or in anonymous class creation expressions)
   752      */
   753     Type checkDiamond(JCNewClass tree, Type t) {
   754         if (!TreeInfo.isDiamond(tree) ||
   755                 t.isErroneous()) {
   756             return checkClassType(tree.clazz.pos(), t, true);
   757         } else if (tree.def != null) {
   758             log.error(tree.clazz.pos(),
   759                     "cant.apply.diamond.1",
   760                     t, diags.fragment("diamond.and.anon.class", t));
   761             return types.createErrorType(t);
   762         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   763             log.error(tree.clazz.pos(),
   764                 "cant.apply.diamond.1",
   765                 t, diags.fragment("diamond.non.generic", t));
   766             return types.createErrorType(t);
   767         } else if (tree.typeargs != null &&
   768                 tree.typeargs.nonEmpty()) {
   769             log.error(tree.clazz.pos(),
   770                 "cant.apply.diamond.1",
   771                 t, diags.fragment("diamond.and.explicit.params", t));
   772             return types.createErrorType(t);
   773         } else {
   774             return t;
   775         }
   776     }
   778     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   779         MethodSymbol m = tree.sym;
   780         if (!allowSimplifiedVarargs) return;
   781         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   782         Type varargElemType = null;
   783         if (m.isVarArgs()) {
   784             varargElemType = types.elemtype(tree.params.last().type);
   785         }
   786         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   787             if (varargElemType != null) {
   788                 log.error(tree,
   789                         "varargs.invalid.trustme.anno",
   790                         syms.trustMeType.tsym,
   791                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   792             } else {
   793                 log.error(tree,
   794                             "varargs.invalid.trustme.anno",
   795                             syms.trustMeType.tsym,
   796                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   797             }
   798         } else if (hasTrustMeAnno && varargElemType != null &&
   799                             types.isReifiable(varargElemType)) {
   800             warnUnsafeVararg(tree,
   801                             "varargs.redundant.trustme.anno",
   802                             syms.trustMeType.tsym,
   803                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   804         }
   805         else if (!hasTrustMeAnno && varargElemType != null &&
   806                 !types.isReifiable(varargElemType)) {
   807             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   808         }
   809     }
   810     //where
   811         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   812             return (s.flags() & VARARGS) != 0 &&
   813                 (s.isConstructor() ||
   814                     (s.flags() & (STATIC | FINAL)) != 0);
   815         }
   817     Type checkMethod(Type owntype,
   818                             Symbol sym,
   819                             Env<AttrContext> env,
   820                             final List<JCExpression> argtrees,
   821                             List<Type> argtypes,
   822                             boolean useVarargs,
   823                             boolean unchecked) {
   824         // System.out.println("call   : " + env.tree);
   825         // System.out.println("method : " + owntype);
   826         // System.out.println("actuals: " + argtypes);
   827         List<Type> formals = owntype.getParameterTypes();
   828         Type last = useVarargs ? formals.last() : null;
   829         if (sym.name==names.init &&
   830                 sym.owner == syms.enumSym)
   831                 formals = formals.tail.tail;
   832         List<JCExpression> args = argtrees;
   833         DeferredAttr.DeferredTypeMap checkDeferredMap =
   834                 deferredAttr.new DeferredTypeMap(DeferredAttr.AttrMode.CHECK, sym, env.info.pendingResolutionPhase);
   835         while (formals.head != last) {
   836             JCTree arg = args.head;
   837             Warner warn = convertWarner(arg.pos(), arg.type, formals.head);
   838             assertConvertible(arg, arg.type, formals.head, warn);
   839             args = args.tail;
   840             formals = formals.tail;
   841         }
   842         if (useVarargs) {
   843             Type varArg = types.elemtype(last);
   844             while (args.tail != null) {
   845                 JCTree arg = args.head;
   846                 Warner warn = convertWarner(arg.pos(), arg.type, varArg);
   847                 assertConvertible(arg, arg.type, varArg, warn);
   848                 args = args.tail;
   849             }
   850         } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) {
   851             // non-varargs call to varargs method
   852             Type varParam = owntype.getParameterTypes().last();
   853             Type lastArg = checkDeferredMap.apply(argtypes.last());
   854             if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) &&
   855                     !types.isSameType(types.erasure(varParam), types.erasure(lastArg)))
   856                 log.warning(argtrees.last().pos(), "inexact.non-varargs.call",
   857                         types.elemtype(varParam), varParam);
   858         }
   859         if (unchecked) {
   860             warnUnchecked(env.tree.pos(),
   861                     "unchecked.meth.invocation.applied",
   862                     kindName(sym),
   863                     sym.name,
   864                     rs.methodArguments(sym.type.getParameterTypes()),
   865                     rs.methodArguments(Type.map(argtypes, checkDeferredMap)),
   866                     kindName(sym.location()),
   867                     sym.location());
   868            owntype = new MethodType(owntype.getParameterTypes(),
   869                    types.erasure(owntype.getReturnType()),
   870                    types.erasure(owntype.getThrownTypes()),
   871                    syms.methodClass);
   872         }
   873         if (useVarargs) {
   874             JCTree tree = env.tree;
   875             Type argtype = owntype.getParameterTypes().last();
   876             if (!types.isReifiable(argtype) &&
   877                     (!allowSimplifiedVarargs ||
   878                     sym.attribute(syms.trustMeType.tsym) == null ||
   879                     !isTrustMeAllowedOnMethod(sym))) {
   880                 warnUnchecked(env.tree.pos(),
   881                                   "unchecked.generic.array.creation",
   882                                   argtype);
   883             }
   884             Type elemtype = types.elemtype(argtype);
   885             switch (tree.getTag()) {
   886                 case APPLY:
   887                     ((JCMethodInvocation) tree).varargsElement = elemtype;
   888                     break;
   889                 case NEWCLASS:
   890                     ((JCNewClass) tree).varargsElement = elemtype;
   891                     break;
   892                 default:
   893                     throw new AssertionError(""+tree);
   894             }
   895          }
   896          return owntype;
   897     }
   898     //where
   899         private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) {
   900             if (types.isConvertible(actual, formal, warn))
   901                 return;
   903             if (formal.isCompound()
   904                 && types.isSubtype(actual, types.supertype(formal))
   905                 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn))
   906                 return;
   907         }
   909     /**
   910      * Check that type 't' is a valid instantiation of a generic class
   911      * (see JLS 4.5)
   912      *
   913      * @param t class type to be checked
   914      * @return true if 't' is well-formed
   915      */
   916     public boolean checkValidGenericType(Type t) {
   917         return firstIncompatibleTypeArg(t) == null;
   918     }
   919     //WHERE
   920         private Type firstIncompatibleTypeArg(Type type) {
   921             List<Type> formals = type.tsym.type.allparams();
   922             List<Type> actuals = type.allparams();
   923             List<Type> args = type.getTypeArguments();
   924             List<Type> forms = type.tsym.type.getTypeArguments();
   925             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   927             // For matching pairs of actual argument types `a' and
   928             // formal type parameters with declared bound `b' ...
   929             while (args.nonEmpty() && forms.nonEmpty()) {
   930                 // exact type arguments needs to know their
   931                 // bounds (for upper and lower bound
   932                 // calculations).  So we create new bounds where
   933                 // type-parameters are replaced with actuals argument types.
   934                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   935                 args = args.tail;
   936                 forms = forms.tail;
   937             }
   939             args = type.getTypeArguments();
   940             List<Type> tvars_cap = types.substBounds(formals,
   941                                       formals,
   942                                       types.capture(type).allparams());
   943             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   944                 // Let the actual arguments know their bound
   945                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   946                 args = args.tail;
   947                 tvars_cap = tvars_cap.tail;
   948             }
   950             args = type.getTypeArguments();
   951             List<Type> bounds = bounds_buf.toList();
   953             while (args.nonEmpty() && bounds.nonEmpty()) {
   954                 Type actual = args.head;
   955                 if (!isTypeArgErroneous(actual) &&
   956                         !bounds.head.isErroneous() &&
   957                         !checkExtends(actual, bounds.head)) {
   958                     return args.head;
   959                 }
   960                 args = args.tail;
   961                 bounds = bounds.tail;
   962             }
   964             args = type.getTypeArguments();
   965             bounds = bounds_buf.toList();
   967             for (Type arg : types.capture(type).getTypeArguments()) {
   968                 if (arg.tag == TYPEVAR &&
   969                         arg.getUpperBound().isErroneous() &&
   970                         !bounds.head.isErroneous() &&
   971                         !isTypeArgErroneous(args.head)) {
   972                     return args.head;
   973                 }
   974                 bounds = bounds.tail;
   975                 args = args.tail;
   976             }
   978             return null;
   979         }
   980         //where
   981         boolean isTypeArgErroneous(Type t) {
   982             return isTypeArgErroneous.visit(t);
   983         }
   985         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
   986             public Boolean visitType(Type t, Void s) {
   987                 return t.isErroneous();
   988             }
   989             @Override
   990             public Boolean visitTypeVar(TypeVar t, Void s) {
   991                 return visit(t.getUpperBound());
   992             }
   993             @Override
   994             public Boolean visitCapturedType(CapturedType t, Void s) {
   995                 return visit(t.getUpperBound()) ||
   996                         visit(t.getLowerBound());
   997             }
   998             @Override
   999             public Boolean visitWildcardType(WildcardType t, Void s) {
  1000                 return visit(t.type);
  1002         };
  1004     /** Check that given modifiers are legal for given symbol and
  1005      *  return modifiers together with any implicit modififiers for that symbol.
  1006      *  Warning: we can't use flags() here since this method
  1007      *  is called during class enter, when flags() would cause a premature
  1008      *  completion.
  1009      *  @param pos           Position to be used for error reporting.
  1010      *  @param flags         The set of modifiers given in a definition.
  1011      *  @param sym           The defined symbol.
  1012      */
  1013     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
  1014         long mask;
  1015         long implicit = 0;
  1016         switch (sym.kind) {
  1017         case VAR:
  1018             if (sym.owner.kind != TYP)
  1019                 mask = LocalVarFlags;
  1020             else if ((sym.owner.flags_field & INTERFACE) != 0)
  1021                 mask = implicit = InterfaceVarFlags;
  1022             else
  1023                 mask = VarFlags;
  1024             break;
  1025         case MTH:
  1026             if (sym.name == names.init) {
  1027                 if ((sym.owner.flags_field & ENUM) != 0) {
  1028                     // enum constructors cannot be declared public or
  1029                     // protected and must be implicitly or explicitly
  1030                     // private
  1031                     implicit = PRIVATE;
  1032                     mask = PRIVATE;
  1033                 } else
  1034                     mask = ConstructorFlags;
  1035             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
  1036                 mask = implicit = InterfaceMethodFlags;
  1037             else {
  1038                 mask = MethodFlags;
  1040             // Imply STRICTFP if owner has STRICTFP set.
  1041             if (((flags|implicit) & Flags.ABSTRACT) == 0)
  1042               implicit |= sym.owner.flags_field & STRICTFP;
  1043             break;
  1044         case TYP:
  1045             if (sym.isLocal()) {
  1046                 mask = LocalClassFlags;
  1047                 if (sym.name.isEmpty()) { // Anonymous class
  1048                     // Anonymous classes in static methods are themselves static;
  1049                     // that's why we admit STATIC here.
  1050                     mask |= STATIC;
  1051                     // JLS: Anonymous classes are final.
  1052                     implicit |= FINAL;
  1054                 if ((sym.owner.flags_field & STATIC) == 0 &&
  1055                     (flags & ENUM) != 0)
  1056                     log.error(pos, "enums.must.be.static");
  1057             } else if (sym.owner.kind == TYP) {
  1058                 mask = MemberClassFlags;
  1059                 if (sym.owner.owner.kind == PCK ||
  1060                     (sym.owner.flags_field & STATIC) != 0)
  1061                     mask |= STATIC;
  1062                 else if ((flags & ENUM) != 0)
  1063                     log.error(pos, "enums.must.be.static");
  1064                 // Nested interfaces and enums are always STATIC (Spec ???)
  1065                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
  1066             } else {
  1067                 mask = ClassFlags;
  1069             // Interfaces are always ABSTRACT
  1070             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
  1072             if ((flags & ENUM) != 0) {
  1073                 // enums can't be declared abstract or final
  1074                 mask &= ~(ABSTRACT | FINAL);
  1075                 implicit |= implicitEnumFinalFlag(tree);
  1077             // Imply STRICTFP if owner has STRICTFP set.
  1078             implicit |= sym.owner.flags_field & STRICTFP;
  1079             break;
  1080         default:
  1081             throw new AssertionError();
  1083         long illegal = flags & StandardFlags & ~mask;
  1084         if (illegal != 0) {
  1085             if ((illegal & INTERFACE) != 0) {
  1086                 log.error(pos, "intf.not.allowed.here");
  1087                 mask |= INTERFACE;
  1089             else {
  1090                 log.error(pos,
  1091                           "mod.not.allowed.here", asFlagSet(illegal));
  1094         else if ((sym.kind == TYP ||
  1095                   // ISSUE: Disallowing abstract&private is no longer appropriate
  1096                   // in the presence of inner classes. Should it be deleted here?
  1097                   checkDisjoint(pos, flags,
  1098                                 ABSTRACT,
  1099                                 PRIVATE | STATIC))
  1100                  &&
  1101                  checkDisjoint(pos, flags,
  1102                                ABSTRACT | INTERFACE,
  1103                                FINAL | NATIVE | SYNCHRONIZED)
  1104                  &&
  1105                  checkDisjoint(pos, flags,
  1106                                PUBLIC,
  1107                                PRIVATE | PROTECTED)
  1108                  &&
  1109                  checkDisjoint(pos, flags,
  1110                                PRIVATE,
  1111                                PUBLIC | PROTECTED)
  1112                  &&
  1113                  checkDisjoint(pos, flags,
  1114                                FINAL,
  1115                                VOLATILE)
  1116                  &&
  1117                  (sym.kind == TYP ||
  1118                   checkDisjoint(pos, flags,
  1119                                 ABSTRACT | NATIVE,
  1120                                 STRICTFP))) {
  1121             // skip
  1123         return flags & (mask | ~StandardFlags) | implicit;
  1127     /** Determine if this enum should be implicitly final.
  1129      *  If the enum has no specialized enum contants, it is final.
  1131      *  If the enum does have specialized enum contants, it is
  1132      *  <i>not</i> final.
  1133      */
  1134     private long implicitEnumFinalFlag(JCTree tree) {
  1135         if (!tree.hasTag(CLASSDEF)) return 0;
  1136         class SpecialTreeVisitor extends JCTree.Visitor {
  1137             boolean specialized;
  1138             SpecialTreeVisitor() {
  1139                 this.specialized = false;
  1140             };
  1142             @Override
  1143             public void visitTree(JCTree tree) { /* no-op */ }
  1145             @Override
  1146             public void visitVarDef(JCVariableDecl tree) {
  1147                 if ((tree.mods.flags & ENUM) != 0) {
  1148                     if (tree.init instanceof JCNewClass &&
  1149                         ((JCNewClass) tree.init).def != null) {
  1150                         specialized = true;
  1156         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1157         JCClassDecl cdef = (JCClassDecl) tree;
  1158         for (JCTree defs: cdef.defs) {
  1159             defs.accept(sts);
  1160             if (sts.specialized) return 0;
  1162         return FINAL;
  1165 /* *************************************************************************
  1166  * Type Validation
  1167  **************************************************************************/
  1169     /** Validate a type expression. That is,
  1170      *  check that all type arguments of a parametric type are within
  1171      *  their bounds. This must be done in a second phase after type attributon
  1172      *  since a class might have a subclass as type parameter bound. E.g:
  1174      *  class B<A extends C> { ... }
  1175      *  class C extends B<C> { ... }
  1177      *  and we can't make sure that the bound is already attributed because
  1178      *  of possible cycles.
  1180      * Visitor method: Validate a type expression, if it is not null, catching
  1181      *  and reporting any completion failures.
  1182      */
  1183     void validate(JCTree tree, Env<AttrContext> env) {
  1184         validate(tree, env, true);
  1186     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1187         new Validator(env).validateTree(tree, checkRaw, true);
  1190     /** Visitor method: Validate a list of type expressions.
  1191      */
  1192     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1193         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1194             validate(l.head, env);
  1197     /** A visitor class for type validation.
  1198      */
  1199     class Validator extends JCTree.Visitor {
  1201         boolean isOuter;
  1202         Env<AttrContext> env;
  1204         Validator(Env<AttrContext> env) {
  1205             this.env = env;
  1208         @Override
  1209         public void visitTypeArray(JCArrayTypeTree tree) {
  1210             tree.elemtype.accept(this);
  1213         @Override
  1214         public void visitTypeApply(JCTypeApply tree) {
  1215             if (tree.type.tag == CLASS) {
  1216                 List<JCExpression> args = tree.arguments;
  1217                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1219                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1220                 if (incompatibleArg != null) {
  1221                     for (JCTree arg : tree.arguments) {
  1222                         if (arg.type == incompatibleArg) {
  1223                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1225                         forms = forms.tail;
  1229                 forms = tree.type.tsym.type.getTypeArguments();
  1231                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1233                 // For matching pairs of actual argument types `a' and
  1234                 // formal type parameters with declared bound `b' ...
  1235                 while (args.nonEmpty() && forms.nonEmpty()) {
  1236                     validateTree(args.head,
  1237                             !(isOuter && is_java_lang_Class),
  1238                             false);
  1239                     args = args.tail;
  1240                     forms = forms.tail;
  1243                 // Check that this type is either fully parameterized, or
  1244                 // not parameterized at all.
  1245                 if (tree.type.getEnclosingType().isRaw())
  1246                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1247                 if (tree.clazz.hasTag(SELECT))
  1248                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1252         @Override
  1253         public void visitTypeParameter(JCTypeParameter tree) {
  1254             validateTrees(tree.bounds, true, isOuter);
  1255             checkClassBounds(tree.pos(), tree.type);
  1258         @Override
  1259         public void visitWildcard(JCWildcard tree) {
  1260             if (tree.inner != null)
  1261                 validateTree(tree.inner, true, isOuter);
  1264         @Override
  1265         public void visitSelect(JCFieldAccess tree) {
  1266             if (tree.type.tag == CLASS) {
  1267                 visitSelectInternal(tree);
  1269                 // Check that this type is either fully parameterized, or
  1270                 // not parameterized at all.
  1271                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1272                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1276         public void visitSelectInternal(JCFieldAccess tree) {
  1277             if (tree.type.tsym.isStatic() &&
  1278                 tree.selected.type.isParameterized()) {
  1279                 // The enclosing type is not a class, so we are
  1280                 // looking at a static member type.  However, the
  1281                 // qualifying expression is parameterized.
  1282                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1283             } else {
  1284                 // otherwise validate the rest of the expression
  1285                 tree.selected.accept(this);
  1289         /** Default visitor method: do nothing.
  1290          */
  1291         @Override
  1292         public void visitTree(JCTree tree) {
  1295         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1296             try {
  1297                 if (tree != null) {
  1298                     this.isOuter = isOuter;
  1299                     tree.accept(this);
  1300                     if (checkRaw)
  1301                         checkRaw(tree, env);
  1303             } catch (CompletionFailure ex) {
  1304                 completionError(tree.pos(), ex);
  1308         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1309             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1310                 validateTree(l.head, checkRaw, isOuter);
  1313         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1314             if (lint.isEnabled(LintCategory.RAW) &&
  1315                 tree.type.tag == CLASS &&
  1316                 !TreeInfo.isDiamond(tree) &&
  1317                 !withinAnonConstr(env) &&
  1318                 tree.type.isRaw()) {
  1319                 log.warning(LintCategory.RAW,
  1320                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1324         boolean withinAnonConstr(Env<AttrContext> env) {
  1325             return env.enclClass.name.isEmpty() &&
  1326                     env.enclMethod != null && env.enclMethod.name == names.init;
  1330 /* *************************************************************************
  1331  * Exception checking
  1332  **************************************************************************/
  1334     /* The following methods treat classes as sets that contain
  1335      * the class itself and all their subclasses
  1336      */
  1338     /** Is given type a subtype of some of the types in given list?
  1339      */
  1340     boolean subset(Type t, List<Type> ts) {
  1341         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1342             if (types.isSubtype(t, l.head)) return true;
  1343         return false;
  1346     /** Is given type a subtype or supertype of
  1347      *  some of the types in given list?
  1348      */
  1349     boolean intersects(Type t, List<Type> ts) {
  1350         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1351             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1352         return false;
  1355     /** Add type set to given type list, unless it is a subclass of some class
  1356      *  in the list.
  1357      */
  1358     List<Type> incl(Type t, List<Type> ts) {
  1359         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1362     /** Remove type set from type set list.
  1363      */
  1364     List<Type> excl(Type t, List<Type> ts) {
  1365         if (ts.isEmpty()) {
  1366             return ts;
  1367         } else {
  1368             List<Type> ts1 = excl(t, ts.tail);
  1369             if (types.isSubtype(ts.head, t)) return ts1;
  1370             else if (ts1 == ts.tail) return ts;
  1371             else return ts1.prepend(ts.head);
  1375     /** Form the union of two type set lists.
  1376      */
  1377     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1378         List<Type> ts = ts1;
  1379         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1380             ts = incl(l.head, ts);
  1381         return ts;
  1384     /** Form the difference of two type lists.
  1385      */
  1386     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1387         List<Type> ts = ts1;
  1388         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1389             ts = excl(l.head, ts);
  1390         return ts;
  1393     /** Form the intersection of two type lists.
  1394      */
  1395     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1396         List<Type> ts = List.nil();
  1397         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1398             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1399         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1400             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1401         return ts;
  1404     /** Is exc an exception symbol that need not be declared?
  1405      */
  1406     boolean isUnchecked(ClassSymbol exc) {
  1407         return
  1408             exc.kind == ERR ||
  1409             exc.isSubClass(syms.errorType.tsym, types) ||
  1410             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1413     /** Is exc an exception type that need not be declared?
  1414      */
  1415     boolean isUnchecked(Type exc) {
  1416         return
  1417             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1418             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1419             exc.tag == BOT;
  1422     /** Same, but handling completion failures.
  1423      */
  1424     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1425         try {
  1426             return isUnchecked(exc);
  1427         } catch (CompletionFailure ex) {
  1428             completionError(pos, ex);
  1429             return true;
  1433     /** Is exc handled by given exception list?
  1434      */
  1435     boolean isHandled(Type exc, List<Type> handled) {
  1436         return isUnchecked(exc) || subset(exc, handled);
  1439     /** Return all exceptions in thrown list that are not in handled list.
  1440      *  @param thrown     The list of thrown exceptions.
  1441      *  @param handled    The list of handled exceptions.
  1442      */
  1443     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1444         List<Type> unhandled = List.nil();
  1445         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1446             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1447         return unhandled;
  1450 /* *************************************************************************
  1451  * Overriding/Implementation checking
  1452  **************************************************************************/
  1454     /** The level of access protection given by a flag set,
  1455      *  where PRIVATE is highest and PUBLIC is lowest.
  1456      */
  1457     static int protection(long flags) {
  1458         switch ((short)(flags & AccessFlags)) {
  1459         case PRIVATE: return 3;
  1460         case PROTECTED: return 1;
  1461         default:
  1462         case PUBLIC: return 0;
  1463         case 0: return 2;
  1467     /** A customized "cannot override" error message.
  1468      *  @param m      The overriding method.
  1469      *  @param other  The overridden method.
  1470      *  @return       An internationalized string.
  1471      */
  1472     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1473         String key;
  1474         if ((other.owner.flags() & INTERFACE) == 0)
  1475             key = "cant.override";
  1476         else if ((m.owner.flags() & INTERFACE) == 0)
  1477             key = "cant.implement";
  1478         else
  1479             key = "clashes.with";
  1480         return diags.fragment(key, m, m.location(), other, other.location());
  1483     /** A customized "override" warning message.
  1484      *  @param m      The overriding method.
  1485      *  @param other  The overridden method.
  1486      *  @return       An internationalized string.
  1487      */
  1488     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1489         String key;
  1490         if ((other.owner.flags() & INTERFACE) == 0)
  1491             key = "unchecked.override";
  1492         else if ((m.owner.flags() & INTERFACE) == 0)
  1493             key = "unchecked.implement";
  1494         else
  1495             key = "unchecked.clash.with";
  1496         return diags.fragment(key, m, m.location(), other, other.location());
  1499     /** A customized "override" warning message.
  1500      *  @param m      The overriding method.
  1501      *  @param other  The overridden method.
  1502      *  @return       An internationalized string.
  1503      */
  1504     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1505         String key;
  1506         if ((other.owner.flags() & INTERFACE) == 0)
  1507             key = "varargs.override";
  1508         else  if ((m.owner.flags() & INTERFACE) == 0)
  1509             key = "varargs.implement";
  1510         else
  1511             key = "varargs.clash.with";
  1512         return diags.fragment(key, m, m.location(), other, other.location());
  1515     /** Check that this method conforms with overridden method 'other'.
  1516      *  where `origin' is the class where checking started.
  1517      *  Complications:
  1518      *  (1) Do not check overriding of synthetic methods
  1519      *      (reason: they might be final).
  1520      *      todo: check whether this is still necessary.
  1521      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1522      *      than the method it implements. Augment the proxy methods with the
  1523      *      undeclared exceptions in this case.
  1524      *  (3) When generics are enabled, admit the case where an interface proxy
  1525      *      has a result type
  1526      *      extended by the result type of the method it implements.
  1527      *      Change the proxies result type to the smaller type in this case.
  1529      *  @param tree         The tree from which positions
  1530      *                      are extracted for errors.
  1531      *  @param m            The overriding method.
  1532      *  @param other        The overridden method.
  1533      *  @param origin       The class of which the overriding method
  1534      *                      is a member.
  1535      */
  1536     void checkOverride(JCTree tree,
  1537                        MethodSymbol m,
  1538                        MethodSymbol other,
  1539                        ClassSymbol origin) {
  1540         // Don't check overriding of synthetic methods or by bridge methods.
  1541         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1542             return;
  1545         // Error if static method overrides instance method (JLS 8.4.6.2).
  1546         if ((m.flags() & STATIC) != 0 &&
  1547                    (other.flags() & STATIC) == 0) {
  1548             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1549                       cannotOverride(m, other));
  1550             return;
  1553         // Error if instance method overrides static or final
  1554         // method (JLS 8.4.6.1).
  1555         if ((other.flags() & FINAL) != 0 ||
  1556                  (m.flags() & STATIC) == 0 &&
  1557                  (other.flags() & STATIC) != 0) {
  1558             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1559                       cannotOverride(m, other),
  1560                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1561             return;
  1564         if ((m.owner.flags() & ANNOTATION) != 0) {
  1565             // handled in validateAnnotationMethod
  1566             return;
  1569         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1570         if ((origin.flags() & INTERFACE) == 0 &&
  1571                  protection(m.flags()) > protection(other.flags())) {
  1572             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1573                       cannotOverride(m, other),
  1574                       other.flags() == 0 ?
  1575                           Flag.PACKAGE :
  1576                           asFlagSet(other.flags() & AccessFlags));
  1577             return;
  1580         Type mt = types.memberType(origin.type, m);
  1581         Type ot = types.memberType(origin.type, other);
  1582         // Error if overriding result type is different
  1583         // (or, in the case of generics mode, not a subtype) of
  1584         // overridden result type. We have to rename any type parameters
  1585         // before comparing types.
  1586         List<Type> mtvars = mt.getTypeArguments();
  1587         List<Type> otvars = ot.getTypeArguments();
  1588         Type mtres = mt.getReturnType();
  1589         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1591         overrideWarner.clear();
  1592         boolean resultTypesOK =
  1593             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1594         if (!resultTypesOK) {
  1595             if (!allowCovariantReturns &&
  1596                 m.owner != origin &&
  1597                 m.owner.isSubClass(other.owner, types)) {
  1598                 // allow limited interoperability with covariant returns
  1599             } else {
  1600                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1601                           "override.incompatible.ret",
  1602                           cannotOverride(m, other),
  1603                           mtres, otres);
  1604                 return;
  1606         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1607             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1608                     "override.unchecked.ret",
  1609                     uncheckedOverrides(m, other),
  1610                     mtres, otres);
  1613         // Error if overriding method throws an exception not reported
  1614         // by overridden method.
  1615         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1616         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1617         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1618         if (unhandledErased.nonEmpty()) {
  1619             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1620                       "override.meth.doesnt.throw",
  1621                       cannotOverride(m, other),
  1622                       unhandledUnerased.head);
  1623             return;
  1625         else if (unhandledUnerased.nonEmpty()) {
  1626             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1627                           "override.unchecked.thrown",
  1628                          cannotOverride(m, other),
  1629                          unhandledUnerased.head);
  1630             return;
  1633         // Optional warning if varargs don't agree
  1634         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1635             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1636             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1637                         ((m.flags() & Flags.VARARGS) != 0)
  1638                         ? "override.varargs.missing"
  1639                         : "override.varargs.extra",
  1640                         varargsOverrides(m, other));
  1643         // Warn if instance method overrides bridge method (compiler spec ??)
  1644         if ((other.flags() & BRIDGE) != 0) {
  1645             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1646                         uncheckedOverrides(m, other));
  1649         // Warn if a deprecated method overridden by a non-deprecated one.
  1650         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1651             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1654     // where
  1655         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1656             // If the method, m, is defined in an interface, then ignore the issue if the method
  1657             // is only inherited via a supertype and also implemented in the supertype,
  1658             // because in that case, we will rediscover the issue when examining the method
  1659             // in the supertype.
  1660             // If the method, m, is not defined in an interface, then the only time we need to
  1661             // address the issue is when the method is the supertype implemementation: any other
  1662             // case, we will have dealt with when examining the supertype classes
  1663             ClassSymbol mc = m.enclClass();
  1664             Type st = types.supertype(origin.type);
  1665             if (st.tag != CLASS)
  1666                 return true;
  1667             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1669             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1670                 List<Type> intfs = types.interfaces(origin.type);
  1671                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1673             else
  1674                 return (stimpl != m);
  1678     // used to check if there were any unchecked conversions
  1679     Warner overrideWarner = new Warner();
  1681     /** Check that a class does not inherit two concrete methods
  1682      *  with the same signature.
  1683      *  @param pos          Position to be used for error reporting.
  1684      *  @param site         The class type to be checked.
  1685      */
  1686     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1687         Type sup = types.supertype(site);
  1688         if (sup.tag != CLASS) return;
  1690         for (Type t1 = sup;
  1691              t1.tsym.type.isParameterized();
  1692              t1 = types.supertype(t1)) {
  1693             for (Scope.Entry e1 = t1.tsym.members().elems;
  1694                  e1 != null;
  1695                  e1 = e1.sibling) {
  1696                 Symbol s1 = e1.sym;
  1697                 if (s1.kind != MTH ||
  1698                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1699                     !s1.isInheritedIn(site.tsym, types) ||
  1700                     ((MethodSymbol)s1).implementation(site.tsym,
  1701                                                       types,
  1702                                                       true) != s1)
  1703                     continue;
  1704                 Type st1 = types.memberType(t1, s1);
  1705                 int s1ArgsLength = st1.getParameterTypes().length();
  1706                 if (st1 == s1.type) continue;
  1708                 for (Type t2 = sup;
  1709                      t2.tag == CLASS;
  1710                      t2 = types.supertype(t2)) {
  1711                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1712                          e2.scope != null;
  1713                          e2 = e2.next()) {
  1714                         Symbol s2 = e2.sym;
  1715                         if (s2 == s1 ||
  1716                             s2.kind != MTH ||
  1717                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1718                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1719                             !s2.isInheritedIn(site.tsym, types) ||
  1720                             ((MethodSymbol)s2).implementation(site.tsym,
  1721                                                               types,
  1722                                                               true) != s2)
  1723                             continue;
  1724                         Type st2 = types.memberType(t2, s2);
  1725                         if (types.overrideEquivalent(st1, st2))
  1726                             log.error(pos, "concrete.inheritance.conflict",
  1727                                       s1, t1, s2, t2, sup);
  1734     /** Check that classes (or interfaces) do not each define an abstract
  1735      *  method with same name and arguments but incompatible return types.
  1736      *  @param pos          Position to be used for error reporting.
  1737      *  @param t1           The first argument type.
  1738      *  @param t2           The second argument type.
  1739      */
  1740     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1741                                             Type t1,
  1742                                             Type t2) {
  1743         return checkCompatibleAbstracts(pos, t1, t2,
  1744                                         types.makeCompoundType(t1, t2));
  1747     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1748                                             Type t1,
  1749                                             Type t2,
  1750                                             Type site) {
  1751         return firstIncompatibility(pos, t1, t2, site) == null;
  1754     /** Return the first method which is defined with same args
  1755      *  but different return types in two given interfaces, or null if none
  1756      *  exists.
  1757      *  @param t1     The first type.
  1758      *  @param t2     The second type.
  1759      *  @param site   The most derived type.
  1760      *  @returns symbol from t2 that conflicts with one in t1.
  1761      */
  1762     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1763         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1764         closure(t1, interfaces1);
  1765         Map<TypeSymbol,Type> interfaces2;
  1766         if (t1 == t2)
  1767             interfaces2 = interfaces1;
  1768         else
  1769             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1771         for (Type t3 : interfaces1.values()) {
  1772             for (Type t4 : interfaces2.values()) {
  1773                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1774                 if (s != null) return s;
  1777         return null;
  1780     /** Compute all the supertypes of t, indexed by type symbol. */
  1781     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1782         if (t.tag != CLASS) return;
  1783         if (typeMap.put(t.tsym, t) == null) {
  1784             closure(types.supertype(t), typeMap);
  1785             for (Type i : types.interfaces(t))
  1786                 closure(i, typeMap);
  1790     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1791     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1792         if (t.tag != CLASS) return;
  1793         if (typesSkip.get(t.tsym) != null) return;
  1794         if (typeMap.put(t.tsym, t) == null) {
  1795             closure(types.supertype(t), typesSkip, typeMap);
  1796             for (Type i : types.interfaces(t))
  1797                 closure(i, typesSkip, typeMap);
  1801     /** Return the first method in t2 that conflicts with a method from t1. */
  1802     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1803         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1804             Symbol s1 = e1.sym;
  1805             Type st1 = null;
  1806             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1807             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1808             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1809             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1810                 Symbol s2 = e2.sym;
  1811                 if (s1 == s2) continue;
  1812                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1813                 if (st1 == null) st1 = types.memberType(t1, s1);
  1814                 Type st2 = types.memberType(t2, s2);
  1815                 if (types.overrideEquivalent(st1, st2)) {
  1816                     List<Type> tvars1 = st1.getTypeArguments();
  1817                     List<Type> tvars2 = st2.getTypeArguments();
  1818                     Type rt1 = st1.getReturnType();
  1819                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1820                     boolean compat =
  1821                         types.isSameType(rt1, rt2) ||
  1822                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1823                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1824                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1825                          checkCommonOverriderIn(s1,s2,site);
  1826                     if (!compat) {
  1827                         log.error(pos, "types.incompatible.diff.ret",
  1828                             t1, t2, s2.name +
  1829                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1830                         return s2;
  1832                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1833                         !checkCommonOverriderIn(s1, s2, site)) {
  1834                     log.error(pos,
  1835                             "name.clash.same.erasure.no.override",
  1836                             s1, s1.location(),
  1837                             s2, s2.location());
  1838                     return s2;
  1842         return null;
  1844     //WHERE
  1845     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1846         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1847         Type st1 = types.memberType(site, s1);
  1848         Type st2 = types.memberType(site, s2);
  1849         closure(site, supertypes);
  1850         for (Type t : supertypes.values()) {
  1851             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1852                 Symbol s3 = e.sym;
  1853                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1854                 Type st3 = types.memberType(site,s3);
  1855                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1856                     if (s3.owner == site.tsym) {
  1857                         return true;
  1859                     List<Type> tvars1 = st1.getTypeArguments();
  1860                     List<Type> tvars2 = st2.getTypeArguments();
  1861                     List<Type> tvars3 = st3.getTypeArguments();
  1862                     Type rt1 = st1.getReturnType();
  1863                     Type rt2 = st2.getReturnType();
  1864                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1865                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1866                     boolean compat =
  1867                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1868                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1869                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1870                     if (compat)
  1871                         return true;
  1875         return false;
  1878     /** Check that a given method conforms with any method it overrides.
  1879      *  @param tree         The tree from which positions are extracted
  1880      *                      for errors.
  1881      *  @param m            The overriding method.
  1882      */
  1883     void checkOverride(JCTree tree, MethodSymbol m) {
  1884         ClassSymbol origin = (ClassSymbol)m.owner;
  1885         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1886             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1887                 log.error(tree.pos(), "enum.no.finalize");
  1888                 return;
  1890         for (Type t = origin.type; t.tag == CLASS;
  1891              t = types.supertype(t)) {
  1892             if (t != origin.type) {
  1893                 checkOverride(tree, t, origin, m);
  1895             for (Type t2 : types.interfaces(t)) {
  1896                 checkOverride(tree, t2, origin, m);
  1901     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1902         TypeSymbol c = site.tsym;
  1903         Scope.Entry e = c.members().lookup(m.name);
  1904         while (e.scope != null) {
  1905             if (m.overrides(e.sym, origin, types, false)) {
  1906                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1907                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1910             e = e.next();
  1914     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1915         ClashFilter cf = new ClashFilter(origin.type);
  1916         return (cf.accepts(s1) &&
  1917                 cf.accepts(s2) &&
  1918                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1922     /** Check that all abstract members of given class have definitions.
  1923      *  @param pos          Position to be used for error reporting.
  1924      *  @param c            The class.
  1925      */
  1926     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1927         try {
  1928             MethodSymbol undef = firstUndef(c, c);
  1929             if (undef != null) {
  1930                 if ((c.flags() & ENUM) != 0 &&
  1931                     types.supertype(c.type).tsym == syms.enumSym &&
  1932                     (c.flags() & FINAL) == 0) {
  1933                     // add the ABSTRACT flag to an enum
  1934                     c.flags_field |= ABSTRACT;
  1935                 } else {
  1936                     MethodSymbol undef1 =
  1937                         new MethodSymbol(undef.flags(), undef.name,
  1938                                          types.memberType(c.type, undef), undef.owner);
  1939                     log.error(pos, "does.not.override.abstract",
  1940                               c, undef1, undef1.location());
  1943         } catch (CompletionFailure ex) {
  1944             completionError(pos, ex);
  1947 //where
  1948         /** Return first abstract member of class `c' that is not defined
  1949          *  in `impl', null if there is none.
  1950          */
  1951         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1952             MethodSymbol undef = null;
  1953             // Do not bother to search in classes that are not abstract,
  1954             // since they cannot have abstract members.
  1955             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1956                 Scope s = c.members();
  1957                 for (Scope.Entry e = s.elems;
  1958                      undef == null && e != null;
  1959                      e = e.sibling) {
  1960                     if (e.sym.kind == MTH &&
  1961                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1962                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1963                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1964                         if (implmeth == null || implmeth == absmeth)
  1965                             undef = absmeth;
  1968                 if (undef == null) {
  1969                     Type st = types.supertype(c.type);
  1970                     if (st.tag == CLASS)
  1971                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1973                 for (List<Type> l = types.interfaces(c.type);
  1974                      undef == null && l.nonEmpty();
  1975                      l = l.tail) {
  1976                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1979             return undef;
  1982     void checkNonCyclicDecl(JCClassDecl tree) {
  1983         CycleChecker cc = new CycleChecker();
  1984         cc.scan(tree);
  1985         if (!cc.errorFound && !cc.partialCheck) {
  1986             tree.sym.flags_field |= ACYCLIC;
  1990     class CycleChecker extends TreeScanner {
  1992         List<Symbol> seenClasses = List.nil();
  1993         boolean errorFound = false;
  1994         boolean partialCheck = false;
  1996         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  1997             if (sym != null && sym.kind == TYP) {
  1998                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  1999                 if (classEnv != null) {
  2000                     DiagnosticSource prevSource = log.currentSource();
  2001                     try {
  2002                         log.useSource(classEnv.toplevel.sourcefile);
  2003                         scan(classEnv.tree);
  2005                     finally {
  2006                         log.useSource(prevSource.getFile());
  2008                 } else if (sym.kind == TYP) {
  2009                     checkClass(pos, sym, List.<JCTree>nil());
  2011             } else {
  2012                 //not completed yet
  2013                 partialCheck = true;
  2017         @Override
  2018         public void visitSelect(JCFieldAccess tree) {
  2019             super.visitSelect(tree);
  2020             checkSymbol(tree.pos(), tree.sym);
  2023         @Override
  2024         public void visitIdent(JCIdent tree) {
  2025             checkSymbol(tree.pos(), tree.sym);
  2028         @Override
  2029         public void visitTypeApply(JCTypeApply tree) {
  2030             scan(tree.clazz);
  2033         @Override
  2034         public void visitTypeArray(JCArrayTypeTree tree) {
  2035             scan(tree.elemtype);
  2038         @Override
  2039         public void visitClassDef(JCClassDecl tree) {
  2040             List<JCTree> supertypes = List.nil();
  2041             if (tree.getExtendsClause() != null) {
  2042                 supertypes = supertypes.prepend(tree.getExtendsClause());
  2044             if (tree.getImplementsClause() != null) {
  2045                 for (JCTree intf : tree.getImplementsClause()) {
  2046                     supertypes = supertypes.prepend(intf);
  2049             checkClass(tree.pos(), tree.sym, supertypes);
  2052         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  2053             if ((c.flags_field & ACYCLIC) != 0)
  2054                 return;
  2055             if (seenClasses.contains(c)) {
  2056                 errorFound = true;
  2057                 noteCyclic(pos, (ClassSymbol)c);
  2058             } else if (!c.type.isErroneous()) {
  2059                 try {
  2060                     seenClasses = seenClasses.prepend(c);
  2061                     if (c.type.tag == CLASS) {
  2062                         if (supertypes.nonEmpty()) {
  2063                             scan(supertypes);
  2065                         else {
  2066                             ClassType ct = (ClassType)c.type;
  2067                             if (ct.supertype_field == null ||
  2068                                     ct.interfaces_field == null) {
  2069                                 //not completed yet
  2070                                 partialCheck = true;
  2071                                 return;
  2073                             checkSymbol(pos, ct.supertype_field.tsym);
  2074                             for (Type intf : ct.interfaces_field) {
  2075                                 checkSymbol(pos, intf.tsym);
  2078                         if (c.owner.kind == TYP) {
  2079                             checkSymbol(pos, c.owner);
  2082                 } finally {
  2083                     seenClasses = seenClasses.tail;
  2089     /** Check for cyclic references. Issue an error if the
  2090      *  symbol of the type referred to has a LOCKED flag set.
  2092      *  @param pos      Position to be used for error reporting.
  2093      *  @param t        The type referred to.
  2094      */
  2095     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  2096         checkNonCyclicInternal(pos, t);
  2100     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  2101         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  2104     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  2105         final TypeVar tv;
  2106         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  2107             return;
  2108         if (seen.contains(t)) {
  2109             tv = (TypeVar)t;
  2110             tv.bound = types.createErrorType(t);
  2111             log.error(pos, "cyclic.inheritance", t);
  2112         } else if (t.tag == TYPEVAR) {
  2113             tv = (TypeVar)t;
  2114             seen = seen.prepend(tv);
  2115             for (Type b : types.getBounds(tv))
  2116                 checkNonCyclic1(pos, b, seen);
  2120     /** Check for cyclic references. Issue an error if the
  2121      *  symbol of the type referred to has a LOCKED flag set.
  2123      *  @param pos      Position to be used for error reporting.
  2124      *  @param t        The type referred to.
  2125      *  @returns        True if the check completed on all attributed classes
  2126      */
  2127     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  2128         boolean complete = true; // was the check complete?
  2129         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  2130         Symbol c = t.tsym;
  2131         if ((c.flags_field & ACYCLIC) != 0) return true;
  2133         if ((c.flags_field & LOCKED) != 0) {
  2134             noteCyclic(pos, (ClassSymbol)c);
  2135         } else if (!c.type.isErroneous()) {
  2136             try {
  2137                 c.flags_field |= LOCKED;
  2138                 if (c.type.tag == CLASS) {
  2139                     ClassType clazz = (ClassType)c.type;
  2140                     if (clazz.interfaces_field != null)
  2141                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2142                             complete &= checkNonCyclicInternal(pos, l.head);
  2143                     if (clazz.supertype_field != null) {
  2144                         Type st = clazz.supertype_field;
  2145                         if (st != null && st.tag == CLASS)
  2146                             complete &= checkNonCyclicInternal(pos, st);
  2148                     if (c.owner.kind == TYP)
  2149                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2151             } finally {
  2152                 c.flags_field &= ~LOCKED;
  2155         if (complete)
  2156             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2157         if (complete) c.flags_field |= ACYCLIC;
  2158         return complete;
  2161     /** Note that we found an inheritance cycle. */
  2162     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2163         log.error(pos, "cyclic.inheritance", c);
  2164         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2165             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2166         Type st = types.supertype(c.type);
  2167         if (st.tag == CLASS)
  2168             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2169         c.type = types.createErrorType(c, c.type);
  2170         c.flags_field |= ACYCLIC;
  2173     /** Check that all methods which implement some
  2174      *  method conform to the method they implement.
  2175      *  @param tree         The class definition whose members are checked.
  2176      */
  2177     void checkImplementations(JCClassDecl tree) {
  2178         checkImplementations(tree, tree.sym);
  2180 //where
  2181         /** Check that all methods which implement some
  2182          *  method in `ic' conform to the method they implement.
  2183          */
  2184         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  2185             ClassSymbol origin = tree.sym;
  2186             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2187                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2188                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2189                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2190                         if (e.sym.kind == MTH &&
  2191                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2192                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2193                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2194                             if (implmeth != null && implmeth != absmeth &&
  2195                                 (implmeth.owner.flags() & INTERFACE) ==
  2196                                 (origin.flags() & INTERFACE)) {
  2197                                 // don't check if implmeth is in a class, yet
  2198                                 // origin is an interface. This case arises only
  2199                                 // if implmeth is declared in Object. The reason is
  2200                                 // that interfaces really don't inherit from
  2201                                 // Object it's just that the compiler represents
  2202                                 // things that way.
  2203                                 checkOverride(tree, implmeth, absmeth, origin);
  2211     /** Check that all abstract methods implemented by a class are
  2212      *  mutually compatible.
  2213      *  @param pos          Position to be used for error reporting.
  2214      *  @param c            The class whose interfaces are checked.
  2215      */
  2216     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2217         List<Type> supertypes = types.interfaces(c);
  2218         Type supertype = types.supertype(c);
  2219         if (supertype.tag == CLASS &&
  2220             (supertype.tsym.flags() & ABSTRACT) != 0)
  2221             supertypes = supertypes.prepend(supertype);
  2222         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2223             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2224                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2225                 return;
  2226             for (List<Type> m = supertypes; m != l; m = m.tail)
  2227                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2228                     return;
  2230         checkCompatibleConcretes(pos, c);
  2233     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2234         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2235             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2236                 // VM allows methods and variables with differing types
  2237                 if (sym.kind == e.sym.kind &&
  2238                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2239                     sym != e.sym &&
  2240                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2241                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2242                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2243                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2244                     return;
  2250     /** Check that all non-override equivalent methods accessible from 'site'
  2251      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2253      *  @param pos  Position to be used for error reporting.
  2254      *  @param site The class whose methods are checked.
  2255      *  @param sym  The method symbol to be checked.
  2256      */
  2257     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2258          ClashFilter cf = new ClashFilter(site);
  2259         //for each method m1 that is overridden (directly or indirectly)
  2260         //by method 'sym' in 'site'...
  2261         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2262             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2263              //...check each method m2 that is a member of 'site'
  2264              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2265                 if (m2 == m1) continue;
  2266                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2267                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2268                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
  2269                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2270                     sym.flags_field |= CLASH;
  2271                     String key = m1 == sym ?
  2272                             "name.clash.same.erasure.no.override" :
  2273                             "name.clash.same.erasure.no.override.1";
  2274                     log.error(pos,
  2275                             key,
  2276                             sym, sym.location(),
  2277                             m2, m2.location(),
  2278                             m1, m1.location());
  2279                     return;
  2287     /** Check that all static methods accessible from 'site' are
  2288      *  mutually compatible (JLS 8.4.8).
  2290      *  @param pos  Position to be used for error reporting.
  2291      *  @param site The class whose methods are checked.
  2292      *  @param sym  The method symbol to be checked.
  2293      */
  2294     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2295         ClashFilter cf = new ClashFilter(site);
  2296         //for each method m1 that is a member of 'site'...
  2297         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2298             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2299             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2300             if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
  2301                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2302                 log.error(pos,
  2303                         "name.clash.same.erasure.no.hide",
  2304                         sym, sym.location(),
  2305                         s, s.location());
  2306                 return;
  2311      //where
  2312      private class ClashFilter implements Filter<Symbol> {
  2314          Type site;
  2316          ClashFilter(Type site) {
  2317              this.site = site;
  2320          boolean shouldSkip(Symbol s) {
  2321              return (s.flags() & CLASH) != 0 &&
  2322                 s.owner == site.tsym;
  2325          public boolean accepts(Symbol s) {
  2326              return s.kind == MTH &&
  2327                      (s.flags() & SYNTHETIC) == 0 &&
  2328                      !shouldSkip(s) &&
  2329                      s.isInheritedIn(site.tsym, types) &&
  2330                      !s.isConstructor();
  2334     /** Report a conflict between a user symbol and a synthetic symbol.
  2335      */
  2336     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2337         if (!sym.type.isErroneous()) {
  2338             if (warnOnSyntheticConflicts) {
  2339                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2341             else {
  2342                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2347     /** Check that class c does not implement directly or indirectly
  2348      *  the same parameterized interface with two different argument lists.
  2349      *  @param pos          Position to be used for error reporting.
  2350      *  @param type         The type whose interfaces are checked.
  2351      */
  2352     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2353         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2355 //where
  2356         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2357          *  with their class symbol as key and their type as value. Make
  2358          *  sure no class is entered with two different types.
  2359          */
  2360         void checkClassBounds(DiagnosticPosition pos,
  2361                               Map<TypeSymbol,Type> seensofar,
  2362                               Type type) {
  2363             if (type.isErroneous()) return;
  2364             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2365                 Type it = l.head;
  2366                 Type oldit = seensofar.put(it.tsym, it);
  2367                 if (oldit != null) {
  2368                     List<Type> oldparams = oldit.allparams();
  2369                     List<Type> newparams = it.allparams();
  2370                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2371                         log.error(pos, "cant.inherit.diff.arg",
  2372                                   it.tsym, Type.toString(oldparams),
  2373                                   Type.toString(newparams));
  2375                 checkClassBounds(pos, seensofar, it);
  2377             Type st = types.supertype(type);
  2378             if (st != null) checkClassBounds(pos, seensofar, st);
  2381     /** Enter interface into into set.
  2382      *  If it existed already, issue a "repeated interface" error.
  2383      */
  2384     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2385         if (its.contains(it))
  2386             log.error(pos, "repeated.interface");
  2387         else {
  2388             its.add(it);
  2392 /* *************************************************************************
  2393  * Check annotations
  2394  **************************************************************************/
  2396     /**
  2397      * Recursively validate annotations values
  2398      */
  2399     void validateAnnotationTree(JCTree tree) {
  2400         class AnnotationValidator extends TreeScanner {
  2401             @Override
  2402             public void visitAnnotation(JCAnnotation tree) {
  2403                 if (!tree.type.isErroneous()) {
  2404                     super.visitAnnotation(tree);
  2405                     validateAnnotation(tree);
  2409         tree.accept(new AnnotationValidator());
  2412     /**
  2413      *  {@literal
  2414      *  Annotation types are restricted to primitives, String, an
  2415      *  enum, an annotation, Class, Class<?>, Class<? extends
  2416      *  Anything>, arrays of the preceding.
  2417      *  }
  2418      */
  2419     void validateAnnotationType(JCTree restype) {
  2420         // restype may be null if an error occurred, so don't bother validating it
  2421         if (restype != null) {
  2422             validateAnnotationType(restype.pos(), restype.type);
  2426     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2427         if (type.isPrimitive()) return;
  2428         if (types.isSameType(type, syms.stringType)) return;
  2429         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2430         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2431         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2432         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2433             validateAnnotationType(pos, types.elemtype(type));
  2434             return;
  2436         log.error(pos, "invalid.annotation.member.type");
  2439     /**
  2440      * "It is also a compile-time error if any method declared in an
  2441      * annotation type has a signature that is override-equivalent to
  2442      * that of any public or protected method declared in class Object
  2443      * or in the interface annotation.Annotation."
  2445      * @jls 9.6 Annotation Types
  2446      */
  2447     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2448         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2449             Scope s = sup.tsym.members();
  2450             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2451                 if (e.sym.kind == MTH &&
  2452                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2453                     types.overrideEquivalent(m.type, e.sym.type))
  2454                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2459     /** Check the annotations of a symbol.
  2460      */
  2461     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2462         for (JCAnnotation a : annotations)
  2463             validateAnnotation(a, s);
  2466     /** Check an annotation of a symbol.
  2467      */
  2468     private void validateAnnotation(JCAnnotation a, Symbol s) {
  2469         validateAnnotationTree(a);
  2471         if (!annotationApplicable(a, s))
  2472             log.error(a.pos(), "annotation.type.not.applicable");
  2474         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2475             if (!isOverrider(s))
  2476                 log.error(a.pos(), "method.does.not.override.superclass");
  2480     /**
  2481      * Validate the proposed container 'containedBy' on the
  2482      * annotation type symbol 's'. Report errors at position
  2483      * 'pos'.
  2485      * @param s The (annotation)type declaration annotated with a @ContainedBy
  2486      * @param containerAnno the @ContainedBy on 's'
  2487      * @param pos where to report errors
  2488      */
  2489     public void validateContainedBy(TypeSymbol s, Attribute.Compound containedBy, DiagnosticPosition pos) {
  2490         Assert.check(types.isSameType(containedBy.type, syms.containedByType));
  2492         Type t = null;
  2493         List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
  2494         if (!l.isEmpty()) {
  2495             Assert.check(l.head.fst.name == names.value);
  2496             t = ((Attribute.Class)l.head.snd).getValue();
  2499         if (t == null) {
  2500             log.error(pos, "invalid.container.wrong.containedby", s, containedBy);
  2501             return;
  2504         validateHasContainerFor(t.tsym, s, pos);
  2505         validateRetention(t.tsym, s, pos);
  2506         validateDocumented(t.tsym, s, pos);
  2507         validateInherited(t.tsym, s, pos);
  2508         validateTarget(t.tsym, s, pos);
  2509         validateDefault(t.tsym, s, pos);
  2512     /**
  2513      * Validate the proposed container 'containerFor' on the
  2514      * annotation type symbol 's'. Report errors at position
  2515      * 'pos'.
  2517      * @param s The (annotation)type declaration annotated with a @ContainerFor
  2518      * @param containerFor the @ContainedFor on 's'
  2519      * @param pos where to report errors
  2520      */
  2521     public void validateContainerFor(TypeSymbol s, Attribute.Compound containerFor, DiagnosticPosition pos) {
  2522         Assert.check(types.isSameType(containerFor.type, syms.containerForType));
  2524         Type t = null;
  2525         List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
  2526         if (!l.isEmpty()) {
  2527             Assert.check(l.head.fst.name == names.value);
  2528             t = ((Attribute.Class)l.head.snd).getValue();
  2531         if (t == null) {
  2532             log.error(pos, "invalid.container.wrong.containerfor", s, containerFor);
  2533             return;
  2536         validateHasContainedBy(t.tsym, s, pos);
  2539     private void validateHasContainedBy(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2540         Attribute.Compound containedBy = container.attribute(syms.containedByType.tsym);
  2542         if (containedBy == null) {
  2543             log.error(pos, "invalid.container.no.containedby", container, syms.containedByType.tsym);
  2544             return;
  2547         Type t = null;
  2548         List<Pair<MethodSymbol,Attribute>> l = containedBy.values;
  2549         if (!l.isEmpty()) {
  2550             Assert.check(l.head.fst.name == names.value);
  2551             t = ((Attribute.Class)l.head.snd).getValue();
  2554         if (t == null) {
  2555             log.error(pos, "invalid.container.wrong.containedby", container, contained);
  2556             return;
  2559         if (!types.isSameType(t, contained.type))
  2560             log.error(pos, "invalid.container.wrong.containedby", t.tsym, contained);
  2563     private void validateHasContainerFor(TypeSymbol container, TypeSymbol contained, DiagnosticPosition pos) {
  2564         Attribute.Compound containerFor = container.attribute(syms.containerForType.tsym);
  2566         if (containerFor == null) {
  2567             log.error(pos, "invalid.container.no.containerfor", container, syms.containerForType.tsym);
  2568             return;
  2571         Type t = null;
  2572         List<Pair<MethodSymbol,Attribute>> l = containerFor.values;
  2573         if (!l.isEmpty()) {
  2574             Assert.check(l.head.fst.name == names.value);
  2575             t = ((Attribute.Class)l.head.snd).getValue();
  2578         if (t == null) {
  2579             log.error(pos, "invalid.container.wrong.containerfor", container, contained);
  2580             return;
  2583         if (!types.isSameType(t, contained.type))
  2584             log.error(pos, "invalid.container.wrong.containerfor", t.tsym, contained);
  2587     private void validateRetention(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2588         Attribute.RetentionPolicy containerRetention = types.getRetention(container);
  2589         Attribute.RetentionPolicy containedRetention = types.getRetention(contained);
  2591         boolean error = false;
  2592         switch (containedRetention) {
  2593         case RUNTIME:
  2594             if (containerRetention != Attribute.RetentionPolicy.RUNTIME) {
  2595                 error = true;
  2597             break;
  2598         case CLASS:
  2599             if (containerRetention == Attribute.RetentionPolicy.SOURCE)  {
  2600                 error = true;
  2603         if (error ) {
  2604             log.error(pos, "invalid.containedby.annotation.retention",
  2605                       container, containerRetention,
  2606                       contained, containedRetention);
  2610     private void validateDocumented(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2611         if (contained.attribute(syms.documentedType.tsym) != null) {
  2612             if (container.attribute(syms.documentedType.tsym) == null) {
  2613                 log.error(pos, "invalid.containedby.annotation.not.documented", container, contained);
  2618     private void validateInherited(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2619         if (contained.attribute(syms.inheritedType.tsym) != null) {
  2620             if (container.attribute(syms.inheritedType.tsym) == null) {
  2621                 log.error(pos, "invalid.containedby.annotation.not.inherited", container, contained);
  2626     private void validateTarget(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2627         Attribute.Array containedTarget = getAttributeTargetAttribute(contained);
  2629         // If contained has no Target, we are done
  2630         if (containedTarget == null) {
  2631             return;
  2634         // If contained has Target m1, container must have a Target
  2635         // annotation, m2, and m2 must be a subset of m1. (This is
  2636         // trivially true if contained has no target as per above).
  2638         // contained has target, but container has not, error
  2639         Attribute.Array containerTarget = getAttributeTargetAttribute(container);
  2640         if (containerTarget == null) {
  2641             log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
  2642             return;
  2645         Set<Name> containerTargets = new HashSet<Name>();
  2646         for (Attribute app : containerTarget.values) {
  2647             if (!(app instanceof Attribute.Enum)) {
  2648                 continue; // recovery
  2650             Attribute.Enum e = (Attribute.Enum)app;
  2651             containerTargets.add(e.value.name);
  2654         Set<Name> containedTargets = new HashSet<Name>();
  2655         for (Attribute app : containedTarget.values) {
  2656             if (!(app instanceof Attribute.Enum)) {
  2657                 continue; // recovery
  2659             Attribute.Enum e = (Attribute.Enum)app;
  2660             containedTargets.add(e.value.name);
  2663         if (!isTargetSubset(containedTargets, containerTargets)) {
  2664             log.error(pos, "invalid.containedby.annotation.incompatible.target", container, contained);
  2668     /** Checks that t is a subset of s, with respect to ElementType
  2669      * semantics, specifically {ANNOTATION_TYPE} is a subset of {TYPE}
  2670      */
  2671     private boolean isTargetSubset(Set<Name> s, Set<Name> t) {
  2672         // Check that all elements in t are present in s
  2673         for (Name n2 : t) {
  2674             boolean currentElementOk = false;
  2675             for (Name n1 : s) {
  2676                 if (n1 == n2) {
  2677                     currentElementOk = true;
  2678                     break;
  2679                 } else if (n1 == names.TYPE && n2 == names.ANNOTATION_TYPE) {
  2680                     currentElementOk = true;
  2681                     break;
  2684             if (!currentElementOk)
  2685                 return false;
  2687         return true;
  2690     private void validateDefault(Symbol container, Symbol contained, DiagnosticPosition pos) {
  2691         // validate that all other elements of containing type has defaults
  2692         Scope scope = container.members();
  2693         for(Symbol elm : scope.getElements()) {
  2694             if (elm.name != names.value &&
  2695                 elm.kind == Kinds.MTH &&
  2696                 ((MethodSymbol)elm).defaultValue == null) {
  2697                 log.error(pos,
  2698                           "invalid.containedby.annotation.elem.nondefault",
  2699                           container,
  2700                           elm);
  2705     /** Is s a method symbol that overrides a method in a superclass? */
  2706     boolean isOverrider(Symbol s) {
  2707         if (s.kind != MTH || s.isStatic())
  2708             return false;
  2709         MethodSymbol m = (MethodSymbol)s;
  2710         TypeSymbol owner = (TypeSymbol)m.owner;
  2711         for (Type sup : types.closure(owner.type)) {
  2712             if (sup == owner.type)
  2713                 continue; // skip "this"
  2714             Scope scope = sup.tsym.members();
  2715             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2716                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2717                     return true;
  2720         return false;
  2723     /** Is the annotation applicable to the symbol? */
  2724     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2725         Attribute.Array arr = getAttributeTargetAttribute(a.annotationType.type.tsym);
  2726         if (arr == null) {
  2727             return true;
  2729         for (Attribute app : arr.values) {
  2730             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2731             Attribute.Enum e = (Attribute.Enum) app;
  2732             if (e.value.name == names.TYPE)
  2733                 { if (s.kind == TYP) return true; }
  2734             else if (e.value.name == names.FIELD)
  2735                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2736             else if (e.value.name == names.METHOD)
  2737                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2738             else if (e.value.name == names.PARAMETER)
  2739                 { if (s.kind == VAR &&
  2740                       s.owner.kind == MTH &&
  2741                       (s.flags() & PARAMETER) != 0)
  2742                     return true;
  2744             else if (e.value.name == names.CONSTRUCTOR)
  2745                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2746             else if (e.value.name == names.LOCAL_VARIABLE)
  2747                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2748                       (s.flags() & PARAMETER) == 0)
  2749                     return true;
  2751             else if (e.value.name == names.ANNOTATION_TYPE)
  2752                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2753                     return true;
  2755             else if (e.value.name == names.PACKAGE)
  2756                 { if (s.kind == PCK) return true; }
  2757             else if (e.value.name == names.TYPE_USE)
  2758                 { if (s.kind == TYP ||
  2759                       s.kind == VAR ||
  2760                       (s.kind == MTH && !s.isConstructor() &&
  2761                        s.type.getReturnType().tag != VOID))
  2762                     return true;
  2764             else
  2765                 return true; // recovery
  2767         return false;
  2771     Attribute.Array getAttributeTargetAttribute(Symbol s) {
  2772         Attribute.Compound atTarget =
  2773             s.attribute(syms.annotationTargetType.tsym);
  2774         if (atTarget == null) return null; // ok, is applicable
  2775         Attribute atValue = atTarget.member(names.value);
  2776         if (!(atValue instanceof Attribute.Array)) return null; // error recovery
  2777         return (Attribute.Array) atValue;
  2780     /** Check an annotation value.
  2781      */
  2782     public void validateAnnotation(JCAnnotation a) {
  2783         // collect an inventory of the members (sorted alphabetically)
  2784         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2785             public int compare(Symbol t, Symbol t1) {
  2786                 return t.name.compareTo(t1.name);
  2788         });
  2789         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2790              e != null;
  2791              e = e.sibling)
  2792             if (e.sym.kind == MTH)
  2793                 members.add((MethodSymbol) e.sym);
  2795         // count them off as they're annotated
  2796         for (JCTree arg : a.args) {
  2797             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2798             JCAssign assign = (JCAssign) arg;
  2799             Symbol m = TreeInfo.symbol(assign.lhs);
  2800             if (m == null || m.type.isErroneous()) continue;
  2801             if (!members.remove(m))
  2802                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2803                           m.name, a.type);
  2806         // all the remaining ones better have default values
  2807         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2808         for (MethodSymbol m : members) {
  2809             if (m.defaultValue == null && !m.type.isErroneous()) {
  2810                 missingDefaults.append(m.name);
  2813         if (missingDefaults.nonEmpty()) {
  2814             String key = (missingDefaults.size() > 1)
  2815                     ? "annotation.missing.default.value.1"
  2816                     : "annotation.missing.default.value";
  2817             log.error(a.pos(), key, a.type, missingDefaults);
  2820         // special case: java.lang.annotation.Target must not have
  2821         // repeated values in its value member
  2822         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2823             a.args.tail == null)
  2824             return;
  2826         if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
  2827         JCAssign assign = (JCAssign) a.args.head;
  2828         Symbol m = TreeInfo.symbol(assign.lhs);
  2829         if (m.name != names.value) return;
  2830         JCTree rhs = assign.rhs;
  2831         if (!rhs.hasTag(NEWARRAY)) return;
  2832         JCNewArray na = (JCNewArray) rhs;
  2833         Set<Symbol> targets = new HashSet<Symbol>();
  2834         for (JCTree elem : na.elems) {
  2835             if (!targets.add(TreeInfo.symbol(elem))) {
  2836                 log.error(elem.pos(), "repeated.annotation.target");
  2841     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2842         if (allowAnnotations &&
  2843             lint.isEnabled(LintCategory.DEP_ANN) &&
  2844             (s.flags() & DEPRECATED) != 0 &&
  2845             !syms.deprecatedType.isErroneous() &&
  2846             s.attribute(syms.deprecatedType.tsym) == null) {
  2847             log.warning(LintCategory.DEP_ANN,
  2848                     pos, "missing.deprecated.annotation");
  2852     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2853         if ((s.flags() & DEPRECATED) != 0 &&
  2854                 (other.flags() & DEPRECATED) == 0 &&
  2855                 s.outermostClass() != other.outermostClass()) {
  2856             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2857                 @Override
  2858                 public void report() {
  2859                     warnDeprecated(pos, s);
  2861             });
  2865     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2866         if ((s.flags() & PROPRIETARY) != 0) {
  2867             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2868                 public void report() {
  2869                     if (enableSunApiLintControl)
  2870                       warnSunApi(pos, "sun.proprietary", s);
  2871                     else
  2872                       log.mandatoryWarning(pos, "sun.proprietary", s);
  2874             });
  2878 /* *************************************************************************
  2879  * Check for recursive annotation elements.
  2880  **************************************************************************/
  2882     /** Check for cycles in the graph of annotation elements.
  2883      */
  2884     void checkNonCyclicElements(JCClassDecl tree) {
  2885         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2886         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2887         try {
  2888             tree.sym.flags_field |= LOCKED;
  2889             for (JCTree def : tree.defs) {
  2890                 if (!def.hasTag(METHODDEF)) continue;
  2891                 JCMethodDecl meth = (JCMethodDecl)def;
  2892                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2894         } finally {
  2895             tree.sym.flags_field &= ~LOCKED;
  2896             tree.sym.flags_field |= ACYCLIC_ANN;
  2900     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2901         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2902             return;
  2903         if ((tsym.flags_field & LOCKED) != 0) {
  2904             log.error(pos, "cyclic.annotation.element");
  2905             return;
  2907         try {
  2908             tsym.flags_field |= LOCKED;
  2909             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2910                 Symbol s = e.sym;
  2911                 if (s.kind != Kinds.MTH)
  2912                     continue;
  2913                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2915         } finally {
  2916             tsym.flags_field &= ~LOCKED;
  2917             tsym.flags_field |= ACYCLIC_ANN;
  2921     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2922         switch (type.tag) {
  2923         case TypeTags.CLASS:
  2924             if ((type.tsym.flags() & ANNOTATION) != 0)
  2925                 checkNonCyclicElementsInternal(pos, type.tsym);
  2926             break;
  2927         case TypeTags.ARRAY:
  2928             checkAnnotationResType(pos, types.elemtype(type));
  2929             break;
  2930         default:
  2931             break; // int etc
  2935 /* *************************************************************************
  2936  * Check for cycles in the constructor call graph.
  2937  **************************************************************************/
  2939     /** Check for cycles in the graph of constructors calling other
  2940      *  constructors.
  2941      */
  2942     void checkCyclicConstructors(JCClassDecl tree) {
  2943         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2945         // enter each constructor this-call into the map
  2946         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2947             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2948             if (app == null) continue;
  2949             JCMethodDecl meth = (JCMethodDecl) l.head;
  2950             if (TreeInfo.name(app.meth) == names._this) {
  2951                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2952             } else {
  2953                 meth.sym.flags_field |= ACYCLIC;
  2957         // Check for cycles in the map
  2958         Symbol[] ctors = new Symbol[0];
  2959         ctors = callMap.keySet().toArray(ctors);
  2960         for (Symbol caller : ctors) {
  2961             checkCyclicConstructor(tree, caller, callMap);
  2965     /** Look in the map to see if the given constructor is part of a
  2966      *  call cycle.
  2967      */
  2968     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2969                                         Map<Symbol,Symbol> callMap) {
  2970         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2971             if ((ctor.flags_field & LOCKED) != 0) {
  2972                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2973                           "recursive.ctor.invocation");
  2974             } else {
  2975                 ctor.flags_field |= LOCKED;
  2976                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2977                 ctor.flags_field &= ~LOCKED;
  2979             ctor.flags_field |= ACYCLIC;
  2983 /* *************************************************************************
  2984  * Miscellaneous
  2985  **************************************************************************/
  2987     /**
  2988      * Return the opcode of the operator but emit an error if it is an
  2989      * error.
  2990      * @param pos        position for error reporting.
  2991      * @param operator   an operator
  2992      * @param tag        a tree tag
  2993      * @param left       type of left hand side
  2994      * @param right      type of right hand side
  2995      */
  2996     int checkOperator(DiagnosticPosition pos,
  2997                        OperatorSymbol operator,
  2998                        JCTree.Tag tag,
  2999                        Type left,
  3000                        Type right) {
  3001         if (operator.opcode == ByteCodes.error) {
  3002             log.error(pos,
  3003                       "operator.cant.be.applied.1",
  3004                       treeinfo.operatorName(tag),
  3005                       left, right);
  3007         return operator.opcode;
  3011     /**
  3012      *  Check for division by integer constant zero
  3013      *  @param pos           Position for error reporting.
  3014      *  @param operator      The operator for the expression
  3015      *  @param operand       The right hand operand for the expression
  3016      */
  3017     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  3018         if (operand.constValue() != null
  3019             && lint.isEnabled(LintCategory.DIVZERO)
  3020             && operand.tag <= LONG
  3021             && ((Number) (operand.constValue())).longValue() == 0) {
  3022             int opc = ((OperatorSymbol)operator).opcode;
  3023             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  3024                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  3025                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  3030     /**
  3031      * Check for empty statements after if
  3032      */
  3033     void checkEmptyIf(JCIf tree) {
  3034         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  3035                 lint.isEnabled(LintCategory.EMPTY))
  3036             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  3039     /** Check that symbol is unique in given scope.
  3040      *  @param pos           Position for error reporting.
  3041      *  @param sym           The symbol.
  3042      *  @param s             The scope.
  3043      */
  3044     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  3045         if (sym.type.isErroneous())
  3046             return true;
  3047         if (sym.owner.name == names.any) return false;
  3048         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  3049             if (sym != e.sym &&
  3050                     (e.sym.flags() & CLASH) == 0 &&
  3051                     sym.kind == e.sym.kind &&
  3052                     sym.name != names.error &&
  3053                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  3054                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  3055                     varargsDuplicateError(pos, sym, e.sym);
  3056                     return true;
  3057                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  3058                     duplicateErasureError(pos, sym, e.sym);
  3059                     sym.flags_field |= CLASH;
  3060                     return true;
  3061                 } else {
  3062                     duplicateError(pos, e.sym);
  3063                     return false;
  3067         return true;
  3070     /** Report duplicate declaration error.
  3071      */
  3072     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  3073         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  3074             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  3078     /** Check that single-type import is not already imported or top-level defined,
  3079      *  but make an exception for two single-type imports which denote the same type.
  3080      *  @param pos           Position for error reporting.
  3081      *  @param sym           The symbol.
  3082      *  @param s             The scope
  3083      */
  3084     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3085         return checkUniqueImport(pos, sym, s, false);
  3088     /** Check that static single-type import is not already imported or top-level defined,
  3089      *  but make an exception for two single-type imports which denote the same type.
  3090      *  @param pos           Position for error reporting.
  3091      *  @param sym           The symbol.
  3092      *  @param s             The scope
  3093      *  @param staticImport  Whether or not this was a static import
  3094      */
  3095     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  3096         return checkUniqueImport(pos, sym, s, true);
  3099     /** Check that single-type import is not already imported or top-level defined,
  3100      *  but make an exception for two single-type imports which denote the same type.
  3101      *  @param pos           Position for error reporting.
  3102      *  @param sym           The symbol.
  3103      *  @param s             The scope.
  3104      *  @param staticImport  Whether or not this was a static import
  3105      */
  3106     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  3107         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  3108             // is encountered class entered via a class declaration?
  3109             boolean isClassDecl = e.scope == s;
  3110             if ((isClassDecl || sym != e.sym) &&
  3111                 sym.kind == e.sym.kind &&
  3112                 sym.name != names.error) {
  3113                 if (!e.sym.type.isErroneous()) {
  3114                     String what = e.sym.toString();
  3115                     if (!isClassDecl) {
  3116                         if (staticImport)
  3117                             log.error(pos, "already.defined.static.single.import", what);
  3118                         else
  3119                             log.error(pos, "already.defined.single.import", what);
  3121                     else if (sym != e.sym)
  3122                         log.error(pos, "already.defined.this.unit", what);
  3124                 return false;
  3127         return true;
  3130     /** Check that a qualified name is in canonical form (for import decls).
  3131      */
  3132     public void checkCanonical(JCTree tree) {
  3133         if (!isCanonical(tree))
  3134             log.error(tree.pos(), "import.requires.canonical",
  3135                       TreeInfo.symbol(tree));
  3137         // where
  3138         private boolean isCanonical(JCTree tree) {
  3139             while (tree.hasTag(SELECT)) {
  3140                 JCFieldAccess s = (JCFieldAccess) tree;
  3141                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  3142                     return false;
  3143                 tree = s.selected;
  3145             return true;
  3148     private class ConversionWarner extends Warner {
  3149         final String uncheckedKey;
  3150         final Type found;
  3151         final Type expected;
  3152         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  3153             super(pos);
  3154             this.uncheckedKey = uncheckedKey;
  3155             this.found = found;
  3156             this.expected = expected;
  3159         @Override
  3160         public void warn(LintCategory lint) {
  3161             boolean warned = this.warned;
  3162             super.warn(lint);
  3163             if (warned) return; // suppress redundant diagnostics
  3164             switch (lint) {
  3165                 case UNCHECKED:
  3166                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  3167                     break;
  3168                 case VARARGS:
  3169                     if (method != null &&
  3170                             method.attribute(syms.trustMeType.tsym) != null &&
  3171                             isTrustMeAllowedOnMethod(method) &&
  3172                             !types.isReifiable(method.type.getParameterTypes().last())) {
  3173                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  3175                     break;
  3176                 default:
  3177                     throw new AssertionError("Unexpected lint: " + lint);
  3182     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  3183         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  3186     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  3187         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial