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

Tue, 28 Dec 2010 15:54:52 -0800

author
ohair
date
Tue, 28 Dec 2010 15:54:52 -0800
changeset 798
4868a36f6fd8
parent 795
7b99f98b3035
child 815
d17f37522154
permissions
-rw-r--r--

6962318: Update copyright year
Reviewed-by: xdono

     1 /*
     2  * Copyright (c) 1999, 2010, 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.*;
    44 import static com.sun.tools.javac.code.Flags.*;
    45 import static com.sun.tools.javac.code.Kinds.*;
    46 import static com.sun.tools.javac.code.TypeTags.*;
    48 import static com.sun.tools.javac.main.OptionName.*;
    50 /** Type checking helper class for the attribution phase.
    51  *
    52  *  <p><b>This is NOT part of any supported API.
    53  *  If you write code that depends on this, you do so at your own risk.
    54  *  This code and its internal interfaces are subject to change or
    55  *  deletion without notice.</b>
    56  */
    57 public class Check {
    58     protected static final Context.Key<Check> checkKey =
    59         new Context.Key<Check>();
    61     private final Names names;
    62     private final Log log;
    63     private final Symtab syms;
    64     private final Enter enter;
    65     private final Infer infer;
    66     private final Types types;
    67     private final JCDiagnostic.Factory diags;
    68     private final boolean skipAnnotations;
    69     private boolean warnOnSyntheticConflicts;
    70     private boolean suppressAbortOnBadClassFile;
    71     private final TreeInfo treeinfo;
    73     // The set of lint options currently in effect. It is initialized
    74     // from the context, and then is set/reset as needed by Attr as it
    75     // visits all the various parts of the trees during attribution.
    76     private Lint lint;
    78     // The method being analyzed in Attr - it is set/reset as needed by
    79     // Attr as it visits new method declarations.
    80     private MethodSymbol method;
    82     public static Check instance(Context context) {
    83         Check instance = context.get(checkKey);
    84         if (instance == null)
    85             instance = new Check(context);
    86         return instance;
    87     }
    89     protected Check(Context context) {
    90         context.put(checkKey, this);
    92         names = Names.instance(context);
    93         log = Log.instance(context);
    94         syms = Symtab.instance(context);
    95         enter = Enter.instance(context);
    96         infer = Infer.instance(context);
    97         this.types = Types.instance(context);
    98         diags = JCDiagnostic.Factory.instance(context);
    99         Options options = Options.instance(context);
   100         lint = Lint.instance(context);
   101         treeinfo = TreeInfo.instance(context);
   103         Source source = Source.instance(context);
   104         allowGenerics = source.allowGenerics();
   105         allowAnnotations = source.allowAnnotations();
   106         allowCovariantReturns = source.allowCovariantReturns();
   107         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   108         complexInference = options.isSet(COMPLEXINFERENCE);
   109         skipAnnotations = options.isSet("skipAnnotations");
   110         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   111         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   113         Target target = Target.instance(context);
   114         syntheticNameChar = target.syntheticNameChar();
   116         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   117         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   118         boolean verboseVarargs = lint.isEnabled(LintCategory.VARARGS);
   119         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   120         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   122         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   123                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   124         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   125                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   126         unsafeVarargsHandler = new MandatoryWarningHandler(log, verboseVarargs,
   127                 enforceMandatoryWarnings, "varargs", LintCategory.VARARGS);
   128         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   129                 enforceMandatoryWarnings, "sunapi", null);
   130     }
   132     /** Switch: generics enabled?
   133      */
   134     boolean allowGenerics;
   136     /** Switch: annotations enabled?
   137      */
   138     boolean allowAnnotations;
   140     /** Switch: covariant returns enabled?
   141      */
   142     boolean allowCovariantReturns;
   144     /** Switch: simplified varargs enabled?
   145      */
   146     boolean allowSimplifiedVarargs;
   148     /** Switch: -complexinference option set?
   149      */
   150     boolean complexInference;
   152     /** Character for synthetic names
   153      */
   154     char syntheticNameChar;
   156     /** A table mapping flat names of all compiled classes in this run to their
   157      *  symbols; maintained from outside.
   158      */
   159     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   161     /** A handler for messages about deprecated usage.
   162      */
   163     private MandatoryWarningHandler deprecationHandler;
   165     /** A handler for messages about unchecked or unsafe usage.
   166      */
   167     private MandatoryWarningHandler uncheckedHandler;
   169     /** A handler for messages about unchecked or unsafe vararg method decl.
   170      */
   171     private MandatoryWarningHandler unsafeVarargsHandler;
   173     /** A handler for messages about using proprietary API.
   174      */
   175     private MandatoryWarningHandler sunApiHandler;
   177 /* *************************************************************************
   178  * Errors and Warnings
   179  **************************************************************************/
   181     Lint setLint(Lint newLint) {
   182         Lint prev = lint;
   183         lint = newLint;
   184         return prev;
   185     }
   187     MethodSymbol setMethod(MethodSymbol newMethod) {
   188         MethodSymbol prev = method;
   189         method = newMethod;
   190         return prev;
   191     }
   193     /** Warn about deprecated symbol.
   194      *  @param pos        Position to be used for error reporting.
   195      *  @param sym        The deprecated symbol.
   196      */
   197     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   198         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   199             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   200     }
   202     /** Warn about unchecked operation.
   203      *  @param pos        Position to be used for error reporting.
   204      *  @param msg        A string describing the problem.
   205      */
   206     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   207         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   208             uncheckedHandler.report(pos, msg, args);
   209     }
   211     /** Warn about unsafe vararg method decl.
   212      *  @param pos        Position to be used for error reporting.
   213      *  @param sym        The deprecated symbol.
   214      */
   215     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   216         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   217             log.warning(LintCategory.VARARGS, pos, key, args);
   218     }
   220     /** Warn about using proprietary API.
   221      *  @param pos        Position to be used for error reporting.
   222      *  @param msg        A string describing the problem.
   223      */
   224     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   225         if (!lint.isSuppressed(LintCategory.SUNAPI))
   226             sunApiHandler.report(pos, msg, args);
   227     }
   229     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   230         if (lint.isEnabled(LintCategory.STATIC))
   231             log.warning(LintCategory.STATIC, pos, msg, args);
   232     }
   234     /**
   235      * Report any deferred diagnostics.
   236      */
   237     public void reportDeferredDiagnostics() {
   238         deprecationHandler.reportDeferredDiagnostic();
   239         uncheckedHandler.reportDeferredDiagnostic();
   240         sunApiHandler.reportDeferredDiagnostic();
   241     }
   244     /** Report a failure to complete a class.
   245      *  @param pos        Position to be used for error reporting.
   246      *  @param ex         The failure to report.
   247      */
   248     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   249         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   250         if (ex instanceof ClassReader.BadClassFile
   251                 && !suppressAbortOnBadClassFile) throw new Abort();
   252         else return syms.errType;
   253     }
   255     /** Report a type error.
   256      *  @param pos        Position to be used for error reporting.
   257      *  @param problem    A string describing the error.
   258      *  @param found      The type that was found.
   259      *  @param req        The type that was required.
   260      */
   261     Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
   262         log.error(pos, "prob.found.req",
   263                   problem, found, req);
   264         return types.createErrorType(found);
   265     }
   267     Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
   268         log.error(pos, "prob.found.req.1", problem, found, req, explanation);
   269         return types.createErrorType(found);
   270     }
   272     /** Report an error that wrong type tag was found.
   273      *  @param pos        Position to be used for error reporting.
   274      *  @param required   An internationalized string describing the type tag
   275      *                    required.
   276      *  @param found      The type that was found.
   277      */
   278     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   279         // this error used to be raised by the parser,
   280         // but has been delayed to this point:
   281         if (found instanceof Type && ((Type)found).tag == VOID) {
   282             log.error(pos, "illegal.start.of.type");
   283             return syms.errType;
   284         }
   285         log.error(pos, "type.found.req", found, required);
   286         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   287     }
   289     /** Report an error that symbol cannot be referenced before super
   290      *  has been called.
   291      *  @param pos        Position to be used for error reporting.
   292      *  @param sym        The referenced symbol.
   293      */
   294     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   295         log.error(pos, "cant.ref.before.ctor.called", sym);
   296     }
   298     /** Report duplicate declaration error.
   299      */
   300     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   301         if (!sym.type.isErroneous()) {
   302             log.error(pos, "already.defined", sym, sym.location());
   303         }
   304     }
   306     /** Report array/varargs duplicate declaration
   307      */
   308     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   309         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   310             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   311         }
   312     }
   314 /* ************************************************************************
   315  * duplicate declaration checking
   316  *************************************************************************/
   318     /** Check that variable does not hide variable with same name in
   319      *  immediately enclosing local scope.
   320      *  @param pos           Position for error reporting.
   321      *  @param v             The symbol.
   322      *  @param s             The scope.
   323      */
   324     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   325         if (s.next != null) {
   326             for (Scope.Entry e = s.next.lookup(v.name);
   327                  e.scope != null && e.sym.owner == v.owner;
   328                  e = e.next()) {
   329                 if (e.sym.kind == VAR &&
   330                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   331                     v.name != names.error) {
   332                     duplicateError(pos, e.sym);
   333                     return;
   334                 }
   335             }
   336         }
   337     }
   339     /** Check that a class or interface does not hide a class or
   340      *  interface with same name in immediately enclosing local scope.
   341      *  @param pos           Position for error reporting.
   342      *  @param c             The symbol.
   343      *  @param s             The scope.
   344      */
   345     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   346         if (s.next != null) {
   347             for (Scope.Entry e = s.next.lookup(c.name);
   348                  e.scope != null && e.sym.owner == c.owner;
   349                  e = e.next()) {
   350                 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
   351                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   352                     c.name != names.error) {
   353                     duplicateError(pos, e.sym);
   354                     return;
   355                 }
   356             }
   357         }
   358     }
   360     /** Check that class does not have the same name as one of
   361      *  its enclosing classes, or as a class defined in its enclosing scope.
   362      *  return true if class is unique in its enclosing scope.
   363      *  @param pos           Position for error reporting.
   364      *  @param name          The class name.
   365      *  @param s             The enclosing scope.
   366      */
   367     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   368         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   369             if (e.sym.kind == TYP && e.sym.name != names.error) {
   370                 duplicateError(pos, e.sym);
   371                 return false;
   372             }
   373         }
   374         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   375             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   376                 duplicateError(pos, sym);
   377                 return true;
   378             }
   379         }
   380         return true;
   381     }
   383 /* *************************************************************************
   384  * Class name generation
   385  **************************************************************************/
   387     /** Return name of local class.
   388      *  This is of the form    <enclClass> $ n <classname>
   389      *  where
   390      *    enclClass is the flat name of the enclosing class,
   391      *    classname is the simple name of the local class
   392      */
   393     Name localClassName(ClassSymbol c) {
   394         for (int i=1; ; i++) {
   395             Name flatname = names.
   396                 fromString("" + c.owner.enclClass().flatname +
   397                            syntheticNameChar + i +
   398                            c.name);
   399             if (compiled.get(flatname) == null) return flatname;
   400         }
   401     }
   403 /* *************************************************************************
   404  * Type Checking
   405  **************************************************************************/
   407     /** Check that a given type is assignable to a given proto-type.
   408      *  If it is, return the type, otherwise return errType.
   409      *  @param pos        Position to be used for error reporting.
   410      *  @param found      The type that was found.
   411      *  @param req        The type that was required.
   412      */
   413     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   414         return checkType(pos, found, req, "incompatible.types");
   415     }
   417     Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
   418         if (req.tag == ERROR)
   419             return req;
   420         if (found.tag == FORALL)
   421             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   422         if (req.tag == NONE)
   423             return found;
   424         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   425             return found;
   426         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   427             return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
   428         if (found.isSuperBound()) {
   429             log.error(pos, "assignment.from.super-bound", found);
   430             return types.createErrorType(found);
   431         }
   432         if (req.isExtendsBound()) {
   433             log.error(pos, "assignment.to.extends-bound", req);
   434             return types.createErrorType(found);
   435         }
   436         return typeError(pos, diags.fragment(errKey), found, req);
   437     }
   439     /** Instantiate polymorphic type to some prototype, unless
   440      *  prototype is `anyPoly' in which case polymorphic type
   441      *  is returned unchanged.
   442      */
   443     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
   444         if (pt == Infer.anyPoly && complexInference) {
   445             return t;
   446         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   447             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   448             return instantiatePoly(pos, t, newpt, warn);
   449         } else if (pt.tag == ERROR) {
   450             return pt;
   451         } else {
   452             try {
   453                 return infer.instantiateExpr(t, pt, warn);
   454             } catch (Infer.NoInstanceException ex) {
   455                 if (ex.isAmbiguous) {
   456                     JCDiagnostic d = ex.getDiagnostic();
   457                     log.error(pos,
   458                               "undetermined.type" + (d!=null ? ".1" : ""),
   459                               t, d);
   460                     return types.createErrorType(pt);
   461                 } else {
   462                     JCDiagnostic d = ex.getDiagnostic();
   463                     return typeError(pos,
   464                                      diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   465                                      t, pt);
   466                 }
   467             } catch (Infer.InvalidInstanceException ex) {
   468                 JCDiagnostic d = ex.getDiagnostic();
   469                 log.error(pos, "invalid.inferred.types", t.tvars, d);
   470                 return types.createErrorType(pt);
   471             }
   472         }
   473     }
   475     /** Check that a given type can be cast to a given target type.
   476      *  Return the result of the cast.
   477      *  @param pos        Position to be used for error reporting.
   478      *  @param found      The type that is being cast.
   479      *  @param req        The target type of the cast.
   480      */
   481     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   482         if (found.tag == FORALL) {
   483             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   484             return req;
   485         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   486             return req;
   487         } else {
   488             return typeError(pos,
   489                              diags.fragment("inconvertible.types"),
   490                              found, req);
   491         }
   492     }
   493 //where
   494         /** Is type a type variable, or a (possibly multi-dimensional) array of
   495          *  type variables?
   496          */
   497         boolean isTypeVar(Type t) {
   498             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   499         }
   501     /** Check that a type is within some bounds.
   502      *
   503      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   504      *  type argument.
   505      *  @param pos           Position to be used for error reporting.
   506      *  @param a             The type that should be bounded by bs.
   507      *  @param bs            The bound.
   508      */
   509     private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
   510          if (a.isUnbound()) {
   511              return;
   512          } else if (a.tag != WILDCARD) {
   513              a = types.upperBound(a);
   514              for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
   515                  if (!types.isSubtype(a, l.head)) {
   516                      log.error(pos, "not.within.bounds", a);
   517                      return;
   518                  }
   519              }
   520          } else if (a.isExtendsBound()) {
   521              if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
   522                  log.error(pos, "not.within.bounds", a);
   523          } else if (a.isSuperBound()) {
   524              if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
   525                  log.error(pos, "not.within.bounds", a);
   526          }
   527      }
   529     /** Check that a type is within some bounds.
   530      *
   531      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   532      *  type argument.
   533      *  @param pos           Position to be used for error reporting.
   534      *  @param a             The type that should be bounded by bs.
   535      *  @param bs            The bound.
   536      */
   537     private void checkCapture(JCTypeApply tree) {
   538         List<JCExpression> args = tree.getTypeArguments();
   539         for (Type arg : types.capture(tree.type).getTypeArguments()) {
   540             if (arg.tag == TYPEVAR && arg.getUpperBound().isErroneous()) {
   541                 log.error(args.head.pos, "not.within.bounds", args.head.type);
   542                 break;
   543             }
   544             args = args.tail;
   545         }
   546      }
   548     /** Check that type is different from 'void'.
   549      *  @param pos           Position to be used for error reporting.
   550      *  @param t             The type to be checked.
   551      */
   552     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   553         if (t.tag == VOID) {
   554             log.error(pos, "void.not.allowed.here");
   555             return types.createErrorType(t);
   556         } else {
   557             return t;
   558         }
   559     }
   561     /** Check that type is a class or interface type.
   562      *  @param pos           Position to be used for error reporting.
   563      *  @param t             The type to be checked.
   564      */
   565     Type checkClassType(DiagnosticPosition pos, Type t) {
   566         if (t.tag != CLASS && t.tag != ERROR)
   567             return typeTagError(pos,
   568                                 diags.fragment("type.req.class"),
   569                                 (t.tag == TYPEVAR)
   570                                 ? diags.fragment("type.parameter", t)
   571                                 : t);
   572         else
   573             return t;
   574     }
   576     /** Check that type is a class or interface type.
   577      *  @param pos           Position to be used for error reporting.
   578      *  @param t             The type to be checked.
   579      *  @param noBounds    True if type bounds are illegal here.
   580      */
   581     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   582         t = checkClassType(pos, t);
   583         if (noBounds && t.isParameterized()) {
   584             List<Type> args = t.getTypeArguments();
   585             while (args.nonEmpty()) {
   586                 if (args.head.tag == WILDCARD)
   587                     return typeTagError(pos,
   588                                         diags.fragment("type.req.exact"),
   589                                         args.head);
   590                 args = args.tail;
   591             }
   592         }
   593         return t;
   594     }
   596     /** Check that type is a reifiable class, interface or array type.
   597      *  @param pos           Position to be used for error reporting.
   598      *  @param t             The type to be checked.
   599      */
   600     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   601         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   602             return typeTagError(pos,
   603                                 diags.fragment("type.req.class.array"),
   604                                 t);
   605         } else if (!types.isReifiable(t)) {
   606             log.error(pos, "illegal.generic.type.for.instof");
   607             return types.createErrorType(t);
   608         } else {
   609             return t;
   610         }
   611     }
   613     /** Check that type is a reference type, i.e. a class, interface or array type
   614      *  or a type variable.
   615      *  @param pos           Position to be used for error reporting.
   616      *  @param t             The type to be checked.
   617      */
   618     Type checkRefType(DiagnosticPosition pos, Type t) {
   619         switch (t.tag) {
   620         case CLASS:
   621         case ARRAY:
   622         case TYPEVAR:
   623         case WILDCARD:
   624         case ERROR:
   625             return t;
   626         default:
   627             return typeTagError(pos,
   628                                 diags.fragment("type.req.ref"),
   629                                 t);
   630         }
   631     }
   633     /** Check that each type is a reference type, i.e. a class, interface or array type
   634      *  or a type variable.
   635      *  @param trees         Original trees, used for error reporting.
   636      *  @param types         The types to be checked.
   637      */
   638     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   639         List<JCExpression> tl = trees;
   640         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   641             l.head = checkRefType(tl.head.pos(), l.head);
   642             tl = tl.tail;
   643         }
   644         return types;
   645     }
   647     /** Check that type is a null or reference type.
   648      *  @param pos           Position to be used for error reporting.
   649      *  @param t             The type to be checked.
   650      */
   651     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   652         switch (t.tag) {
   653         case CLASS:
   654         case ARRAY:
   655         case TYPEVAR:
   656         case WILDCARD:
   657         case BOT:
   658         case ERROR:
   659             return t;
   660         default:
   661             return typeTagError(pos,
   662                                 diags.fragment("type.req.ref"),
   663                                 t);
   664         }
   665     }
   667     /** Check that flag set does not contain elements of two conflicting sets. s
   668      *  Return true if it doesn't.
   669      *  @param pos           Position to be used for error reporting.
   670      *  @param flags         The set of flags to be checked.
   671      *  @param set1          Conflicting flags set #1.
   672      *  @param set2          Conflicting flags set #2.
   673      */
   674     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   675         if ((flags & set1) != 0 && (flags & set2) != 0) {
   676             log.error(pos,
   677                       "illegal.combination.of.modifiers",
   678                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   679                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   680             return false;
   681         } else
   682             return true;
   683     }
   685     /** Check that the type inferred using the diamond operator does not contain
   686      *  non-denotable types such as captured types or intersection types.
   687      *  @param t the type inferred using the diamond operator
   688      */
   689     List<Type> checkDiamond(ClassType t) {
   690         DiamondTypeChecker dtc = new DiamondTypeChecker();
   691         ListBuffer<Type> buf = ListBuffer.lb();
   692         for (Type arg : t.getTypeArguments()) {
   693             if (!dtc.visit(arg, null)) {
   694                 buf.append(arg);
   695             }
   696         }
   697         return buf.toList();
   698     }
   700     static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
   701         public Boolean visitType(Type t, Void s) {
   702             return true;
   703         }
   704         @Override
   705         public Boolean visitClassType(ClassType t, Void s) {
   706             if (t.isCompound()) {
   707                 return false;
   708             }
   709             for (Type targ : t.getTypeArguments()) {
   710                 if (!visit(targ, s)) {
   711                     return false;
   712                 }
   713             }
   714             return true;
   715         }
   716         @Override
   717         public Boolean visitCapturedType(CapturedType t, Void s) {
   718             return false;
   719         }
   720     }
   722     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   723         MethodSymbol m = tree.sym;
   724         if (!allowSimplifiedVarargs) return;
   725         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   726         Type varargElemType = null;
   727         if (m.isVarArgs()) {
   728             varargElemType = types.elemtype(tree.params.last().type);
   729         }
   730         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   731             if (varargElemType != null) {
   732                 log.error(tree,
   733                         "varargs.invalid.trustme.anno",
   734                         syms.trustMeType.tsym,
   735                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   736             } else {
   737                 log.error(tree,
   738                             "varargs.invalid.trustme.anno",
   739                             syms.trustMeType.tsym,
   740                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   741             }
   742         } else if (hasTrustMeAnno && varargElemType != null &&
   743                             types.isReifiable(varargElemType)) {
   744             warnUnsafeVararg(tree,
   745                             "varargs.redundant.trustme.anno",
   746                             syms.trustMeType.tsym,
   747                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   748         }
   749         else if (!hasTrustMeAnno && varargElemType != null &&
   750                 !types.isReifiable(varargElemType)) {
   751             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   752         }
   753     }
   754     //where
   755         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   756             return (s.flags() & VARARGS) != 0 &&
   757                 (s.isConstructor() ||
   758                     (s.flags() & (STATIC | FINAL)) != 0);
   759         }
   761     /**
   762      * Check that vararg method call is sound
   763      * @param pos Position to be used for error reporting.
   764      * @param argtypes Actual arguments supplied to vararg method.
   765      */
   766     void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
   767         Type argtype = argtypes.last();
   768         if (!types.isReifiable(argtype) &&
   769                 (!allowSimplifiedVarargs ||
   770                 msym.attribute(syms.trustMeType.tsym) == null ||
   771                 !isTrustMeAllowedOnMethod(msym))) {
   772             warnUnchecked(pos,
   773                               "unchecked.generic.array.creation",
   774                               argtype);
   775         }
   776     }
   778     /** Check that given modifiers are legal for given symbol and
   779      *  return modifiers together with any implicit modififiers for that symbol.
   780      *  Warning: we can't use flags() here since this method
   781      *  is called during class enter, when flags() would cause a premature
   782      *  completion.
   783      *  @param pos           Position to be used for error reporting.
   784      *  @param flags         The set of modifiers given in a definition.
   785      *  @param sym           The defined symbol.
   786      */
   787     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   788         long mask;
   789         long implicit = 0;
   790         switch (sym.kind) {
   791         case VAR:
   792             if (sym.owner.kind != TYP)
   793                 mask = LocalVarFlags;
   794             else if ((sym.owner.flags_field & INTERFACE) != 0)
   795                 mask = implicit = InterfaceVarFlags;
   796             else
   797                 mask = VarFlags;
   798             break;
   799         case MTH:
   800             if (sym.name == names.init) {
   801                 if ((sym.owner.flags_field & ENUM) != 0) {
   802                     // enum constructors cannot be declared public or
   803                     // protected and must be implicitly or explicitly
   804                     // private
   805                     implicit = PRIVATE;
   806                     mask = PRIVATE;
   807                 } else
   808                     mask = ConstructorFlags;
   809             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   810                 mask = implicit = InterfaceMethodFlags;
   811             else {
   812                 mask = MethodFlags;
   813             }
   814             // Imply STRICTFP if owner has STRICTFP set.
   815             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   816               implicit |= sym.owner.flags_field & STRICTFP;
   817             break;
   818         case TYP:
   819             if (sym.isLocal()) {
   820                 mask = LocalClassFlags;
   821                 if (sym.name.isEmpty()) { // Anonymous class
   822                     // Anonymous classes in static methods are themselves static;
   823                     // that's why we admit STATIC here.
   824                     mask |= STATIC;
   825                     // JLS: Anonymous classes are final.
   826                     implicit |= FINAL;
   827                 }
   828                 if ((sym.owner.flags_field & STATIC) == 0 &&
   829                     (flags & ENUM) != 0)
   830                     log.error(pos, "enums.must.be.static");
   831             } else if (sym.owner.kind == TYP) {
   832                 mask = MemberClassFlags;
   833                 if (sym.owner.owner.kind == PCK ||
   834                     (sym.owner.flags_field & STATIC) != 0)
   835                     mask |= STATIC;
   836                 else if ((flags & ENUM) != 0)
   837                     log.error(pos, "enums.must.be.static");
   838                 // Nested interfaces and enums are always STATIC (Spec ???)
   839                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   840             } else {
   841                 mask = ClassFlags;
   842             }
   843             // Interfaces are always ABSTRACT
   844             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   846             if ((flags & ENUM) != 0) {
   847                 // enums can't be declared abstract or final
   848                 mask &= ~(ABSTRACT | FINAL);
   849                 implicit |= implicitEnumFinalFlag(tree);
   850             }
   851             // Imply STRICTFP if owner has STRICTFP set.
   852             implicit |= sym.owner.flags_field & STRICTFP;
   853             break;
   854         default:
   855             throw new AssertionError();
   856         }
   857         long illegal = flags & StandardFlags & ~mask;
   858         if (illegal != 0) {
   859             if ((illegal & INTERFACE) != 0) {
   860                 log.error(pos, "intf.not.allowed.here");
   861                 mask |= INTERFACE;
   862             }
   863             else {
   864                 log.error(pos,
   865                           "mod.not.allowed.here", asFlagSet(illegal));
   866             }
   867         }
   868         else if ((sym.kind == TYP ||
   869                   // ISSUE: Disallowing abstract&private is no longer appropriate
   870                   // in the presence of inner classes. Should it be deleted here?
   871                   checkDisjoint(pos, flags,
   872                                 ABSTRACT,
   873                                 PRIVATE | STATIC))
   874                  &&
   875                  checkDisjoint(pos, flags,
   876                                ABSTRACT | INTERFACE,
   877                                FINAL | NATIVE | SYNCHRONIZED)
   878                  &&
   879                  checkDisjoint(pos, flags,
   880                                PUBLIC,
   881                                PRIVATE | PROTECTED)
   882                  &&
   883                  checkDisjoint(pos, flags,
   884                                PRIVATE,
   885                                PUBLIC | PROTECTED)
   886                  &&
   887                  checkDisjoint(pos, flags,
   888                                FINAL,
   889                                VOLATILE)
   890                  &&
   891                  (sym.kind == TYP ||
   892                   checkDisjoint(pos, flags,
   893                                 ABSTRACT | NATIVE,
   894                                 STRICTFP))) {
   895             // skip
   896         }
   897         return flags & (mask | ~StandardFlags) | implicit;
   898     }
   901     /** Determine if this enum should be implicitly final.
   902      *
   903      *  If the enum has no specialized enum contants, it is final.
   904      *
   905      *  If the enum does have specialized enum contants, it is
   906      *  <i>not</i> final.
   907      */
   908     private long implicitEnumFinalFlag(JCTree tree) {
   909         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   910         class SpecialTreeVisitor extends JCTree.Visitor {
   911             boolean specialized;
   912             SpecialTreeVisitor() {
   913                 this.specialized = false;
   914             };
   916             @Override
   917             public void visitTree(JCTree tree) { /* no-op */ }
   919             @Override
   920             public void visitVarDef(JCVariableDecl tree) {
   921                 if ((tree.mods.flags & ENUM) != 0) {
   922                     if (tree.init instanceof JCNewClass &&
   923                         ((JCNewClass) tree.init).def != null) {
   924                         specialized = true;
   925                     }
   926                 }
   927             }
   928         }
   930         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   931         JCClassDecl cdef = (JCClassDecl) tree;
   932         for (JCTree defs: cdef.defs) {
   933             defs.accept(sts);
   934             if (sts.specialized) return 0;
   935         }
   936         return FINAL;
   937     }
   939 /* *************************************************************************
   940  * Type Validation
   941  **************************************************************************/
   943     /** Validate a type expression. That is,
   944      *  check that all type arguments of a parametric type are within
   945      *  their bounds. This must be done in a second phase after type attributon
   946      *  since a class might have a subclass as type parameter bound. E.g:
   947      *
   948      *  class B<A extends C> { ... }
   949      *  class C extends B<C> { ... }
   950      *
   951      *  and we can't make sure that the bound is already attributed because
   952      *  of possible cycles.
   953      *
   954      * Visitor method: Validate a type expression, if it is not null, catching
   955      *  and reporting any completion failures.
   956      */
   957     void validate(JCTree tree, Env<AttrContext> env) {
   958         validate(tree, env, true);
   959     }
   960     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
   961         new Validator(env).validateTree(tree, checkRaw, true);
   962     }
   964     /** Visitor method: Validate a list of type expressions.
   965      */
   966     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
   967         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   968             validate(l.head, env);
   969     }
   971     /** A visitor class for type validation.
   972      */
   973     class Validator extends JCTree.Visitor {
   975         boolean isOuter;
   976         Env<AttrContext> env;
   978         Validator(Env<AttrContext> env) {
   979             this.env = env;
   980         }
   982         @Override
   983         public void visitTypeArray(JCArrayTypeTree tree) {
   984             tree.elemtype.accept(this);
   985         }
   987         @Override
   988         public void visitTypeApply(JCTypeApply tree) {
   989             if (tree.type.tag == CLASS) {
   990                 List<Type> formals = tree.type.tsym.type.allparams();
   991                 List<Type> actuals = tree.type.allparams();
   992                 List<JCExpression> args = tree.arguments;
   993                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
   994                 ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
   996                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
   998                 // For matching pairs of actual argument types `a' and
   999                 // formal type parameters with declared bound `b' ...
  1000                 while (args.nonEmpty() && forms.nonEmpty()) {
  1001                     validateTree(args.head,
  1002                             !(isOuter && is_java_lang_Class),
  1003                             false);
  1005                     // exact type arguments needs to know their
  1006                     // bounds (for upper and lower bound
  1007                     // calculations).  So we create new TypeVars with
  1008                     // bounds substed with actuals.
  1009                     tvars_buf.append(types.substBound(((TypeVar)forms.head),
  1010                                                       formals,
  1011                                                       actuals));
  1013                     args = args.tail;
  1014                     forms = forms.tail;
  1017                 args = tree.arguments;
  1018                 List<Type> tvars_cap = types.substBounds(formals,
  1019                                           formals,
  1020                                           types.capture(tree.type).allparams());
  1021                 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
  1022                     // Let the actual arguments know their bound
  1023                     args.head.type.withTypeVar((TypeVar)tvars_cap.head);
  1024                     args = args.tail;
  1025                     tvars_cap = tvars_cap.tail;
  1028                 args = tree.arguments;
  1029                 List<Type> tvars = tvars_buf.toList();
  1031                 while (args.nonEmpty() && tvars.nonEmpty()) {
  1032                     Type actual = types.subst(args.head.type,
  1033                         tree.type.tsym.type.getTypeArguments(),
  1034                         tvars_buf.toList());
  1035                     checkExtends(args.head.pos(),
  1036                                  actual,
  1037                                  (TypeVar)tvars.head);
  1038                     args = args.tail;
  1039                     tvars = tvars.tail;
  1042                 checkCapture(tree);
  1044                 // Check that this type is either fully parameterized, or
  1045                 // not parameterized at all.
  1046                 if (tree.type.getEnclosingType().isRaw())
  1047                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1048                 if (tree.clazz.getTag() == JCTree.SELECT)
  1049                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1053         @Override
  1054         public void visitTypeParameter(JCTypeParameter tree) {
  1055             validateTrees(tree.bounds, true, isOuter);
  1056             checkClassBounds(tree.pos(), tree.type);
  1059         @Override
  1060         public void visitWildcard(JCWildcard tree) {
  1061             if (tree.inner != null)
  1062                 validateTree(tree.inner, true, isOuter);
  1065         @Override
  1066         public void visitSelect(JCFieldAccess tree) {
  1067             if (tree.type.tag == CLASS) {
  1068                 visitSelectInternal(tree);
  1070                 // Check that this type is either fully parameterized, or
  1071                 // not parameterized at all.
  1072                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1073                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1076         public void visitSelectInternal(JCFieldAccess tree) {
  1077             if (tree.type.tsym.isStatic() &&
  1078                 tree.selected.type.isParameterized()) {
  1079                 // The enclosing type is not a class, so we are
  1080                 // looking at a static member type.  However, the
  1081                 // qualifying expression is parameterized.
  1082                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1083             } else {
  1084                 // otherwise validate the rest of the expression
  1085                 tree.selected.accept(this);
  1089         @Override
  1090         public void visitAnnotatedType(JCAnnotatedType tree) {
  1091             tree.underlyingType.accept(this);
  1094         /** Default visitor method: do nothing.
  1095          */
  1096         @Override
  1097         public void visitTree(JCTree tree) {
  1100         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1101             try {
  1102                 if (tree != null) {
  1103                     this.isOuter = isOuter;
  1104                     tree.accept(this);
  1105                     if (checkRaw)
  1106                         checkRaw(tree, env);
  1108             } catch (CompletionFailure ex) {
  1109                 completionError(tree.pos(), ex);
  1113         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1114             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1115                 validateTree(l.head, checkRaw, isOuter);
  1118         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1119             if (lint.isEnabled(LintCategory.RAW) &&
  1120                 tree.type.tag == CLASS &&
  1121                 !TreeInfo.isDiamond(tree) &&
  1122                 !env.enclClass.name.isEmpty() &&  //anonymous or intersection
  1123                 tree.type.isRaw()) {
  1124                 log.warning(LintCategory.RAW,
  1125                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1130 /* *************************************************************************
  1131  * Exception checking
  1132  **************************************************************************/
  1134     /* The following methods treat classes as sets that contain
  1135      * the class itself and all their subclasses
  1136      */
  1138     /** Is given type a subtype of some of the types in given list?
  1139      */
  1140     boolean subset(Type t, List<Type> ts) {
  1141         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1142             if (types.isSubtype(t, l.head)) return true;
  1143         return false;
  1146     /** Is given type a subtype or supertype of
  1147      *  some of the types in given list?
  1148      */
  1149     boolean intersects(Type t, List<Type> ts) {
  1150         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1151             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1152         return false;
  1155     /** Add type set to given type list, unless it is a subclass of some class
  1156      *  in the list.
  1157      */
  1158     List<Type> incl(Type t, List<Type> ts) {
  1159         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1162     /** Remove type set from type set list.
  1163      */
  1164     List<Type> excl(Type t, List<Type> ts) {
  1165         if (ts.isEmpty()) {
  1166             return ts;
  1167         } else {
  1168             List<Type> ts1 = excl(t, ts.tail);
  1169             if (types.isSubtype(ts.head, t)) return ts1;
  1170             else if (ts1 == ts.tail) return ts;
  1171             else return ts1.prepend(ts.head);
  1175     /** Form the union of two type set lists.
  1176      */
  1177     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1178         List<Type> ts = ts1;
  1179         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1180             ts = incl(l.head, ts);
  1181         return ts;
  1184     /** Form the difference of two type lists.
  1185      */
  1186     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1187         List<Type> ts = ts1;
  1188         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1189             ts = excl(l.head, ts);
  1190         return ts;
  1193     /** Form the intersection of two type lists.
  1194      */
  1195     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1196         List<Type> ts = List.nil();
  1197         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1198             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1199         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1200             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1201         return ts;
  1204     /** Is exc an exception symbol that need not be declared?
  1205      */
  1206     boolean isUnchecked(ClassSymbol exc) {
  1207         return
  1208             exc.kind == ERR ||
  1209             exc.isSubClass(syms.errorType.tsym, types) ||
  1210             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1213     /** Is exc an exception type that need not be declared?
  1214      */
  1215     boolean isUnchecked(Type exc) {
  1216         return
  1217             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1218             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1219             exc.tag == BOT;
  1222     /** Same, but handling completion failures.
  1223      */
  1224     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1225         try {
  1226             return isUnchecked(exc);
  1227         } catch (CompletionFailure ex) {
  1228             completionError(pos, ex);
  1229             return true;
  1233     /** Is exc handled by given exception list?
  1234      */
  1235     boolean isHandled(Type exc, List<Type> handled) {
  1236         return isUnchecked(exc) || subset(exc, handled);
  1239     /** Return all exceptions in thrown list that are not in handled list.
  1240      *  @param thrown     The list of thrown exceptions.
  1241      *  @param handled    The list of handled exceptions.
  1242      */
  1243     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1244         List<Type> unhandled = List.nil();
  1245         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1246             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1247         return unhandled;
  1250 /* *************************************************************************
  1251  * Overriding/Implementation checking
  1252  **************************************************************************/
  1254     /** The level of access protection given by a flag set,
  1255      *  where PRIVATE is highest and PUBLIC is lowest.
  1256      */
  1257     static int protection(long flags) {
  1258         switch ((short)(flags & AccessFlags)) {
  1259         case PRIVATE: return 3;
  1260         case PROTECTED: return 1;
  1261         default:
  1262         case PUBLIC: return 0;
  1263         case 0: return 2;
  1267     /** A customized "cannot override" error message.
  1268      *  @param m      The overriding method.
  1269      *  @param other  The overridden method.
  1270      *  @return       An internationalized string.
  1271      */
  1272     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1273         String key;
  1274         if ((other.owner.flags() & INTERFACE) == 0)
  1275             key = "cant.override";
  1276         else if ((m.owner.flags() & INTERFACE) == 0)
  1277             key = "cant.implement";
  1278         else
  1279             key = "clashes.with";
  1280         return diags.fragment(key, m, m.location(), other, other.location());
  1283     /** A customized "override" warning message.
  1284      *  @param m      The overriding method.
  1285      *  @param other  The overridden method.
  1286      *  @return       An internationalized string.
  1287      */
  1288     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1289         String key;
  1290         if ((other.owner.flags() & INTERFACE) == 0)
  1291             key = "unchecked.override";
  1292         else if ((m.owner.flags() & INTERFACE) == 0)
  1293             key = "unchecked.implement";
  1294         else
  1295             key = "unchecked.clash.with";
  1296         return diags.fragment(key, m, m.location(), other, other.location());
  1299     /** A customized "override" warning message.
  1300      *  @param m      The overriding method.
  1301      *  @param other  The overridden method.
  1302      *  @return       An internationalized string.
  1303      */
  1304     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1305         String key;
  1306         if ((other.owner.flags() & INTERFACE) == 0)
  1307             key = "varargs.override";
  1308         else  if ((m.owner.flags() & INTERFACE) == 0)
  1309             key = "varargs.implement";
  1310         else
  1311             key = "varargs.clash.with";
  1312         return diags.fragment(key, m, m.location(), other, other.location());
  1315     /** Check that this method conforms with overridden method 'other'.
  1316      *  where `origin' is the class where checking started.
  1317      *  Complications:
  1318      *  (1) Do not check overriding of synthetic methods
  1319      *      (reason: they might be final).
  1320      *      todo: check whether this is still necessary.
  1321      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1322      *      than the method it implements. Augment the proxy methods with the
  1323      *      undeclared exceptions in this case.
  1324      *  (3) When generics are enabled, admit the case where an interface proxy
  1325      *      has a result type
  1326      *      extended by the result type of the method it implements.
  1327      *      Change the proxies result type to the smaller type in this case.
  1329      *  @param tree         The tree from which positions
  1330      *                      are extracted for errors.
  1331      *  @param m            The overriding method.
  1332      *  @param other        The overridden method.
  1333      *  @param origin       The class of which the overriding method
  1334      *                      is a member.
  1335      */
  1336     void checkOverride(JCTree tree,
  1337                        MethodSymbol m,
  1338                        MethodSymbol other,
  1339                        ClassSymbol origin) {
  1340         // Don't check overriding of synthetic methods or by bridge methods.
  1341         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1342             return;
  1345         // Error if static method overrides instance method (JLS 8.4.6.2).
  1346         if ((m.flags() & STATIC) != 0 &&
  1347                    (other.flags() & STATIC) == 0) {
  1348             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1349                       cannotOverride(m, other));
  1350             return;
  1353         // Error if instance method overrides static or final
  1354         // method (JLS 8.4.6.1).
  1355         if ((other.flags() & FINAL) != 0 ||
  1356                  (m.flags() & STATIC) == 0 &&
  1357                  (other.flags() & STATIC) != 0) {
  1358             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1359                       cannotOverride(m, other),
  1360                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1361             return;
  1364         if ((m.owner.flags() & ANNOTATION) != 0) {
  1365             // handled in validateAnnotationMethod
  1366             return;
  1369         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1370         if ((origin.flags() & INTERFACE) == 0 &&
  1371                  protection(m.flags()) > protection(other.flags())) {
  1372             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1373                       cannotOverride(m, other),
  1374                       other.flags() == 0 ?
  1375                           Flag.PACKAGE :
  1376                           asFlagSet(other.flags() & AccessFlags));
  1377             return;
  1380         Type mt = types.memberType(origin.type, m);
  1381         Type ot = types.memberType(origin.type, other);
  1382         // Error if overriding result type is different
  1383         // (or, in the case of generics mode, not a subtype) of
  1384         // overridden result type. We have to rename any type parameters
  1385         // before comparing types.
  1386         List<Type> mtvars = mt.getTypeArguments();
  1387         List<Type> otvars = ot.getTypeArguments();
  1388         Type mtres = mt.getReturnType();
  1389         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1391         overrideWarner.clear();
  1392         boolean resultTypesOK =
  1393             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1394         if (!resultTypesOK) {
  1395             if (!allowCovariantReturns &&
  1396                 m.owner != origin &&
  1397                 m.owner.isSubClass(other.owner, types)) {
  1398                 // allow limited interoperability with covariant returns
  1399             } else {
  1400                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1401                           "override.incompatible.ret",
  1402                           cannotOverride(m, other),
  1403                           mtres, otres);
  1404                 return;
  1406         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1407             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1408                     "override.unchecked.ret",
  1409                     uncheckedOverrides(m, other),
  1410                     mtres, otres);
  1413         // Error if overriding method throws an exception not reported
  1414         // by overridden method.
  1415         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1416         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1417         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1418         if (unhandledErased.nonEmpty()) {
  1419             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1420                       "override.meth.doesnt.throw",
  1421                       cannotOverride(m, other),
  1422                       unhandledUnerased.head);
  1423             return;
  1425         else if (unhandledUnerased.nonEmpty()) {
  1426             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1427                           "override.unchecked.thrown",
  1428                          cannotOverride(m, other),
  1429                          unhandledUnerased.head);
  1430             return;
  1433         // Optional warning if varargs don't agree
  1434         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1435             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1436             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1437                         ((m.flags() & Flags.VARARGS) != 0)
  1438                         ? "override.varargs.missing"
  1439                         : "override.varargs.extra",
  1440                         varargsOverrides(m, other));
  1443         // Warn if instance method overrides bridge method (compiler spec ??)
  1444         if ((other.flags() & BRIDGE) != 0) {
  1445             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1446                         uncheckedOverrides(m, other));
  1449         // Warn if a deprecated method overridden by a non-deprecated one.
  1450         if ((other.flags() & DEPRECATED) != 0
  1451             && (m.flags() & DEPRECATED) == 0
  1452             && m.outermostClass() != other.outermostClass()
  1453             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1454             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1457     // where
  1458         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1459             // If the method, m, is defined in an interface, then ignore the issue if the method
  1460             // is only inherited via a supertype and also implemented in the supertype,
  1461             // because in that case, we will rediscover the issue when examining the method
  1462             // in the supertype.
  1463             // If the method, m, is not defined in an interface, then the only time we need to
  1464             // address the issue is when the method is the supertype implemementation: any other
  1465             // case, we will have dealt with when examining the supertype classes
  1466             ClassSymbol mc = m.enclClass();
  1467             Type st = types.supertype(origin.type);
  1468             if (st.tag != CLASS)
  1469                 return true;
  1470             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1472             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1473                 List<Type> intfs = types.interfaces(origin.type);
  1474                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1476             else
  1477                 return (stimpl != m);
  1481     // used to check if there were any unchecked conversions
  1482     Warner overrideWarner = new Warner();
  1484     /** Check that a class does not inherit two concrete methods
  1485      *  with the same signature.
  1486      *  @param pos          Position to be used for error reporting.
  1487      *  @param site         The class type to be checked.
  1488      */
  1489     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1490         Type sup = types.supertype(site);
  1491         if (sup.tag != CLASS) return;
  1493         for (Type t1 = sup;
  1494              t1.tsym.type.isParameterized();
  1495              t1 = types.supertype(t1)) {
  1496             for (Scope.Entry e1 = t1.tsym.members().elems;
  1497                  e1 != null;
  1498                  e1 = e1.sibling) {
  1499                 Symbol s1 = e1.sym;
  1500                 if (s1.kind != MTH ||
  1501                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1502                     !s1.isInheritedIn(site.tsym, types) ||
  1503                     ((MethodSymbol)s1).implementation(site.tsym,
  1504                                                       types,
  1505                                                       true) != s1)
  1506                     continue;
  1507                 Type st1 = types.memberType(t1, s1);
  1508                 int s1ArgsLength = st1.getParameterTypes().length();
  1509                 if (st1 == s1.type) continue;
  1511                 for (Type t2 = sup;
  1512                      t2.tag == CLASS;
  1513                      t2 = types.supertype(t2)) {
  1514                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1515                          e2.scope != null;
  1516                          e2 = e2.next()) {
  1517                         Symbol s2 = e2.sym;
  1518                         if (s2 == s1 ||
  1519                             s2.kind != MTH ||
  1520                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1521                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1522                             !s2.isInheritedIn(site.tsym, types) ||
  1523                             ((MethodSymbol)s2).implementation(site.tsym,
  1524                                                               types,
  1525                                                               true) != s2)
  1526                             continue;
  1527                         Type st2 = types.memberType(t2, s2);
  1528                         if (types.overrideEquivalent(st1, st2))
  1529                             log.error(pos, "concrete.inheritance.conflict",
  1530                                       s1, t1, s2, t2, sup);
  1537     /** Check that classes (or interfaces) do not each define an abstract
  1538      *  method with same name and arguments but incompatible return types.
  1539      *  @param pos          Position to be used for error reporting.
  1540      *  @param t1           The first argument type.
  1541      *  @param t2           The second argument type.
  1542      */
  1543     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1544                                             Type t1,
  1545                                             Type t2) {
  1546         return checkCompatibleAbstracts(pos, t1, t2,
  1547                                         types.makeCompoundType(t1, t2));
  1550     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1551                                             Type t1,
  1552                                             Type t2,
  1553                                             Type site) {
  1554         return firstIncompatibility(pos, t1, t2, site) == null;
  1557     /** Return the first method which is defined with same args
  1558      *  but different return types in two given interfaces, or null if none
  1559      *  exists.
  1560      *  @param t1     The first type.
  1561      *  @param t2     The second type.
  1562      *  @param site   The most derived type.
  1563      *  @returns symbol from t2 that conflicts with one in t1.
  1564      */
  1565     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1566         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1567         closure(t1, interfaces1);
  1568         Map<TypeSymbol,Type> interfaces2;
  1569         if (t1 == t2)
  1570             interfaces2 = interfaces1;
  1571         else
  1572             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1574         for (Type t3 : interfaces1.values()) {
  1575             for (Type t4 : interfaces2.values()) {
  1576                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1577                 if (s != null) return s;
  1580         return null;
  1583     /** Compute all the supertypes of t, indexed by type symbol. */
  1584     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1585         if (t.tag != CLASS) return;
  1586         if (typeMap.put(t.tsym, t) == null) {
  1587             closure(types.supertype(t), typeMap);
  1588             for (Type i : types.interfaces(t))
  1589                 closure(i, typeMap);
  1593     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1594     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1595         if (t.tag != CLASS) return;
  1596         if (typesSkip.get(t.tsym) != null) return;
  1597         if (typeMap.put(t.tsym, t) == null) {
  1598             closure(types.supertype(t), typesSkip, typeMap);
  1599             for (Type i : types.interfaces(t))
  1600                 closure(i, typesSkip, typeMap);
  1604     /** Return the first method in t2 that conflicts with a method from t1. */
  1605     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1606         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1607             Symbol s1 = e1.sym;
  1608             Type st1 = null;
  1609             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1610             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1611             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1612             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1613                 Symbol s2 = e2.sym;
  1614                 if (s1 == s2) continue;
  1615                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1616                 if (st1 == null) st1 = types.memberType(t1, s1);
  1617                 Type st2 = types.memberType(t2, s2);
  1618                 if (types.overrideEquivalent(st1, st2)) {
  1619                     List<Type> tvars1 = st1.getTypeArguments();
  1620                     List<Type> tvars2 = st2.getTypeArguments();
  1621                     Type rt1 = st1.getReturnType();
  1622                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1623                     boolean compat =
  1624                         types.isSameType(rt1, rt2) ||
  1625                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1626                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1627                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1628                          checkCommonOverriderIn(s1,s2,site);
  1629                     if (!compat) {
  1630                         log.error(pos, "types.incompatible.diff.ret",
  1631                             t1, t2, s2.name +
  1632                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1633                         return s2;
  1635                 } else if (!checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
  1636                     log.error(pos,
  1637                             "name.clash.same.erasure.no.override",
  1638                             s1, s1.location(),
  1639                             s2, s2.location());
  1640                     return s2;
  1644         return null;
  1646     //WHERE
  1647     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1648         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1649         Type st1 = types.memberType(site, s1);
  1650         Type st2 = types.memberType(site, s2);
  1651         closure(site, supertypes);
  1652         for (Type t : supertypes.values()) {
  1653             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1654                 Symbol s3 = e.sym;
  1655                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1656                 Type st3 = types.memberType(site,s3);
  1657                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1658                     if (s3.owner == site.tsym) {
  1659                         return true;
  1661                     List<Type> tvars1 = st1.getTypeArguments();
  1662                     List<Type> tvars2 = st2.getTypeArguments();
  1663                     List<Type> tvars3 = st3.getTypeArguments();
  1664                     Type rt1 = st1.getReturnType();
  1665                     Type rt2 = st2.getReturnType();
  1666                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1667                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1668                     boolean compat =
  1669                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1670                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1671                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1672                     if (compat)
  1673                         return true;
  1677         return false;
  1680     /** Check that a given method conforms with any method it overrides.
  1681      *  @param tree         The tree from which positions are extracted
  1682      *                      for errors.
  1683      *  @param m            The overriding method.
  1684      */
  1685     void checkOverride(JCTree tree, MethodSymbol m) {
  1686         ClassSymbol origin = (ClassSymbol)m.owner;
  1687         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1688             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1689                 log.error(tree.pos(), "enum.no.finalize");
  1690                 return;
  1692         for (Type t = origin.type; t.tag == CLASS;
  1693              t = types.supertype(t)) {
  1694             if (t != origin.type) {
  1695                 checkOverride(tree, t, origin, m);
  1697             for (Type t2 : types.interfaces(t)) {
  1698                 checkOverride(tree, t2, origin, m);
  1703     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1704         TypeSymbol c = site.tsym;
  1705         Scope.Entry e = c.members().lookup(m.name);
  1706         while (e.scope != null) {
  1707             if (m.overrides(e.sym, origin, types, false)) {
  1708                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1709                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1712             e = e.next();
  1716     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1717         if (s1.kind == MTH &&
  1718                     s1.isInheritedIn(origin, types) &&
  1719                     (s1.flags() & SYNTHETIC) == 0 &&
  1720                     !s2.isConstructor()) {
  1721             Type er1 = s2.erasure(types);
  1722             Type er2 = s1.erasure(types);
  1723             if (types.isSameTypes(er1.getParameterTypes(),
  1724                     er2.getParameterTypes())) {
  1725                     return false;
  1728         return true;
  1732     /** Check that all abstract members of given class have definitions.
  1733      *  @param pos          Position to be used for error reporting.
  1734      *  @param c            The class.
  1735      */
  1736     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1737         try {
  1738             MethodSymbol undef = firstUndef(c, c);
  1739             if (undef != null) {
  1740                 if ((c.flags() & ENUM) != 0 &&
  1741                     types.supertype(c.type).tsym == syms.enumSym &&
  1742                     (c.flags() & FINAL) == 0) {
  1743                     // add the ABSTRACT flag to an enum
  1744                     c.flags_field |= ABSTRACT;
  1745                 } else {
  1746                     MethodSymbol undef1 =
  1747                         new MethodSymbol(undef.flags(), undef.name,
  1748                                          types.memberType(c.type, undef), undef.owner);
  1749                     log.error(pos, "does.not.override.abstract",
  1750                               c, undef1, undef1.location());
  1753         } catch (CompletionFailure ex) {
  1754             completionError(pos, ex);
  1757 //where
  1758         /** Return first abstract member of class `c' that is not defined
  1759          *  in `impl', null if there is none.
  1760          */
  1761         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1762             MethodSymbol undef = null;
  1763             // Do not bother to search in classes that are not abstract,
  1764             // since they cannot have abstract members.
  1765             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1766                 Scope s = c.members();
  1767                 for (Scope.Entry e = s.elems;
  1768                      undef == null && e != null;
  1769                      e = e.sibling) {
  1770                     if (e.sym.kind == MTH &&
  1771                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1772                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1773                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1774                         if (implmeth == null || implmeth == absmeth)
  1775                             undef = absmeth;
  1778                 if (undef == null) {
  1779                     Type st = types.supertype(c.type);
  1780                     if (st.tag == CLASS)
  1781                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1783                 for (List<Type> l = types.interfaces(c.type);
  1784                      undef == null && l.nonEmpty();
  1785                      l = l.tail) {
  1786                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1789             return undef;
  1792     void checkNonCyclicDecl(JCClassDecl tree) {
  1793         CycleChecker cc = new CycleChecker();
  1794         cc.scan(tree);
  1795         if (!cc.errorFound && !cc.partialCheck) {
  1796             tree.sym.flags_field |= ACYCLIC;
  1800     class CycleChecker extends TreeScanner {
  1802         List<Symbol> seenClasses = List.nil();
  1803         boolean errorFound = false;
  1804         boolean partialCheck = false;
  1806         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  1807             if (sym != null && sym.kind == TYP) {
  1808                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  1809                 if (classEnv != null) {
  1810                     DiagnosticSource prevSource = log.currentSource();
  1811                     try {
  1812                         log.useSource(classEnv.toplevel.sourcefile);
  1813                         scan(classEnv.tree);
  1815                     finally {
  1816                         log.useSource(prevSource.getFile());
  1818                 } else if (sym.kind == TYP) {
  1819                     checkClass(pos, sym, List.<JCTree>nil());
  1821             } else {
  1822                 //not completed yet
  1823                 partialCheck = true;
  1827         @Override
  1828         public void visitSelect(JCFieldAccess tree) {
  1829             super.visitSelect(tree);
  1830             checkSymbol(tree.pos(), tree.sym);
  1833         @Override
  1834         public void visitIdent(JCIdent tree) {
  1835             checkSymbol(tree.pos(), tree.sym);
  1838         @Override
  1839         public void visitTypeApply(JCTypeApply tree) {
  1840             scan(tree.clazz);
  1843         @Override
  1844         public void visitTypeArray(JCArrayTypeTree tree) {
  1845             scan(tree.elemtype);
  1848         @Override
  1849         public void visitClassDef(JCClassDecl tree) {
  1850             List<JCTree> supertypes = List.nil();
  1851             if (tree.getExtendsClause() != null) {
  1852                 supertypes = supertypes.prepend(tree.getExtendsClause());
  1854             if (tree.getImplementsClause() != null) {
  1855                 for (JCTree intf : tree.getImplementsClause()) {
  1856                     supertypes = supertypes.prepend(intf);
  1859             checkClass(tree.pos(), tree.sym, supertypes);
  1862         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  1863             if ((c.flags_field & ACYCLIC) != 0)
  1864                 return;
  1865             if (seenClasses.contains(c)) {
  1866                 errorFound = true;
  1867                 noteCyclic(pos, (ClassSymbol)c);
  1868             } else if (!c.type.isErroneous()) {
  1869                 try {
  1870                     seenClasses = seenClasses.prepend(c);
  1871                     if (c.type.tag == CLASS) {
  1872                         if (supertypes.nonEmpty()) {
  1873                             scan(supertypes);
  1875                         else {
  1876                             ClassType ct = (ClassType)c.type;
  1877                             if (ct.supertype_field == null ||
  1878                                     ct.interfaces_field == null) {
  1879                                 //not completed yet
  1880                                 partialCheck = true;
  1881                                 return;
  1883                             checkSymbol(pos, ct.supertype_field.tsym);
  1884                             for (Type intf : ct.interfaces_field) {
  1885                                 checkSymbol(pos, intf.tsym);
  1888                         if (c.owner.kind == TYP) {
  1889                             checkSymbol(pos, c.owner);
  1892                 } finally {
  1893                     seenClasses = seenClasses.tail;
  1899     /** Check for cyclic references. Issue an error if the
  1900      *  symbol of the type referred to has a LOCKED flag set.
  1902      *  @param pos      Position to be used for error reporting.
  1903      *  @param t        The type referred to.
  1904      */
  1905     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1906         checkNonCyclicInternal(pos, t);
  1910     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1911         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1914     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1915         final TypeVar tv;
  1916         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1917             return;
  1918         if (seen.contains(t)) {
  1919             tv = (TypeVar)t;
  1920             tv.bound = types.createErrorType(t);
  1921             log.error(pos, "cyclic.inheritance", t);
  1922         } else if (t.tag == TYPEVAR) {
  1923             tv = (TypeVar)t;
  1924             seen = seen.prepend(tv);
  1925             for (Type b : types.getBounds(tv))
  1926                 checkNonCyclic1(pos, b, seen);
  1930     /** Check for cyclic references. Issue an error if the
  1931      *  symbol of the type referred to has a LOCKED flag set.
  1933      *  @param pos      Position to be used for error reporting.
  1934      *  @param t        The type referred to.
  1935      *  @returns        True if the check completed on all attributed classes
  1936      */
  1937     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1938         boolean complete = true; // was the check complete?
  1939         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1940         Symbol c = t.tsym;
  1941         if ((c.flags_field & ACYCLIC) != 0) return true;
  1943         if ((c.flags_field & LOCKED) != 0) {
  1944             noteCyclic(pos, (ClassSymbol)c);
  1945         } else if (!c.type.isErroneous()) {
  1946             try {
  1947                 c.flags_field |= LOCKED;
  1948                 if (c.type.tag == CLASS) {
  1949                     ClassType clazz = (ClassType)c.type;
  1950                     if (clazz.interfaces_field != null)
  1951                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1952                             complete &= checkNonCyclicInternal(pos, l.head);
  1953                     if (clazz.supertype_field != null) {
  1954                         Type st = clazz.supertype_field;
  1955                         if (st != null && st.tag == CLASS)
  1956                             complete &= checkNonCyclicInternal(pos, st);
  1958                     if (c.owner.kind == TYP)
  1959                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1961             } finally {
  1962                 c.flags_field &= ~LOCKED;
  1965         if (complete)
  1966             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1967         if (complete) c.flags_field |= ACYCLIC;
  1968         return complete;
  1971     /** Note that we found an inheritance cycle. */
  1972     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1973         log.error(pos, "cyclic.inheritance", c);
  1974         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1975             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  1976         Type st = types.supertype(c.type);
  1977         if (st.tag == CLASS)
  1978             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  1979         c.type = types.createErrorType(c, c.type);
  1980         c.flags_field |= ACYCLIC;
  1983     /** Check that all methods which implement some
  1984      *  method conform to the method they implement.
  1985      *  @param tree         The class definition whose members are checked.
  1986      */
  1987     void checkImplementations(JCClassDecl tree) {
  1988         checkImplementations(tree, tree.sym);
  1990 //where
  1991         /** Check that all methods which implement some
  1992          *  method in `ic' conform to the method they implement.
  1993          */
  1994         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1995             ClassSymbol origin = tree.sym;
  1996             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1997                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1998                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1999                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2000                         if (e.sym.kind == MTH &&
  2001                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2002                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2003                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2004                             if (implmeth != null && implmeth != absmeth &&
  2005                                 (implmeth.owner.flags() & INTERFACE) ==
  2006                                 (origin.flags() & INTERFACE)) {
  2007                                 // don't check if implmeth is in a class, yet
  2008                                 // origin is an interface. This case arises only
  2009                                 // if implmeth is declared in Object. The reason is
  2010                                 // that interfaces really don't inherit from
  2011                                 // Object it's just that the compiler represents
  2012                                 // things that way.
  2013                                 checkOverride(tree, implmeth, absmeth, origin);
  2021     /** Check that all abstract methods implemented by a class are
  2022      *  mutually compatible.
  2023      *  @param pos          Position to be used for error reporting.
  2024      *  @param c            The class whose interfaces are checked.
  2025      */
  2026     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2027         List<Type> supertypes = types.interfaces(c);
  2028         Type supertype = types.supertype(c);
  2029         if (supertype.tag == CLASS &&
  2030             (supertype.tsym.flags() & ABSTRACT) != 0)
  2031             supertypes = supertypes.prepend(supertype);
  2032         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2033             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2034                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2035                 return;
  2036             for (List<Type> m = supertypes; m != l; m = m.tail)
  2037                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2038                     return;
  2040         checkCompatibleConcretes(pos, c);
  2043     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2044         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2045             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2046                 // VM allows methods and variables with differing types
  2047                 if (sym.kind == e.sym.kind &&
  2048                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2049                     sym != e.sym &&
  2050                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2051                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2052                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2053                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2054                     return;
  2060     /** Check that all non-override equivalent methods accessible from 'site'
  2061      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2063      *  @param pos  Position to be used for error reporting.
  2064      *  @param site The class whose methods are checked.
  2065      *  @param sym  The method symbol to be checked.
  2066      */
  2067     void checkClashes(DiagnosticPosition pos, Type site, Symbol sym) {
  2068         List<Type> supertypes = types.closure(site);
  2069         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2070             for (List<Type> m = supertypes; m.nonEmpty(); m = m.tail) {
  2071                 checkClashes(pos, l.head, m.head, site, sym);
  2076     /** Reports an error whenever 'sym' seen as a member of type 't1' clashes with
  2077      *  some unrelated method defined in 't2'.
  2078      */
  2079     private void checkClashes(DiagnosticPosition pos, Type t1, Type t2, Type site, Symbol s1) {
  2080         ClashFilter cf = new ClashFilter(site);
  2081         s1 = ((MethodSymbol)s1).implementedIn(t1.tsym, types);
  2082         if (s1 == null) return;
  2083         Type st1 = types.memberType(site, s1);
  2084         for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name, cf); e2.scope != null; e2 = e2.next(cf)) {
  2085             Symbol s2 = e2.sym;
  2086             if (s1 == s2) continue;
  2087             Type st2 = types.memberType(site, s2);
  2088             if (!types.overrideEquivalent(st1, st2) &&
  2089                     !checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
  2090                 log.error(pos,
  2091                         "name.clash.same.erasure.no.override",
  2092                         s1, s1.location(),
  2093                         s2, s2.location());
  2097     //where
  2098     private class ClashFilter implements Filter<Symbol> {
  2100         Type site;
  2102         ClashFilter(Type site) {
  2103             this.site = site;
  2106         public boolean accepts(Symbol s) {
  2107             return s.kind == MTH &&
  2108                     (s.flags() & SYNTHETIC) == 0 &&
  2109                     s.isInheritedIn(site.tsym, types) &&
  2110                     !s.isConstructor();
  2114     /** Report a conflict between a user symbol and a synthetic symbol.
  2115      */
  2116     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2117         if (!sym.type.isErroneous()) {
  2118             if (warnOnSyntheticConflicts) {
  2119                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2121             else {
  2122                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2127     /** Check that class c does not implement directly or indirectly
  2128      *  the same parameterized interface with two different argument lists.
  2129      *  @param pos          Position to be used for error reporting.
  2130      *  @param type         The type whose interfaces are checked.
  2131      */
  2132     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2133         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2135 //where
  2136         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2137          *  with their class symbol as key and their type as value. Make
  2138          *  sure no class is entered with two different types.
  2139          */
  2140         void checkClassBounds(DiagnosticPosition pos,
  2141                               Map<TypeSymbol,Type> seensofar,
  2142                               Type type) {
  2143             if (type.isErroneous()) return;
  2144             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2145                 Type it = l.head;
  2146                 Type oldit = seensofar.put(it.tsym, it);
  2147                 if (oldit != null) {
  2148                     List<Type> oldparams = oldit.allparams();
  2149                     List<Type> newparams = it.allparams();
  2150                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2151                         log.error(pos, "cant.inherit.diff.arg",
  2152                                   it.tsym, Type.toString(oldparams),
  2153                                   Type.toString(newparams));
  2155                 checkClassBounds(pos, seensofar, it);
  2157             Type st = types.supertype(type);
  2158             if (st != null) checkClassBounds(pos, seensofar, st);
  2161     /** Enter interface into into set.
  2162      *  If it existed already, issue a "repeated interface" error.
  2163      */
  2164     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2165         if (its.contains(it))
  2166             log.error(pos, "repeated.interface");
  2167         else {
  2168             its.add(it);
  2172 /* *************************************************************************
  2173  * Check annotations
  2174  **************************************************************************/
  2176     /**
  2177      * Recursively validate annotations values
  2178      */
  2179     void validateAnnotationTree(JCTree tree) {
  2180         class AnnotationValidator extends TreeScanner {
  2181             @Override
  2182             public void visitAnnotation(JCAnnotation tree) {
  2183                 super.visitAnnotation(tree);
  2184                 validateAnnotation(tree);
  2187         tree.accept(new AnnotationValidator());
  2190     /** Annotation types are restricted to primitives, String, an
  2191      *  enum, an annotation, Class, Class<?>, Class<? extends
  2192      *  Anything>, arrays of the preceding.
  2193      */
  2194     void validateAnnotationType(JCTree restype) {
  2195         // restype may be null if an error occurred, so don't bother validating it
  2196         if (restype != null) {
  2197             validateAnnotationType(restype.pos(), restype.type);
  2201     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2202         if (type.isPrimitive()) return;
  2203         if (types.isSameType(type, syms.stringType)) return;
  2204         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2205         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2206         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2207         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2208             validateAnnotationType(pos, types.elemtype(type));
  2209             return;
  2211         log.error(pos, "invalid.annotation.member.type");
  2214     /**
  2215      * "It is also a compile-time error if any method declared in an
  2216      * annotation type has a signature that is override-equivalent to
  2217      * that of any public or protected method declared in class Object
  2218      * or in the interface annotation.Annotation."
  2220      * @jls3 9.6 Annotation Types
  2221      */
  2222     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2223         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2224             Scope s = sup.tsym.members();
  2225             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2226                 if (e.sym.kind == MTH &&
  2227                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2228                     types.overrideEquivalent(m.type, e.sym.type))
  2229                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2234     /** Check the annotations of a symbol.
  2235      */
  2236     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2237         if (skipAnnotations) return;
  2238         for (JCAnnotation a : annotations)
  2239             validateAnnotation(a, s);
  2242     /** Check the type annotations
  2243      */
  2244     public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
  2245         if (skipAnnotations) return;
  2246         for (JCTypeAnnotation a : annotations)
  2247             validateTypeAnnotation(a, isTypeParameter);
  2250     /** Check an annotation of a symbol.
  2251      */
  2252     public void validateAnnotation(JCAnnotation a, Symbol s) {
  2253         validateAnnotationTree(a);
  2255         if (!annotationApplicable(a, s))
  2256             log.error(a.pos(), "annotation.type.not.applicable");
  2258         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2259             if (!isOverrider(s))
  2260                 log.error(a.pos(), "method.does.not.override.superclass");
  2264     public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
  2265         if (a.type == null)
  2266             throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
  2267         validateAnnotationTree(a);
  2269         if (!isTypeAnnotation(a, isTypeParameter))
  2270             log.error(a.pos(), "annotation.type.not.applicable");
  2273     /** Is s a method symbol that overrides a method in a superclass? */
  2274     boolean isOverrider(Symbol s) {
  2275         if (s.kind != MTH || s.isStatic())
  2276             return false;
  2277         MethodSymbol m = (MethodSymbol)s;
  2278         TypeSymbol owner = (TypeSymbol)m.owner;
  2279         for (Type sup : types.closure(owner.type)) {
  2280             if (sup == owner.type)
  2281                 continue; // skip "this"
  2282             Scope scope = sup.tsym.members();
  2283             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2284                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2285                     return true;
  2288         return false;
  2291     /** Is the annotation applicable to type annotations */
  2292     boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
  2293         Attribute.Compound atTarget =
  2294             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2295         if (atTarget == null) return true;
  2296         Attribute atValue = atTarget.member(names.value);
  2297         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2298         Attribute.Array arr = (Attribute.Array) atValue;
  2299         for (Attribute app : arr.values) {
  2300             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2301             Attribute.Enum e = (Attribute.Enum) app;
  2302             if (!isTypeParameter && e.value.name == names.TYPE_USE)
  2303                 return true;
  2304             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  2305                 return true;
  2307         return false;
  2310     /** Is the annotation applicable to the symbol? */
  2311     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2312         Attribute.Compound atTarget =
  2313             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2314         if (atTarget == null) return true;
  2315         Attribute atValue = atTarget.member(names.value);
  2316         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2317         Attribute.Array arr = (Attribute.Array) atValue;
  2318         for (Attribute app : arr.values) {
  2319             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2320             Attribute.Enum e = (Attribute.Enum) app;
  2321             if (e.value.name == names.TYPE)
  2322                 { if (s.kind == TYP) return true; }
  2323             else if (e.value.name == names.FIELD)
  2324                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2325             else if (e.value.name == names.METHOD)
  2326                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2327             else if (e.value.name == names.PARAMETER)
  2328                 { if (s.kind == VAR &&
  2329                       s.owner.kind == MTH &&
  2330                       (s.flags() & PARAMETER) != 0)
  2331                     return true;
  2333             else if (e.value.name == names.CONSTRUCTOR)
  2334                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2335             else if (e.value.name == names.LOCAL_VARIABLE)
  2336                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2337                       (s.flags() & PARAMETER) == 0)
  2338                     return true;
  2340             else if (e.value.name == names.ANNOTATION_TYPE)
  2341                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2342                     return true;
  2344             else if (e.value.name == names.PACKAGE)
  2345                 { if (s.kind == PCK) return true; }
  2346             else if (e.value.name == names.TYPE_USE)
  2347                 { if (s.kind == TYP ||
  2348                       s.kind == VAR ||
  2349                       (s.kind == MTH && !s.isConstructor() &&
  2350                        s.type.getReturnType().tag != VOID))
  2351                     return true;
  2353             else
  2354                 return true; // recovery
  2356         return false;
  2359     /** Check an annotation value.
  2360      */
  2361     public void validateAnnotation(JCAnnotation a) {
  2362         if (a.type.isErroneous()) return;
  2364         // collect an inventory of the members (sorted alphabetically)
  2365         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2366             public int compare(Symbol t, Symbol t1) {
  2367                 return t.name.compareTo(t1.name);
  2369         });
  2370         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2371              e != null;
  2372              e = e.sibling)
  2373             if (e.sym.kind == MTH)
  2374                 members.add((MethodSymbol) e.sym);
  2376         // count them off as they're annotated
  2377         for (JCTree arg : a.args) {
  2378             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  2379             JCAssign assign = (JCAssign) arg;
  2380             Symbol m = TreeInfo.symbol(assign.lhs);
  2381             if (m == null || m.type.isErroneous()) continue;
  2382             if (!members.remove(m))
  2383                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2384                           m.name, a.type);
  2387         // all the remaining ones better have default values
  2388         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2389         for (MethodSymbol m : members) {
  2390             if (m.defaultValue == null && !m.type.isErroneous()) {
  2391                 missingDefaults.append(m.name);
  2394         if (missingDefaults.nonEmpty()) {
  2395             String key = (missingDefaults.size() > 1)
  2396                     ? "annotation.missing.default.value.1"
  2397                     : "annotation.missing.default.value";
  2398             log.error(a.pos(), key, a.type, missingDefaults);
  2401         // special case: java.lang.annotation.Target must not have
  2402         // repeated values in its value member
  2403         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2404             a.args.tail == null)
  2405             return;
  2407         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  2408         JCAssign assign = (JCAssign) a.args.head;
  2409         Symbol m = TreeInfo.symbol(assign.lhs);
  2410         if (m.name != names.value) return;
  2411         JCTree rhs = assign.rhs;
  2412         if (rhs.getTag() != JCTree.NEWARRAY) return;
  2413         JCNewArray na = (JCNewArray) rhs;
  2414         Set<Symbol> targets = new HashSet<Symbol>();
  2415         for (JCTree elem : na.elems) {
  2416             if (!targets.add(TreeInfo.symbol(elem))) {
  2417                 log.error(elem.pos(), "repeated.annotation.target");
  2422     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2423         if (allowAnnotations &&
  2424             lint.isEnabled(LintCategory.DEP_ANN) &&
  2425             (s.flags() & DEPRECATED) != 0 &&
  2426             !syms.deprecatedType.isErroneous() &&
  2427             s.attribute(syms.deprecatedType.tsym) == null) {
  2428             log.warning(LintCategory.DEP_ANN,
  2429                     pos, "missing.deprecated.annotation");
  2433 /* *************************************************************************
  2434  * Check for recursive annotation elements.
  2435  **************************************************************************/
  2437     /** Check for cycles in the graph of annotation elements.
  2438      */
  2439     void checkNonCyclicElements(JCClassDecl tree) {
  2440         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2441         assert (tree.sym.flags_field & LOCKED) == 0;
  2442         try {
  2443             tree.sym.flags_field |= LOCKED;
  2444             for (JCTree def : tree.defs) {
  2445                 if (def.getTag() != JCTree.METHODDEF) continue;
  2446                 JCMethodDecl meth = (JCMethodDecl)def;
  2447                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2449         } finally {
  2450             tree.sym.flags_field &= ~LOCKED;
  2451             tree.sym.flags_field |= ACYCLIC_ANN;
  2455     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2456         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2457             return;
  2458         if ((tsym.flags_field & LOCKED) != 0) {
  2459             log.error(pos, "cyclic.annotation.element");
  2460             return;
  2462         try {
  2463             tsym.flags_field |= LOCKED;
  2464             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2465                 Symbol s = e.sym;
  2466                 if (s.kind != Kinds.MTH)
  2467                     continue;
  2468                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2470         } finally {
  2471             tsym.flags_field &= ~LOCKED;
  2472             tsym.flags_field |= ACYCLIC_ANN;
  2476     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2477         switch (type.tag) {
  2478         case TypeTags.CLASS:
  2479             if ((type.tsym.flags() & ANNOTATION) != 0)
  2480                 checkNonCyclicElementsInternal(pos, type.tsym);
  2481             break;
  2482         case TypeTags.ARRAY:
  2483             checkAnnotationResType(pos, types.elemtype(type));
  2484             break;
  2485         default:
  2486             break; // int etc
  2490 /* *************************************************************************
  2491  * Check for cycles in the constructor call graph.
  2492  **************************************************************************/
  2494     /** Check for cycles in the graph of constructors calling other
  2495      *  constructors.
  2496      */
  2497     void checkCyclicConstructors(JCClassDecl tree) {
  2498         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2500         // enter each constructor this-call into the map
  2501         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2502             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2503             if (app == null) continue;
  2504             JCMethodDecl meth = (JCMethodDecl) l.head;
  2505             if (TreeInfo.name(app.meth) == names._this) {
  2506                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2507             } else {
  2508                 meth.sym.flags_field |= ACYCLIC;
  2512         // Check for cycles in the map
  2513         Symbol[] ctors = new Symbol[0];
  2514         ctors = callMap.keySet().toArray(ctors);
  2515         for (Symbol caller : ctors) {
  2516             checkCyclicConstructor(tree, caller, callMap);
  2520     /** Look in the map to see if the given constructor is part of a
  2521      *  call cycle.
  2522      */
  2523     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2524                                         Map<Symbol,Symbol> callMap) {
  2525         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2526             if ((ctor.flags_field & LOCKED) != 0) {
  2527                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2528                           "recursive.ctor.invocation");
  2529             } else {
  2530                 ctor.flags_field |= LOCKED;
  2531                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2532                 ctor.flags_field &= ~LOCKED;
  2534             ctor.flags_field |= ACYCLIC;
  2538 /* *************************************************************************
  2539  * Miscellaneous
  2540  **************************************************************************/
  2542     /**
  2543      * Return the opcode of the operator but emit an error if it is an
  2544      * error.
  2545      * @param pos        position for error reporting.
  2546      * @param operator   an operator
  2547      * @param tag        a tree tag
  2548      * @param left       type of left hand side
  2549      * @param right      type of right hand side
  2550      */
  2551     int checkOperator(DiagnosticPosition pos,
  2552                        OperatorSymbol operator,
  2553                        int tag,
  2554                        Type left,
  2555                        Type right) {
  2556         if (operator.opcode == ByteCodes.error) {
  2557             log.error(pos,
  2558                       "operator.cant.be.applied",
  2559                       treeinfo.operatorName(tag),
  2560                       List.of(left, right));
  2562         return operator.opcode;
  2566     /**
  2567      *  Check for division by integer constant zero
  2568      *  @param pos           Position for error reporting.
  2569      *  @param operator      The operator for the expression
  2570      *  @param operand       The right hand operand for the expression
  2571      */
  2572     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2573         if (operand.constValue() != null
  2574             && lint.isEnabled(LintCategory.DIVZERO)
  2575             && operand.tag <= LONG
  2576             && ((Number) (operand.constValue())).longValue() == 0) {
  2577             int opc = ((OperatorSymbol)operator).opcode;
  2578             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2579                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2580                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  2585     /**
  2586      * Check for empty statements after if
  2587      */
  2588     void checkEmptyIf(JCIf tree) {
  2589         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(LintCategory.EMPTY))
  2590             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  2593     /** Check that symbol is unique in given scope.
  2594      *  @param pos           Position for error reporting.
  2595      *  @param sym           The symbol.
  2596      *  @param s             The scope.
  2597      */
  2598     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2599         if (sym.type.isErroneous())
  2600             return true;
  2601         if (sym.owner.name == names.any) return false;
  2602         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2603             if (sym != e.sym &&
  2604                 sym.kind == e.sym.kind &&
  2605                 sym.name != names.error &&
  2606                 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2607                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2608                     varargsDuplicateError(pos, sym, e.sym);
  2609                 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
  2610                     duplicateErasureError(pos, sym, e.sym);
  2611                 else
  2612                     duplicateError(pos, e.sym);
  2613                 return false;
  2616         return true;
  2618     //where
  2619     /** Report duplicate declaration error.
  2620      */
  2621     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2622         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2623             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2627     /** Check that single-type import is not already imported or top-level defined,
  2628      *  but make an exception for two single-type imports which denote the same type.
  2629      *  @param pos           Position for error reporting.
  2630      *  @param sym           The symbol.
  2631      *  @param s             The scope
  2632      */
  2633     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2634         return checkUniqueImport(pos, sym, s, false);
  2637     /** Check that static single-type import is not already imported or top-level defined,
  2638      *  but make an exception for two single-type imports which denote the same type.
  2639      *  @param pos           Position for error reporting.
  2640      *  @param sym           The symbol.
  2641      *  @param s             The scope
  2642      *  @param staticImport  Whether or not this was a static import
  2643      */
  2644     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2645         return checkUniqueImport(pos, sym, s, true);
  2648     /** Check that single-type import is not already imported or top-level defined,
  2649      *  but make an exception for two single-type imports which denote the same type.
  2650      *  @param pos           Position for error reporting.
  2651      *  @param sym           The symbol.
  2652      *  @param s             The scope.
  2653      *  @param staticImport  Whether or not this was a static import
  2654      */
  2655     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2656         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2657             // is encountered class entered via a class declaration?
  2658             boolean isClassDecl = e.scope == s;
  2659             if ((isClassDecl || sym != e.sym) &&
  2660                 sym.kind == e.sym.kind &&
  2661                 sym.name != names.error) {
  2662                 if (!e.sym.type.isErroneous()) {
  2663                     String what = e.sym.toString();
  2664                     if (!isClassDecl) {
  2665                         if (staticImport)
  2666                             log.error(pos, "already.defined.static.single.import", what);
  2667                         else
  2668                             log.error(pos, "already.defined.single.import", what);
  2670                     else if (sym != e.sym)
  2671                         log.error(pos, "already.defined.this.unit", what);
  2673                 return false;
  2676         return true;
  2679     /** Check that a qualified name is in canonical form (for import decls).
  2680      */
  2681     public void checkCanonical(JCTree tree) {
  2682         if (!isCanonical(tree))
  2683             log.error(tree.pos(), "import.requires.canonical",
  2684                       TreeInfo.symbol(tree));
  2686         // where
  2687         private boolean isCanonical(JCTree tree) {
  2688             while (tree.getTag() == JCTree.SELECT) {
  2689                 JCFieldAccess s = (JCFieldAccess) tree;
  2690                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2691                     return false;
  2692                 tree = s.selected;
  2694             return true;
  2697     private class ConversionWarner extends Warner {
  2698         final String uncheckedKey;
  2699         final Type found;
  2700         final Type expected;
  2701         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  2702             super(pos);
  2703             this.uncheckedKey = uncheckedKey;
  2704             this.found = found;
  2705             this.expected = expected;
  2708         @Override
  2709         public void warn(LintCategory lint) {
  2710             boolean warned = this.warned;
  2711             super.warn(lint);
  2712             if (warned) return; // suppress redundant diagnostics
  2713             switch (lint) {
  2714                 case UNCHECKED:
  2715                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  2716                     break;
  2717                 case VARARGS:
  2718                     if (method != null &&
  2719                             method.attribute(syms.trustMeType.tsym) != null &&
  2720                             isTrustMeAllowedOnMethod(method) &&
  2721                             !types.isReifiable(method.type.getParameterTypes().last())) {
  2722                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  2724                     break;
  2725                 default:
  2726                     throw new AssertionError("Unexpected lint: " + lint);
  2731     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2732         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2735     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2736         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial