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

Mon, 24 Jan 2011 15:44:51 +0000

author
mcimadamore
date
Mon, 24 Jan 2011 15:44:51 +0000
changeset 829
ce6175cfe11e
parent 828
19c900c703c6
child 844
2088e674f0e0
permissions
-rw-r--r--

6968793: issues with diagnostics
Summary: several diagnostic improvements
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, 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 boolean checkExtends(Type a, TypeVar bs) {
   510          if (a.isUnbound()) {
   511              return true;
   512          } else if (a.tag != WILDCARD) {
   513              a = types.upperBound(a);
   514              return types.isSubtype(a, bs.bound);
   515          } else if (a.isExtendsBound()) {
   516              return types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings);
   517          } else if (a.isSuperBound()) {
   518              return !types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound());
   519          }
   520          return true;
   521      }
   523     /** Check that type is different from 'void'.
   524      *  @param pos           Position to be used for error reporting.
   525      *  @param t             The type to be checked.
   526      */
   527     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   528         if (t.tag == VOID) {
   529             log.error(pos, "void.not.allowed.here");
   530             return types.createErrorType(t);
   531         } else {
   532             return t;
   533         }
   534     }
   536     /** Check that type is a class or interface type.
   537      *  @param pos           Position to be used for error reporting.
   538      *  @param t             The type to be checked.
   539      */
   540     Type checkClassType(DiagnosticPosition pos, Type t) {
   541         if (t.tag != CLASS && t.tag != ERROR)
   542             return typeTagError(pos,
   543                                 diags.fragment("type.req.class"),
   544                                 (t.tag == TYPEVAR)
   545                                 ? diags.fragment("type.parameter", t)
   546                                 : t);
   547         else
   548             return t;
   549     }
   551     /** Check that type is a class or interface type.
   552      *  @param pos           Position to be used for error reporting.
   553      *  @param t             The type to be checked.
   554      *  @param noBounds    True if type bounds are illegal here.
   555      */
   556     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   557         t = checkClassType(pos, t);
   558         if (noBounds && t.isParameterized()) {
   559             List<Type> args = t.getTypeArguments();
   560             while (args.nonEmpty()) {
   561                 if (args.head.tag == WILDCARD)
   562                     return typeTagError(pos,
   563                                         diags.fragment("type.req.exact"),
   564                                         args.head);
   565                 args = args.tail;
   566             }
   567         }
   568         return t;
   569     }
   571     /** Check that type is a reifiable class, interface or array type.
   572      *  @param pos           Position to be used for error reporting.
   573      *  @param t             The type to be checked.
   574      */
   575     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   576         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   577             return typeTagError(pos,
   578                                 diags.fragment("type.req.class.array"),
   579                                 t);
   580         } else if (!types.isReifiable(t)) {
   581             log.error(pos, "illegal.generic.type.for.instof");
   582             return types.createErrorType(t);
   583         } else {
   584             return t;
   585         }
   586     }
   588     /** Check that type is a reference type, i.e. a class, interface or array type
   589      *  or a type variable.
   590      *  @param pos           Position to be used for error reporting.
   591      *  @param t             The type to be checked.
   592      */
   593     Type checkRefType(DiagnosticPosition pos, Type t) {
   594         switch (t.tag) {
   595         case CLASS:
   596         case ARRAY:
   597         case TYPEVAR:
   598         case WILDCARD:
   599         case ERROR:
   600             return t;
   601         default:
   602             return typeTagError(pos,
   603                                 diags.fragment("type.req.ref"),
   604                                 t);
   605         }
   606     }
   608     /** Check that each type is a reference type, i.e. a class, interface or array type
   609      *  or a type variable.
   610      *  @param trees         Original trees, used for error reporting.
   611      *  @param types         The types to be checked.
   612      */
   613     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   614         List<JCExpression> tl = trees;
   615         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   616             l.head = checkRefType(tl.head.pos(), l.head);
   617             tl = tl.tail;
   618         }
   619         return types;
   620     }
   622     /** Check that type is a null or reference type.
   623      *  @param pos           Position to be used for error reporting.
   624      *  @param t             The type to be checked.
   625      */
   626     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   627         switch (t.tag) {
   628         case CLASS:
   629         case ARRAY:
   630         case TYPEVAR:
   631         case WILDCARD:
   632         case BOT:
   633         case ERROR:
   634             return t;
   635         default:
   636             return typeTagError(pos,
   637                                 diags.fragment("type.req.ref"),
   638                                 t);
   639         }
   640     }
   642     /** Check that flag set does not contain elements of two conflicting sets. s
   643      *  Return true if it doesn't.
   644      *  @param pos           Position to be used for error reporting.
   645      *  @param flags         The set of flags to be checked.
   646      *  @param set1          Conflicting flags set #1.
   647      *  @param set2          Conflicting flags set #2.
   648      */
   649     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   650         if ((flags & set1) != 0 && (flags & set2) != 0) {
   651             log.error(pos,
   652                       "illegal.combination.of.modifiers",
   653                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   654                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   655             return false;
   656         } else
   657             return true;
   658     }
   660     /** Check that the type inferred using the diamond operator does not contain
   661      *  non-denotable types such as captured types or intersection types.
   662      *  @param t the type inferred using the diamond operator
   663      */
   664     List<Type> checkDiamond(ClassType t) {
   665         DiamondTypeChecker dtc = new DiamondTypeChecker();
   666         ListBuffer<Type> buf = ListBuffer.lb();
   667         for (Type arg : t.getTypeArguments()) {
   668             if (!dtc.visit(arg, null)) {
   669                 buf.append(arg);
   670             }
   671         }
   672         return buf.toList();
   673     }
   675     static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
   676         public Boolean visitType(Type t, Void s) {
   677             return true;
   678         }
   679         @Override
   680         public Boolean visitClassType(ClassType t, Void s) {
   681             if (t.isCompound()) {
   682                 return false;
   683             }
   684             for (Type targ : t.getTypeArguments()) {
   685                 if (!visit(targ, s)) {
   686                     return false;
   687                 }
   688             }
   689             return true;
   690         }
   691         @Override
   692         public Boolean visitCapturedType(CapturedType t, Void s) {
   693             return false;
   694         }
   695     }
   697     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   698         MethodSymbol m = tree.sym;
   699         if (!allowSimplifiedVarargs) return;
   700         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   701         Type varargElemType = null;
   702         if (m.isVarArgs()) {
   703             varargElemType = types.elemtype(tree.params.last().type);
   704         }
   705         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   706             if (varargElemType != null) {
   707                 log.error(tree,
   708                         "varargs.invalid.trustme.anno",
   709                         syms.trustMeType.tsym,
   710                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   711             } else {
   712                 log.error(tree,
   713                             "varargs.invalid.trustme.anno",
   714                             syms.trustMeType.tsym,
   715                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   716             }
   717         } else if (hasTrustMeAnno && varargElemType != null &&
   718                             types.isReifiable(varargElemType)) {
   719             warnUnsafeVararg(tree,
   720                             "varargs.redundant.trustme.anno",
   721                             syms.trustMeType.tsym,
   722                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   723         }
   724         else if (!hasTrustMeAnno && varargElemType != null &&
   725                 !types.isReifiable(varargElemType)) {
   726             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   727         }
   728     }
   729     //where
   730         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   731             return (s.flags() & VARARGS) != 0 &&
   732                 (s.isConstructor() ||
   733                     (s.flags() & (STATIC | FINAL)) != 0);
   734         }
   736     /**
   737      * Check that vararg method call is sound
   738      * @param pos Position to be used for error reporting.
   739      * @param argtypes Actual arguments supplied to vararg method.
   740      */
   741     void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
   742         Type argtype = argtypes.last();
   743         if (!types.isReifiable(argtype) &&
   744                 (!allowSimplifiedVarargs ||
   745                 msym.attribute(syms.trustMeType.tsym) == null ||
   746                 !isTrustMeAllowedOnMethod(msym))) {
   747             warnUnchecked(pos,
   748                               "unchecked.generic.array.creation",
   749                               argtype);
   750         }
   751     }
   753     /**
   754      * Check that type 't' is a valid instantiation of a generic class
   755      * (see JLS 4.5)
   756      *
   757      * @param t class type to be checked
   758      * @return true if 't' is well-formed
   759      */
   760     public boolean checkValidGenericType(Type t) {
   761         return firstIncompatibleTypeArg(t) == null;
   762     }
   763     //WHERE
   764         private Type firstIncompatibleTypeArg(Type type) {
   765             List<Type> formals = type.tsym.type.allparams();
   766             List<Type> actuals = type.allparams();
   767             List<Type> args = type.getTypeArguments();
   768             List<Type> forms = type.tsym.type.getTypeArguments();
   769             ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
   771             // For matching pairs of actual argument types `a' and
   772             // formal type parameters with declared bound `b' ...
   773             while (args.nonEmpty() && forms.nonEmpty()) {
   774                 // exact type arguments needs to know their
   775                 // bounds (for upper and lower bound
   776                 // calculations).  So we create new TypeVars with
   777                 // bounds substed with actuals.
   778                 tvars_buf.append(types.substBound(((TypeVar)forms.head),
   779                                                   formals,
   780                                                   actuals));
   781                 args = args.tail;
   782                 forms = forms.tail;
   783             }
   785             args = type.getTypeArguments();
   786             List<Type> tvars_cap = types.substBounds(formals,
   787                                       formals,
   788                                       types.capture(type).allparams());
   789             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   790                 // Let the actual arguments know their bound
   791                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   792                 args = args.tail;
   793                 tvars_cap = tvars_cap.tail;
   794             }
   796             args = type.getTypeArguments();
   797             List<Type> tvars = tvars_buf.toList();
   799             while (args.nonEmpty() && tvars.nonEmpty()) {
   800                 Type actual = types.subst(args.head,
   801                     type.tsym.type.getTypeArguments(),
   802                     tvars_buf.toList());
   803                 if (!checkExtends(actual, (TypeVar)tvars.head) &&
   804                         !tvars.head.getUpperBound().isErroneous()) {
   805                     return args.head;
   806                 }
   807                 args = args.tail;
   808                 tvars = tvars.tail;
   809             }
   811             args = type.getTypeArguments();
   812             tvars = tvars_buf.toList();
   814             for (Type arg : types.capture(type).getTypeArguments()) {
   815                 if (arg.tag == TYPEVAR &&
   816                         arg.getUpperBound().isErroneous() &&
   817                         !tvars.head.getUpperBound().isErroneous()) {
   818                     return args.head;
   819                 }
   820                 tvars = tvars.tail;
   821             }
   823             return null;
   824         }
   826     /** Check that given modifiers are legal for given symbol and
   827      *  return modifiers together with any implicit modififiers for that symbol.
   828      *  Warning: we can't use flags() here since this method
   829      *  is called during class enter, when flags() would cause a premature
   830      *  completion.
   831      *  @param pos           Position to be used for error reporting.
   832      *  @param flags         The set of modifiers given in a definition.
   833      *  @param sym           The defined symbol.
   834      */
   835     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   836         long mask;
   837         long implicit = 0;
   838         switch (sym.kind) {
   839         case VAR:
   840             if (sym.owner.kind != TYP)
   841                 mask = LocalVarFlags;
   842             else if ((sym.owner.flags_field & INTERFACE) != 0)
   843                 mask = implicit = InterfaceVarFlags;
   844             else
   845                 mask = VarFlags;
   846             break;
   847         case MTH:
   848             if (sym.name == names.init) {
   849                 if ((sym.owner.flags_field & ENUM) != 0) {
   850                     // enum constructors cannot be declared public or
   851                     // protected and must be implicitly or explicitly
   852                     // private
   853                     implicit = PRIVATE;
   854                     mask = PRIVATE;
   855                 } else
   856                     mask = ConstructorFlags;
   857             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   858                 mask = implicit = InterfaceMethodFlags;
   859             else {
   860                 mask = MethodFlags;
   861             }
   862             // Imply STRICTFP if owner has STRICTFP set.
   863             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   864               implicit |= sym.owner.flags_field & STRICTFP;
   865             break;
   866         case TYP:
   867             if (sym.isLocal()) {
   868                 mask = LocalClassFlags;
   869                 if (sym.name.isEmpty()) { // Anonymous class
   870                     // Anonymous classes in static methods are themselves static;
   871                     // that's why we admit STATIC here.
   872                     mask |= STATIC;
   873                     // JLS: Anonymous classes are final.
   874                     implicit |= FINAL;
   875                 }
   876                 if ((sym.owner.flags_field & STATIC) == 0 &&
   877                     (flags & ENUM) != 0)
   878                     log.error(pos, "enums.must.be.static");
   879             } else if (sym.owner.kind == TYP) {
   880                 mask = MemberClassFlags;
   881                 if (sym.owner.owner.kind == PCK ||
   882                     (sym.owner.flags_field & STATIC) != 0)
   883                     mask |= STATIC;
   884                 else if ((flags & ENUM) != 0)
   885                     log.error(pos, "enums.must.be.static");
   886                 // Nested interfaces and enums are always STATIC (Spec ???)
   887                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   888             } else {
   889                 mask = ClassFlags;
   890             }
   891             // Interfaces are always ABSTRACT
   892             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   894             if ((flags & ENUM) != 0) {
   895                 // enums can't be declared abstract or final
   896                 mask &= ~(ABSTRACT | FINAL);
   897                 implicit |= implicitEnumFinalFlag(tree);
   898             }
   899             // Imply STRICTFP if owner has STRICTFP set.
   900             implicit |= sym.owner.flags_field & STRICTFP;
   901             break;
   902         default:
   903             throw new AssertionError();
   904         }
   905         long illegal = flags & StandardFlags & ~mask;
   906         if (illegal != 0) {
   907             if ((illegal & INTERFACE) != 0) {
   908                 log.error(pos, "intf.not.allowed.here");
   909                 mask |= INTERFACE;
   910             }
   911             else {
   912                 log.error(pos,
   913                           "mod.not.allowed.here", asFlagSet(illegal));
   914             }
   915         }
   916         else if ((sym.kind == TYP ||
   917                   // ISSUE: Disallowing abstract&private is no longer appropriate
   918                   // in the presence of inner classes. Should it be deleted here?
   919                   checkDisjoint(pos, flags,
   920                                 ABSTRACT,
   921                                 PRIVATE | STATIC))
   922                  &&
   923                  checkDisjoint(pos, flags,
   924                                ABSTRACT | INTERFACE,
   925                                FINAL | NATIVE | SYNCHRONIZED)
   926                  &&
   927                  checkDisjoint(pos, flags,
   928                                PUBLIC,
   929                                PRIVATE | PROTECTED)
   930                  &&
   931                  checkDisjoint(pos, flags,
   932                                PRIVATE,
   933                                PUBLIC | PROTECTED)
   934                  &&
   935                  checkDisjoint(pos, flags,
   936                                FINAL,
   937                                VOLATILE)
   938                  &&
   939                  (sym.kind == TYP ||
   940                   checkDisjoint(pos, flags,
   941                                 ABSTRACT | NATIVE,
   942                                 STRICTFP))) {
   943             // skip
   944         }
   945         return flags & (mask | ~StandardFlags) | implicit;
   946     }
   949     /** Determine if this enum should be implicitly final.
   950      *
   951      *  If the enum has no specialized enum contants, it is final.
   952      *
   953      *  If the enum does have specialized enum contants, it is
   954      *  <i>not</i> final.
   955      */
   956     private long implicitEnumFinalFlag(JCTree tree) {
   957         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   958         class SpecialTreeVisitor extends JCTree.Visitor {
   959             boolean specialized;
   960             SpecialTreeVisitor() {
   961                 this.specialized = false;
   962             };
   964             @Override
   965             public void visitTree(JCTree tree) { /* no-op */ }
   967             @Override
   968             public void visitVarDef(JCVariableDecl tree) {
   969                 if ((tree.mods.flags & ENUM) != 0) {
   970                     if (tree.init instanceof JCNewClass &&
   971                         ((JCNewClass) tree.init).def != null) {
   972                         specialized = true;
   973                     }
   974                 }
   975             }
   976         }
   978         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   979         JCClassDecl cdef = (JCClassDecl) tree;
   980         for (JCTree defs: cdef.defs) {
   981             defs.accept(sts);
   982             if (sts.specialized) return 0;
   983         }
   984         return FINAL;
   985     }
   987 /* *************************************************************************
   988  * Type Validation
   989  **************************************************************************/
   991     /** Validate a type expression. That is,
   992      *  check that all type arguments of a parametric type are within
   993      *  their bounds. This must be done in a second phase after type attributon
   994      *  since a class might have a subclass as type parameter bound. E.g:
   995      *
   996      *  class B<A extends C> { ... }
   997      *  class C extends B<C> { ... }
   998      *
   999      *  and we can't make sure that the bound is already attributed because
  1000      *  of possible cycles.
  1002      * Visitor method: Validate a type expression, if it is not null, catching
  1003      *  and reporting any completion failures.
  1004      */
  1005     void validate(JCTree tree, Env<AttrContext> env) {
  1006         validate(tree, env, true);
  1008     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1009         new Validator(env).validateTree(tree, checkRaw, true);
  1012     /** Visitor method: Validate a list of type expressions.
  1013      */
  1014     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1015         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1016             validate(l.head, env);
  1019     /** A visitor class for type validation.
  1020      */
  1021     class Validator extends JCTree.Visitor {
  1023         boolean isOuter;
  1024         Env<AttrContext> env;
  1026         Validator(Env<AttrContext> env) {
  1027             this.env = env;
  1030         @Override
  1031         public void visitTypeArray(JCArrayTypeTree tree) {
  1032             tree.elemtype.accept(this);
  1035         @Override
  1036         public void visitTypeApply(JCTypeApply tree) {
  1037             if (tree.type.tag == CLASS) {
  1038                 List<JCExpression> args = tree.arguments;
  1039                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1041                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1042                 if (incompatibleArg != null) {
  1043                     for (JCTree arg : tree.arguments) {
  1044                         if (arg.type == incompatibleArg) {
  1045                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1047                         forms = forms.tail;
  1051                 forms = tree.type.tsym.type.getTypeArguments();
  1053                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1055                 // For matching pairs of actual argument types `a' and
  1056                 // formal type parameters with declared bound `b' ...
  1057                 while (args.nonEmpty() && forms.nonEmpty()) {
  1058                     validateTree(args.head,
  1059                             !(isOuter && is_java_lang_Class),
  1060                             false);
  1061                     args = args.tail;
  1062                     forms = forms.tail;
  1065                 // Check that this type is either fully parameterized, or
  1066                 // not parameterized at all.
  1067                 if (tree.type.getEnclosingType().isRaw())
  1068                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1069                 if (tree.clazz.getTag() == JCTree.SELECT)
  1070                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1074         @Override
  1075         public void visitTypeParameter(JCTypeParameter tree) {
  1076             validateTrees(tree.bounds, true, isOuter);
  1077             checkClassBounds(tree.pos(), tree.type);
  1080         @Override
  1081         public void visitWildcard(JCWildcard tree) {
  1082             if (tree.inner != null)
  1083                 validateTree(tree.inner, true, isOuter);
  1086         @Override
  1087         public void visitSelect(JCFieldAccess tree) {
  1088             if (tree.type.tag == CLASS) {
  1089                 visitSelectInternal(tree);
  1091                 // Check that this type is either fully parameterized, or
  1092                 // not parameterized at all.
  1093                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1094                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1097         public void visitSelectInternal(JCFieldAccess tree) {
  1098             if (tree.type.tsym.isStatic() &&
  1099                 tree.selected.type.isParameterized()) {
  1100                 // The enclosing type is not a class, so we are
  1101                 // looking at a static member type.  However, the
  1102                 // qualifying expression is parameterized.
  1103                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1104             } else {
  1105                 // otherwise validate the rest of the expression
  1106                 tree.selected.accept(this);
  1110         /** Default visitor method: do nothing.
  1111          */
  1112         @Override
  1113         public void visitTree(JCTree tree) {
  1116         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1117             try {
  1118                 if (tree != null) {
  1119                     this.isOuter = isOuter;
  1120                     tree.accept(this);
  1121                     if (checkRaw)
  1122                         checkRaw(tree, env);
  1124             } catch (CompletionFailure ex) {
  1125                 completionError(tree.pos(), ex);
  1129         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1130             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1131                 validateTree(l.head, checkRaw, isOuter);
  1134         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1135             if (lint.isEnabled(LintCategory.RAW) &&
  1136                 tree.type.tag == CLASS &&
  1137                 !TreeInfo.isDiamond(tree) &&
  1138                 !env.enclClass.name.isEmpty() &&  //anonymous or intersection
  1139                 tree.type.isRaw()) {
  1140                 log.warning(LintCategory.RAW,
  1141                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1146 /* *************************************************************************
  1147  * Exception checking
  1148  **************************************************************************/
  1150     /* The following methods treat classes as sets that contain
  1151      * the class itself and all their subclasses
  1152      */
  1154     /** Is given type a subtype of some of the types in given list?
  1155      */
  1156     boolean subset(Type t, List<Type> ts) {
  1157         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1158             if (types.isSubtype(t, l.head)) return true;
  1159         return false;
  1162     /** Is given type a subtype or supertype of
  1163      *  some of the types in given list?
  1164      */
  1165     boolean intersects(Type t, List<Type> ts) {
  1166         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1167             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1168         return false;
  1171     /** Add type set to given type list, unless it is a subclass of some class
  1172      *  in the list.
  1173      */
  1174     List<Type> incl(Type t, List<Type> ts) {
  1175         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1178     /** Remove type set from type set list.
  1179      */
  1180     List<Type> excl(Type t, List<Type> ts) {
  1181         if (ts.isEmpty()) {
  1182             return ts;
  1183         } else {
  1184             List<Type> ts1 = excl(t, ts.tail);
  1185             if (types.isSubtype(ts.head, t)) return ts1;
  1186             else if (ts1 == ts.tail) return ts;
  1187             else return ts1.prepend(ts.head);
  1191     /** Form the union of two type set lists.
  1192      */
  1193     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1194         List<Type> ts = ts1;
  1195         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1196             ts = incl(l.head, ts);
  1197         return ts;
  1200     /** Form the difference of two type lists.
  1201      */
  1202     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1203         List<Type> ts = ts1;
  1204         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1205             ts = excl(l.head, ts);
  1206         return ts;
  1209     /** Form the intersection of two type lists.
  1210      */
  1211     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1212         List<Type> ts = List.nil();
  1213         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1214             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1215         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1216             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1217         return ts;
  1220     /** Is exc an exception symbol that need not be declared?
  1221      */
  1222     boolean isUnchecked(ClassSymbol exc) {
  1223         return
  1224             exc.kind == ERR ||
  1225             exc.isSubClass(syms.errorType.tsym, types) ||
  1226             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1229     /** Is exc an exception type that need not be declared?
  1230      */
  1231     boolean isUnchecked(Type exc) {
  1232         return
  1233             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1234             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1235             exc.tag == BOT;
  1238     /** Same, but handling completion failures.
  1239      */
  1240     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1241         try {
  1242             return isUnchecked(exc);
  1243         } catch (CompletionFailure ex) {
  1244             completionError(pos, ex);
  1245             return true;
  1249     /** Is exc handled by given exception list?
  1250      */
  1251     boolean isHandled(Type exc, List<Type> handled) {
  1252         return isUnchecked(exc) || subset(exc, handled);
  1255     /** Return all exceptions in thrown list that are not in handled list.
  1256      *  @param thrown     The list of thrown exceptions.
  1257      *  @param handled    The list of handled exceptions.
  1258      */
  1259     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1260         List<Type> unhandled = List.nil();
  1261         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1262             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1263         return unhandled;
  1266 /* *************************************************************************
  1267  * Overriding/Implementation checking
  1268  **************************************************************************/
  1270     /** The level of access protection given by a flag set,
  1271      *  where PRIVATE is highest and PUBLIC is lowest.
  1272      */
  1273     static int protection(long flags) {
  1274         switch ((short)(flags & AccessFlags)) {
  1275         case PRIVATE: return 3;
  1276         case PROTECTED: return 1;
  1277         default:
  1278         case PUBLIC: return 0;
  1279         case 0: return 2;
  1283     /** A customized "cannot override" error message.
  1284      *  @param m      The overriding method.
  1285      *  @param other  The overridden method.
  1286      *  @return       An internationalized string.
  1287      */
  1288     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1289         String key;
  1290         if ((other.owner.flags() & INTERFACE) == 0)
  1291             key = "cant.override";
  1292         else if ((m.owner.flags() & INTERFACE) == 0)
  1293             key = "cant.implement";
  1294         else
  1295             key = "clashes.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 uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1305         String key;
  1306         if ((other.owner.flags() & INTERFACE) == 0)
  1307             key = "unchecked.override";
  1308         else if ((m.owner.flags() & INTERFACE) == 0)
  1309             key = "unchecked.implement";
  1310         else
  1311             key = "unchecked.clash.with";
  1312         return diags.fragment(key, m, m.location(), other, other.location());
  1315     /** A customized "override" warning message.
  1316      *  @param m      The overriding method.
  1317      *  @param other  The overridden method.
  1318      *  @return       An internationalized string.
  1319      */
  1320     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1321         String key;
  1322         if ((other.owner.flags() & INTERFACE) == 0)
  1323             key = "varargs.override";
  1324         else  if ((m.owner.flags() & INTERFACE) == 0)
  1325             key = "varargs.implement";
  1326         else
  1327             key = "varargs.clash.with";
  1328         return diags.fragment(key, m, m.location(), other, other.location());
  1331     /** Check that this method conforms with overridden method 'other'.
  1332      *  where `origin' is the class where checking started.
  1333      *  Complications:
  1334      *  (1) Do not check overriding of synthetic methods
  1335      *      (reason: they might be final).
  1336      *      todo: check whether this is still necessary.
  1337      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1338      *      than the method it implements. Augment the proxy methods with the
  1339      *      undeclared exceptions in this case.
  1340      *  (3) When generics are enabled, admit the case where an interface proxy
  1341      *      has a result type
  1342      *      extended by the result type of the method it implements.
  1343      *      Change the proxies result type to the smaller type in this case.
  1345      *  @param tree         The tree from which positions
  1346      *                      are extracted for errors.
  1347      *  @param m            The overriding method.
  1348      *  @param other        The overridden method.
  1349      *  @param origin       The class of which the overriding method
  1350      *                      is a member.
  1351      */
  1352     void checkOverride(JCTree tree,
  1353                        MethodSymbol m,
  1354                        MethodSymbol other,
  1355                        ClassSymbol origin) {
  1356         // Don't check overriding of synthetic methods or by bridge methods.
  1357         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1358             return;
  1361         // Error if static method overrides instance method (JLS 8.4.6.2).
  1362         if ((m.flags() & STATIC) != 0 &&
  1363                    (other.flags() & STATIC) == 0) {
  1364             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1365                       cannotOverride(m, other));
  1366             return;
  1369         // Error if instance method overrides static or final
  1370         // method (JLS 8.4.6.1).
  1371         if ((other.flags() & FINAL) != 0 ||
  1372                  (m.flags() & STATIC) == 0 &&
  1373                  (other.flags() & STATIC) != 0) {
  1374             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1375                       cannotOverride(m, other),
  1376                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1377             return;
  1380         if ((m.owner.flags() & ANNOTATION) != 0) {
  1381             // handled in validateAnnotationMethod
  1382             return;
  1385         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1386         if ((origin.flags() & INTERFACE) == 0 &&
  1387                  protection(m.flags()) > protection(other.flags())) {
  1388             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1389                       cannotOverride(m, other),
  1390                       other.flags() == 0 ?
  1391                           Flag.PACKAGE :
  1392                           asFlagSet(other.flags() & AccessFlags));
  1393             return;
  1396         Type mt = types.memberType(origin.type, m);
  1397         Type ot = types.memberType(origin.type, other);
  1398         // Error if overriding result type is different
  1399         // (or, in the case of generics mode, not a subtype) of
  1400         // overridden result type. We have to rename any type parameters
  1401         // before comparing types.
  1402         List<Type> mtvars = mt.getTypeArguments();
  1403         List<Type> otvars = ot.getTypeArguments();
  1404         Type mtres = mt.getReturnType();
  1405         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1407         overrideWarner.clear();
  1408         boolean resultTypesOK =
  1409             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1410         if (!resultTypesOK) {
  1411             if (!allowCovariantReturns &&
  1412                 m.owner != origin &&
  1413                 m.owner.isSubClass(other.owner, types)) {
  1414                 // allow limited interoperability with covariant returns
  1415             } else {
  1416                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1417                           "override.incompatible.ret",
  1418                           cannotOverride(m, other),
  1419                           mtres, otres);
  1420                 return;
  1422         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1423             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1424                     "override.unchecked.ret",
  1425                     uncheckedOverrides(m, other),
  1426                     mtres, otres);
  1429         // Error if overriding method throws an exception not reported
  1430         // by overridden method.
  1431         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1432         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1433         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1434         if (unhandledErased.nonEmpty()) {
  1435             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1436                       "override.meth.doesnt.throw",
  1437                       cannotOverride(m, other),
  1438                       unhandledUnerased.head);
  1439             return;
  1441         else if (unhandledUnerased.nonEmpty()) {
  1442             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1443                           "override.unchecked.thrown",
  1444                          cannotOverride(m, other),
  1445                          unhandledUnerased.head);
  1446             return;
  1449         // Optional warning if varargs don't agree
  1450         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1451             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1452             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1453                         ((m.flags() & Flags.VARARGS) != 0)
  1454                         ? "override.varargs.missing"
  1455                         : "override.varargs.extra",
  1456                         varargsOverrides(m, other));
  1459         // Warn if instance method overrides bridge method (compiler spec ??)
  1460         if ((other.flags() & BRIDGE) != 0) {
  1461             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1462                         uncheckedOverrides(m, other));
  1465         // Warn if a deprecated method overridden by a non-deprecated one.
  1466         if ((other.flags() & DEPRECATED) != 0
  1467             && (m.flags() & DEPRECATED) == 0
  1468             && m.outermostClass() != other.outermostClass()
  1469             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1470             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1473     // where
  1474         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1475             // If the method, m, is defined in an interface, then ignore the issue if the method
  1476             // is only inherited via a supertype and also implemented in the supertype,
  1477             // because in that case, we will rediscover the issue when examining the method
  1478             // in the supertype.
  1479             // If the method, m, is not defined in an interface, then the only time we need to
  1480             // address the issue is when the method is the supertype implemementation: any other
  1481             // case, we will have dealt with when examining the supertype classes
  1482             ClassSymbol mc = m.enclClass();
  1483             Type st = types.supertype(origin.type);
  1484             if (st.tag != CLASS)
  1485                 return true;
  1486             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1488             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1489                 List<Type> intfs = types.interfaces(origin.type);
  1490                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1492             else
  1493                 return (stimpl != m);
  1497     // used to check if there were any unchecked conversions
  1498     Warner overrideWarner = new Warner();
  1500     /** Check that a class does not inherit two concrete methods
  1501      *  with the same signature.
  1502      *  @param pos          Position to be used for error reporting.
  1503      *  @param site         The class type to be checked.
  1504      */
  1505     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1506         Type sup = types.supertype(site);
  1507         if (sup.tag != CLASS) return;
  1509         for (Type t1 = sup;
  1510              t1.tsym.type.isParameterized();
  1511              t1 = types.supertype(t1)) {
  1512             for (Scope.Entry e1 = t1.tsym.members().elems;
  1513                  e1 != null;
  1514                  e1 = e1.sibling) {
  1515                 Symbol s1 = e1.sym;
  1516                 if (s1.kind != MTH ||
  1517                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1518                     !s1.isInheritedIn(site.tsym, types) ||
  1519                     ((MethodSymbol)s1).implementation(site.tsym,
  1520                                                       types,
  1521                                                       true) != s1)
  1522                     continue;
  1523                 Type st1 = types.memberType(t1, s1);
  1524                 int s1ArgsLength = st1.getParameterTypes().length();
  1525                 if (st1 == s1.type) continue;
  1527                 for (Type t2 = sup;
  1528                      t2.tag == CLASS;
  1529                      t2 = types.supertype(t2)) {
  1530                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1531                          e2.scope != null;
  1532                          e2 = e2.next()) {
  1533                         Symbol s2 = e2.sym;
  1534                         if (s2 == s1 ||
  1535                             s2.kind != MTH ||
  1536                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1537                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1538                             !s2.isInheritedIn(site.tsym, types) ||
  1539                             ((MethodSymbol)s2).implementation(site.tsym,
  1540                                                               types,
  1541                                                               true) != s2)
  1542                             continue;
  1543                         Type st2 = types.memberType(t2, s2);
  1544                         if (types.overrideEquivalent(st1, st2))
  1545                             log.error(pos, "concrete.inheritance.conflict",
  1546                                       s1, t1, s2, t2, sup);
  1553     /** Check that classes (or interfaces) do not each define an abstract
  1554      *  method with same name and arguments but incompatible return types.
  1555      *  @param pos          Position to be used for error reporting.
  1556      *  @param t1           The first argument type.
  1557      *  @param t2           The second argument type.
  1558      */
  1559     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1560                                             Type t1,
  1561                                             Type t2) {
  1562         return checkCompatibleAbstracts(pos, t1, t2,
  1563                                         types.makeCompoundType(t1, t2));
  1566     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1567                                             Type t1,
  1568                                             Type t2,
  1569                                             Type site) {
  1570         return firstIncompatibility(pos, t1, t2, site) == null;
  1573     /** Return the first method which is defined with same args
  1574      *  but different return types in two given interfaces, or null if none
  1575      *  exists.
  1576      *  @param t1     The first type.
  1577      *  @param t2     The second type.
  1578      *  @param site   The most derived type.
  1579      *  @returns symbol from t2 that conflicts with one in t1.
  1580      */
  1581     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1582         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1583         closure(t1, interfaces1);
  1584         Map<TypeSymbol,Type> interfaces2;
  1585         if (t1 == t2)
  1586             interfaces2 = interfaces1;
  1587         else
  1588             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1590         for (Type t3 : interfaces1.values()) {
  1591             for (Type t4 : interfaces2.values()) {
  1592                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1593                 if (s != null) return s;
  1596         return null;
  1599     /** Compute all the supertypes of t, indexed by type symbol. */
  1600     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1601         if (t.tag != CLASS) return;
  1602         if (typeMap.put(t.tsym, t) == null) {
  1603             closure(types.supertype(t), typeMap);
  1604             for (Type i : types.interfaces(t))
  1605                 closure(i, typeMap);
  1609     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1610     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1611         if (t.tag != CLASS) return;
  1612         if (typesSkip.get(t.tsym) != null) return;
  1613         if (typeMap.put(t.tsym, t) == null) {
  1614             closure(types.supertype(t), typesSkip, typeMap);
  1615             for (Type i : types.interfaces(t))
  1616                 closure(i, typesSkip, typeMap);
  1620     /** Return the first method in t2 that conflicts with a method from t1. */
  1621     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1622         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1623             Symbol s1 = e1.sym;
  1624             Type st1 = null;
  1625             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1626             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1627             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1628             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1629                 Symbol s2 = e2.sym;
  1630                 if (s1 == s2) continue;
  1631                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1632                 if (st1 == null) st1 = types.memberType(t1, s1);
  1633                 Type st2 = types.memberType(t2, s2);
  1634                 if (types.overrideEquivalent(st1, st2)) {
  1635                     List<Type> tvars1 = st1.getTypeArguments();
  1636                     List<Type> tvars2 = st2.getTypeArguments();
  1637                     Type rt1 = st1.getReturnType();
  1638                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1639                     boolean compat =
  1640                         types.isSameType(rt1, rt2) ||
  1641                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1642                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1643                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1644                          checkCommonOverriderIn(s1,s2,site);
  1645                     if (!compat) {
  1646                         log.error(pos, "types.incompatible.diff.ret",
  1647                             t1, t2, s2.name +
  1648                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1649                         return s2;
  1651                 } else if (!checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
  1652                     log.error(pos,
  1653                             "name.clash.same.erasure.no.override",
  1654                             s1, s1.location(),
  1655                             s2, s2.location());
  1656                     return s2;
  1660         return null;
  1662     //WHERE
  1663     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1664         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1665         Type st1 = types.memberType(site, s1);
  1666         Type st2 = types.memberType(site, s2);
  1667         closure(site, supertypes);
  1668         for (Type t : supertypes.values()) {
  1669             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1670                 Symbol s3 = e.sym;
  1671                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1672                 Type st3 = types.memberType(site,s3);
  1673                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1674                     if (s3.owner == site.tsym) {
  1675                         return true;
  1677                     List<Type> tvars1 = st1.getTypeArguments();
  1678                     List<Type> tvars2 = st2.getTypeArguments();
  1679                     List<Type> tvars3 = st3.getTypeArguments();
  1680                     Type rt1 = st1.getReturnType();
  1681                     Type rt2 = st2.getReturnType();
  1682                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1683                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1684                     boolean compat =
  1685                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1686                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1687                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1688                     if (compat)
  1689                         return true;
  1693         return false;
  1696     /** Check that a given method conforms with any method it overrides.
  1697      *  @param tree         The tree from which positions are extracted
  1698      *                      for errors.
  1699      *  @param m            The overriding method.
  1700      */
  1701     void checkOverride(JCTree tree, MethodSymbol m) {
  1702         ClassSymbol origin = (ClassSymbol)m.owner;
  1703         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1704             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1705                 log.error(tree.pos(), "enum.no.finalize");
  1706                 return;
  1708         for (Type t = origin.type; t.tag == CLASS;
  1709              t = types.supertype(t)) {
  1710             if (t != origin.type) {
  1711                 checkOverride(tree, t, origin, m);
  1713             for (Type t2 : types.interfaces(t)) {
  1714                 checkOverride(tree, t2, origin, m);
  1719     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1720         TypeSymbol c = site.tsym;
  1721         Scope.Entry e = c.members().lookup(m.name);
  1722         while (e.scope != null) {
  1723             if (m.overrides(e.sym, origin, types, false)) {
  1724                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1725                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1728             e = e.next();
  1732     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1733         if (s1.kind == MTH &&
  1734                     s1.isInheritedIn(origin, types) &&
  1735                     (s1.flags() & SYNTHETIC) == 0 &&
  1736                     !s2.isConstructor()) {
  1737             Type er1 = s2.erasure(types);
  1738             Type er2 = s1.erasure(types);
  1739             if (types.isSameTypes(er1.getParameterTypes(),
  1740                     er2.getParameterTypes())) {
  1741                     return false;
  1744         return true;
  1748     /** Check that all abstract members of given class have definitions.
  1749      *  @param pos          Position to be used for error reporting.
  1750      *  @param c            The class.
  1751      */
  1752     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1753         try {
  1754             MethodSymbol undef = firstUndef(c, c);
  1755             if (undef != null) {
  1756                 if ((c.flags() & ENUM) != 0 &&
  1757                     types.supertype(c.type).tsym == syms.enumSym &&
  1758                     (c.flags() & FINAL) == 0) {
  1759                     // add the ABSTRACT flag to an enum
  1760                     c.flags_field |= ABSTRACT;
  1761                 } else {
  1762                     MethodSymbol undef1 =
  1763                         new MethodSymbol(undef.flags(), undef.name,
  1764                                          types.memberType(c.type, undef), undef.owner);
  1765                     log.error(pos, "does.not.override.abstract",
  1766                               c, undef1, undef1.location());
  1769         } catch (CompletionFailure ex) {
  1770             completionError(pos, ex);
  1773 //where
  1774         /** Return first abstract member of class `c' that is not defined
  1775          *  in `impl', null if there is none.
  1776          */
  1777         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1778             MethodSymbol undef = null;
  1779             // Do not bother to search in classes that are not abstract,
  1780             // since they cannot have abstract members.
  1781             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1782                 Scope s = c.members();
  1783                 for (Scope.Entry e = s.elems;
  1784                      undef == null && e != null;
  1785                      e = e.sibling) {
  1786                     if (e.sym.kind == MTH &&
  1787                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1788                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1789                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1790                         if (implmeth == null || implmeth == absmeth)
  1791                             undef = absmeth;
  1794                 if (undef == null) {
  1795                     Type st = types.supertype(c.type);
  1796                     if (st.tag == CLASS)
  1797                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1799                 for (List<Type> l = types.interfaces(c.type);
  1800                      undef == null && l.nonEmpty();
  1801                      l = l.tail) {
  1802                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1805             return undef;
  1808     void checkNonCyclicDecl(JCClassDecl tree) {
  1809         CycleChecker cc = new CycleChecker();
  1810         cc.scan(tree);
  1811         if (!cc.errorFound && !cc.partialCheck) {
  1812             tree.sym.flags_field |= ACYCLIC;
  1816     class CycleChecker extends TreeScanner {
  1818         List<Symbol> seenClasses = List.nil();
  1819         boolean errorFound = false;
  1820         boolean partialCheck = false;
  1822         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  1823             if (sym != null && sym.kind == TYP) {
  1824                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  1825                 if (classEnv != null) {
  1826                     DiagnosticSource prevSource = log.currentSource();
  1827                     try {
  1828                         log.useSource(classEnv.toplevel.sourcefile);
  1829                         scan(classEnv.tree);
  1831                     finally {
  1832                         log.useSource(prevSource.getFile());
  1834                 } else if (sym.kind == TYP) {
  1835                     checkClass(pos, sym, List.<JCTree>nil());
  1837             } else {
  1838                 //not completed yet
  1839                 partialCheck = true;
  1843         @Override
  1844         public void visitSelect(JCFieldAccess tree) {
  1845             super.visitSelect(tree);
  1846             checkSymbol(tree.pos(), tree.sym);
  1849         @Override
  1850         public void visitIdent(JCIdent tree) {
  1851             checkSymbol(tree.pos(), tree.sym);
  1854         @Override
  1855         public void visitTypeApply(JCTypeApply tree) {
  1856             scan(tree.clazz);
  1859         @Override
  1860         public void visitTypeArray(JCArrayTypeTree tree) {
  1861             scan(tree.elemtype);
  1864         @Override
  1865         public void visitClassDef(JCClassDecl tree) {
  1866             List<JCTree> supertypes = List.nil();
  1867             if (tree.getExtendsClause() != null) {
  1868                 supertypes = supertypes.prepend(tree.getExtendsClause());
  1870             if (tree.getImplementsClause() != null) {
  1871                 for (JCTree intf : tree.getImplementsClause()) {
  1872                     supertypes = supertypes.prepend(intf);
  1875             checkClass(tree.pos(), tree.sym, supertypes);
  1878         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  1879             if ((c.flags_field & ACYCLIC) != 0)
  1880                 return;
  1881             if (seenClasses.contains(c)) {
  1882                 errorFound = true;
  1883                 noteCyclic(pos, (ClassSymbol)c);
  1884             } else if (!c.type.isErroneous()) {
  1885                 try {
  1886                     seenClasses = seenClasses.prepend(c);
  1887                     if (c.type.tag == CLASS) {
  1888                         if (supertypes.nonEmpty()) {
  1889                             scan(supertypes);
  1891                         else {
  1892                             ClassType ct = (ClassType)c.type;
  1893                             if (ct.supertype_field == null ||
  1894                                     ct.interfaces_field == null) {
  1895                                 //not completed yet
  1896                                 partialCheck = true;
  1897                                 return;
  1899                             checkSymbol(pos, ct.supertype_field.tsym);
  1900                             for (Type intf : ct.interfaces_field) {
  1901                                 checkSymbol(pos, intf.tsym);
  1904                         if (c.owner.kind == TYP) {
  1905                             checkSymbol(pos, c.owner);
  1908                 } finally {
  1909                     seenClasses = seenClasses.tail;
  1915     /** Check for cyclic references. Issue an error if the
  1916      *  symbol of the type referred to has a LOCKED flag set.
  1918      *  @param pos      Position to be used for error reporting.
  1919      *  @param t        The type referred to.
  1920      */
  1921     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1922         checkNonCyclicInternal(pos, t);
  1926     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1927         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1930     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1931         final TypeVar tv;
  1932         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1933             return;
  1934         if (seen.contains(t)) {
  1935             tv = (TypeVar)t;
  1936             tv.bound = types.createErrorType(t);
  1937             log.error(pos, "cyclic.inheritance", t);
  1938         } else if (t.tag == TYPEVAR) {
  1939             tv = (TypeVar)t;
  1940             seen = seen.prepend(tv);
  1941             for (Type b : types.getBounds(tv))
  1942                 checkNonCyclic1(pos, b, seen);
  1946     /** Check for cyclic references. Issue an error if the
  1947      *  symbol of the type referred to has a LOCKED flag set.
  1949      *  @param pos      Position to be used for error reporting.
  1950      *  @param t        The type referred to.
  1951      *  @returns        True if the check completed on all attributed classes
  1952      */
  1953     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1954         boolean complete = true; // was the check complete?
  1955         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1956         Symbol c = t.tsym;
  1957         if ((c.flags_field & ACYCLIC) != 0) return true;
  1959         if ((c.flags_field & LOCKED) != 0) {
  1960             noteCyclic(pos, (ClassSymbol)c);
  1961         } else if (!c.type.isErroneous()) {
  1962             try {
  1963                 c.flags_field |= LOCKED;
  1964                 if (c.type.tag == CLASS) {
  1965                     ClassType clazz = (ClassType)c.type;
  1966                     if (clazz.interfaces_field != null)
  1967                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1968                             complete &= checkNonCyclicInternal(pos, l.head);
  1969                     if (clazz.supertype_field != null) {
  1970                         Type st = clazz.supertype_field;
  1971                         if (st != null && st.tag == CLASS)
  1972                             complete &= checkNonCyclicInternal(pos, st);
  1974                     if (c.owner.kind == TYP)
  1975                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1977             } finally {
  1978                 c.flags_field &= ~LOCKED;
  1981         if (complete)
  1982             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1983         if (complete) c.flags_field |= ACYCLIC;
  1984         return complete;
  1987     /** Note that we found an inheritance cycle. */
  1988     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1989         log.error(pos, "cyclic.inheritance", c);
  1990         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1991             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  1992         Type st = types.supertype(c.type);
  1993         if (st.tag == CLASS)
  1994             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  1995         c.type = types.createErrorType(c, c.type);
  1996         c.flags_field |= ACYCLIC;
  1999     /** Check that all methods which implement some
  2000      *  method conform to the method they implement.
  2001      *  @param tree         The class definition whose members are checked.
  2002      */
  2003     void checkImplementations(JCClassDecl tree) {
  2004         checkImplementations(tree, tree.sym);
  2006 //where
  2007         /** Check that all methods which implement some
  2008          *  method in `ic' conform to the method they implement.
  2009          */
  2010         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  2011             ClassSymbol origin = tree.sym;
  2012             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2013                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2014                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2015                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2016                         if (e.sym.kind == MTH &&
  2017                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2018                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2019                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2020                             if (implmeth != null && implmeth != absmeth &&
  2021                                 (implmeth.owner.flags() & INTERFACE) ==
  2022                                 (origin.flags() & INTERFACE)) {
  2023                                 // don't check if implmeth is in a class, yet
  2024                                 // origin is an interface. This case arises only
  2025                                 // if implmeth is declared in Object. The reason is
  2026                                 // that interfaces really don't inherit from
  2027                                 // Object it's just that the compiler represents
  2028                                 // things that way.
  2029                                 checkOverride(tree, implmeth, absmeth, origin);
  2037     /** Check that all abstract methods implemented by a class are
  2038      *  mutually compatible.
  2039      *  @param pos          Position to be used for error reporting.
  2040      *  @param c            The class whose interfaces are checked.
  2041      */
  2042     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2043         List<Type> supertypes = types.interfaces(c);
  2044         Type supertype = types.supertype(c);
  2045         if (supertype.tag == CLASS &&
  2046             (supertype.tsym.flags() & ABSTRACT) != 0)
  2047             supertypes = supertypes.prepend(supertype);
  2048         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2049             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2050                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2051                 return;
  2052             for (List<Type> m = supertypes; m != l; m = m.tail)
  2053                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2054                     return;
  2056         checkCompatibleConcretes(pos, c);
  2059     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2060         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2061             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2062                 // VM allows methods and variables with differing types
  2063                 if (sym.kind == e.sym.kind &&
  2064                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2065                     sym != e.sym &&
  2066                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2067                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2068                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2069                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2070                     return;
  2076     /** Check that all non-override equivalent methods accessible from 'site'
  2077      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2079      *  @param pos  Position to be used for error reporting.
  2080      *  @param site The class whose methods are checked.
  2081      *  @param sym  The method symbol to be checked.
  2082      */
  2083     void checkClashes(DiagnosticPosition pos, Type site, Symbol sym) {
  2084         List<Type> supertypes = types.closure(site);
  2085         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2086             for (List<Type> m = supertypes; m.nonEmpty(); m = m.tail) {
  2087                 checkClashes(pos, l.head, m.head, site, sym);
  2092     /** Reports an error whenever 'sym' seen as a member of type 't1' clashes with
  2093      *  some unrelated method defined in 't2'.
  2094      */
  2095     private void checkClashes(DiagnosticPosition pos, Type t1, Type t2, Type site, Symbol s1) {
  2096         ClashFilter cf = new ClashFilter(site);
  2097         s1 = ((MethodSymbol)s1).implementedIn(t1.tsym, types);
  2098         if (s1 == null) return;
  2099         Type st1 = types.memberType(site, s1);
  2100         for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name, cf); e2.scope != null; e2 = e2.next(cf)) {
  2101             Symbol s2 = e2.sym;
  2102             if (s1 == s2) continue;
  2103             Type st2 = types.memberType(site, s2);
  2104             if (!types.overrideEquivalent(st1, st2) &&
  2105                     !checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
  2106                 log.error(pos,
  2107                         "name.clash.same.erasure.no.override",
  2108                         s1, s1.location(),
  2109                         s2, s2.location());
  2113     //where
  2114     private class ClashFilter implements Filter<Symbol> {
  2116         Type site;
  2118         ClashFilter(Type site) {
  2119             this.site = site;
  2122         public boolean accepts(Symbol s) {
  2123             return s.kind == MTH &&
  2124                     (s.flags() & SYNTHETIC) == 0 &&
  2125                     s.isInheritedIn(site.tsym, types) &&
  2126                     !s.isConstructor();
  2130     /** Report a conflict between a user symbol and a synthetic symbol.
  2131      */
  2132     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2133         if (!sym.type.isErroneous()) {
  2134             if (warnOnSyntheticConflicts) {
  2135                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2137             else {
  2138                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2143     /** Check that class c does not implement directly or indirectly
  2144      *  the same parameterized interface with two different argument lists.
  2145      *  @param pos          Position to be used for error reporting.
  2146      *  @param type         The type whose interfaces are checked.
  2147      */
  2148     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2149         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2151 //where
  2152         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2153          *  with their class symbol as key and their type as value. Make
  2154          *  sure no class is entered with two different types.
  2155          */
  2156         void checkClassBounds(DiagnosticPosition pos,
  2157                               Map<TypeSymbol,Type> seensofar,
  2158                               Type type) {
  2159             if (type.isErroneous()) return;
  2160             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2161                 Type it = l.head;
  2162                 Type oldit = seensofar.put(it.tsym, it);
  2163                 if (oldit != null) {
  2164                     List<Type> oldparams = oldit.allparams();
  2165                     List<Type> newparams = it.allparams();
  2166                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2167                         log.error(pos, "cant.inherit.diff.arg",
  2168                                   it.tsym, Type.toString(oldparams),
  2169                                   Type.toString(newparams));
  2171                 checkClassBounds(pos, seensofar, it);
  2173             Type st = types.supertype(type);
  2174             if (st != null) checkClassBounds(pos, seensofar, st);
  2177     /** Enter interface into into set.
  2178      *  If it existed already, issue a "repeated interface" error.
  2179      */
  2180     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2181         if (its.contains(it))
  2182             log.error(pos, "repeated.interface");
  2183         else {
  2184             its.add(it);
  2188 /* *************************************************************************
  2189  * Check annotations
  2190  **************************************************************************/
  2192     /**
  2193      * Recursively validate annotations values
  2194      */
  2195     void validateAnnotationTree(JCTree tree) {
  2196         class AnnotationValidator extends TreeScanner {
  2197             @Override
  2198             public void visitAnnotation(JCAnnotation tree) {
  2199                 super.visitAnnotation(tree);
  2200                 validateAnnotation(tree);
  2203         tree.accept(new AnnotationValidator());
  2206     /** Annotation types are restricted to primitives, String, an
  2207      *  enum, an annotation, Class, Class<?>, Class<? extends
  2208      *  Anything>, arrays of the preceding.
  2209      */
  2210     void validateAnnotationType(JCTree restype) {
  2211         // restype may be null if an error occurred, so don't bother validating it
  2212         if (restype != null) {
  2213             validateAnnotationType(restype.pos(), restype.type);
  2217     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2218         if (type.isPrimitive()) return;
  2219         if (types.isSameType(type, syms.stringType)) return;
  2220         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2221         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2222         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2223         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2224             validateAnnotationType(pos, types.elemtype(type));
  2225             return;
  2227         log.error(pos, "invalid.annotation.member.type");
  2230     /**
  2231      * "It is also a compile-time error if any method declared in an
  2232      * annotation type has a signature that is override-equivalent to
  2233      * that of any public or protected method declared in class Object
  2234      * or in the interface annotation.Annotation."
  2236      * @jls3 9.6 Annotation Types
  2237      */
  2238     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2239         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2240             Scope s = sup.tsym.members();
  2241             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2242                 if (e.sym.kind == MTH &&
  2243                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2244                     types.overrideEquivalent(m.type, e.sym.type))
  2245                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2250     /** Check the annotations of a symbol.
  2251      */
  2252     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2253         if (skipAnnotations) return;
  2254         for (JCAnnotation a : annotations)
  2255             validateAnnotation(a, s);
  2258     /** Check an annotation of a symbol.
  2259      */
  2260     public void validateAnnotation(JCAnnotation a, Symbol s) {
  2261         validateAnnotationTree(a);
  2263         if (!annotationApplicable(a, s))
  2264             log.error(a.pos(), "annotation.type.not.applicable");
  2266         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2267             if (!isOverrider(s))
  2268                 log.error(a.pos(), "method.does.not.override.superclass");
  2272     /** Is s a method symbol that overrides a method in a superclass? */
  2273     boolean isOverrider(Symbol s) {
  2274         if (s.kind != MTH || s.isStatic())
  2275             return false;
  2276         MethodSymbol m = (MethodSymbol)s;
  2277         TypeSymbol owner = (TypeSymbol)m.owner;
  2278         for (Type sup : types.closure(owner.type)) {
  2279             if (sup == owner.type)
  2280                 continue; // skip "this"
  2281             Scope scope = sup.tsym.members();
  2282             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2283                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2284                     return true;
  2287         return false;
  2290     /** Is the annotation applicable to the symbol? */
  2291     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2292         Attribute.Compound atTarget =
  2293             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2294         if (atTarget == null) return true;
  2295         Attribute atValue = atTarget.member(names.value);
  2296         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2297         Attribute.Array arr = (Attribute.Array) atValue;
  2298         for (Attribute app : arr.values) {
  2299             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2300             Attribute.Enum e = (Attribute.Enum) app;
  2301             if (e.value.name == names.TYPE)
  2302                 { if (s.kind == TYP) return true; }
  2303             else if (e.value.name == names.FIELD)
  2304                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2305             else if (e.value.name == names.METHOD)
  2306                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2307             else if (e.value.name == names.PARAMETER)
  2308                 { if (s.kind == VAR &&
  2309                       s.owner.kind == MTH &&
  2310                       (s.flags() & PARAMETER) != 0)
  2311                     return true;
  2313             else if (e.value.name == names.CONSTRUCTOR)
  2314                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2315             else if (e.value.name == names.LOCAL_VARIABLE)
  2316                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2317                       (s.flags() & PARAMETER) == 0)
  2318                     return true;
  2320             else if (e.value.name == names.ANNOTATION_TYPE)
  2321                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2322                     return true;
  2324             else if (e.value.name == names.PACKAGE)
  2325                 { if (s.kind == PCK) return true; }
  2326             else if (e.value.name == names.TYPE_USE)
  2327                 { if (s.kind == TYP ||
  2328                       s.kind == VAR ||
  2329                       (s.kind == MTH && !s.isConstructor() &&
  2330                        s.type.getReturnType().tag != VOID))
  2331                     return true;
  2333             else
  2334                 return true; // recovery
  2336         return false;
  2339     /** Check an annotation value.
  2340      */
  2341     public void validateAnnotation(JCAnnotation a) {
  2342         if (a.type.isErroneous()) return;
  2344         // collect an inventory of the members (sorted alphabetically)
  2345         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2346             public int compare(Symbol t, Symbol t1) {
  2347                 return t.name.compareTo(t1.name);
  2349         });
  2350         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2351              e != null;
  2352              e = e.sibling)
  2353             if (e.sym.kind == MTH)
  2354                 members.add((MethodSymbol) e.sym);
  2356         // count them off as they're annotated
  2357         for (JCTree arg : a.args) {
  2358             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  2359             JCAssign assign = (JCAssign) arg;
  2360             Symbol m = TreeInfo.symbol(assign.lhs);
  2361             if (m == null || m.type.isErroneous()) continue;
  2362             if (!members.remove(m))
  2363                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2364                           m.name, a.type);
  2367         // all the remaining ones better have default values
  2368         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2369         for (MethodSymbol m : members) {
  2370             if (m.defaultValue == null && !m.type.isErroneous()) {
  2371                 missingDefaults.append(m.name);
  2374         if (missingDefaults.nonEmpty()) {
  2375             String key = (missingDefaults.size() > 1)
  2376                     ? "annotation.missing.default.value.1"
  2377                     : "annotation.missing.default.value";
  2378             log.error(a.pos(), key, a.type, missingDefaults);
  2381         // special case: java.lang.annotation.Target must not have
  2382         // repeated values in its value member
  2383         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2384             a.args.tail == null)
  2385             return;
  2387         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  2388         JCAssign assign = (JCAssign) a.args.head;
  2389         Symbol m = TreeInfo.symbol(assign.lhs);
  2390         if (m.name != names.value) return;
  2391         JCTree rhs = assign.rhs;
  2392         if (rhs.getTag() != JCTree.NEWARRAY) return;
  2393         JCNewArray na = (JCNewArray) rhs;
  2394         Set<Symbol> targets = new HashSet<Symbol>();
  2395         for (JCTree elem : na.elems) {
  2396             if (!targets.add(TreeInfo.symbol(elem))) {
  2397                 log.error(elem.pos(), "repeated.annotation.target");
  2402     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2403         if (allowAnnotations &&
  2404             lint.isEnabled(LintCategory.DEP_ANN) &&
  2405             (s.flags() & DEPRECATED) != 0 &&
  2406             !syms.deprecatedType.isErroneous() &&
  2407             s.attribute(syms.deprecatedType.tsym) == null) {
  2408             log.warning(LintCategory.DEP_ANN,
  2409                     pos, "missing.deprecated.annotation");
  2413 /* *************************************************************************
  2414  * Check for recursive annotation elements.
  2415  **************************************************************************/
  2417     /** Check for cycles in the graph of annotation elements.
  2418      */
  2419     void checkNonCyclicElements(JCClassDecl tree) {
  2420         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2421         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2422         try {
  2423             tree.sym.flags_field |= LOCKED;
  2424             for (JCTree def : tree.defs) {
  2425                 if (def.getTag() != JCTree.METHODDEF) continue;
  2426                 JCMethodDecl meth = (JCMethodDecl)def;
  2427                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2429         } finally {
  2430             tree.sym.flags_field &= ~LOCKED;
  2431             tree.sym.flags_field |= ACYCLIC_ANN;
  2435     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2436         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2437             return;
  2438         if ((tsym.flags_field & LOCKED) != 0) {
  2439             log.error(pos, "cyclic.annotation.element");
  2440             return;
  2442         try {
  2443             tsym.flags_field |= LOCKED;
  2444             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2445                 Symbol s = e.sym;
  2446                 if (s.kind != Kinds.MTH)
  2447                     continue;
  2448                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2450         } finally {
  2451             tsym.flags_field &= ~LOCKED;
  2452             tsym.flags_field |= ACYCLIC_ANN;
  2456     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2457         switch (type.tag) {
  2458         case TypeTags.CLASS:
  2459             if ((type.tsym.flags() & ANNOTATION) != 0)
  2460                 checkNonCyclicElementsInternal(pos, type.tsym);
  2461             break;
  2462         case TypeTags.ARRAY:
  2463             checkAnnotationResType(pos, types.elemtype(type));
  2464             break;
  2465         default:
  2466             break; // int etc
  2470 /* *************************************************************************
  2471  * Check for cycles in the constructor call graph.
  2472  **************************************************************************/
  2474     /** Check for cycles in the graph of constructors calling other
  2475      *  constructors.
  2476      */
  2477     void checkCyclicConstructors(JCClassDecl tree) {
  2478         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2480         // enter each constructor this-call into the map
  2481         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2482             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2483             if (app == null) continue;
  2484             JCMethodDecl meth = (JCMethodDecl) l.head;
  2485             if (TreeInfo.name(app.meth) == names._this) {
  2486                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2487             } else {
  2488                 meth.sym.flags_field |= ACYCLIC;
  2492         // Check for cycles in the map
  2493         Symbol[] ctors = new Symbol[0];
  2494         ctors = callMap.keySet().toArray(ctors);
  2495         for (Symbol caller : ctors) {
  2496             checkCyclicConstructor(tree, caller, callMap);
  2500     /** Look in the map to see if the given constructor is part of a
  2501      *  call cycle.
  2502      */
  2503     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2504                                         Map<Symbol,Symbol> callMap) {
  2505         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2506             if ((ctor.flags_field & LOCKED) != 0) {
  2507                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2508                           "recursive.ctor.invocation");
  2509             } else {
  2510                 ctor.flags_field |= LOCKED;
  2511                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2512                 ctor.flags_field &= ~LOCKED;
  2514             ctor.flags_field |= ACYCLIC;
  2518 /* *************************************************************************
  2519  * Miscellaneous
  2520  **************************************************************************/
  2522     /**
  2523      * Return the opcode of the operator but emit an error if it is an
  2524      * error.
  2525      * @param pos        position for error reporting.
  2526      * @param operator   an operator
  2527      * @param tag        a tree tag
  2528      * @param left       type of left hand side
  2529      * @param right      type of right hand side
  2530      */
  2531     int checkOperator(DiagnosticPosition pos,
  2532                        OperatorSymbol operator,
  2533                        int tag,
  2534                        Type left,
  2535                        Type right) {
  2536         if (operator.opcode == ByteCodes.error) {
  2537             log.error(pos,
  2538                       "operator.cant.be.applied",
  2539                       treeinfo.operatorName(tag),
  2540                       List.of(left, right));
  2542         return operator.opcode;
  2546     /**
  2547      *  Check for division by integer constant zero
  2548      *  @param pos           Position for error reporting.
  2549      *  @param operator      The operator for the expression
  2550      *  @param operand       The right hand operand for the expression
  2551      */
  2552     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2553         if (operand.constValue() != null
  2554             && lint.isEnabled(LintCategory.DIVZERO)
  2555             && operand.tag <= LONG
  2556             && ((Number) (operand.constValue())).longValue() == 0) {
  2557             int opc = ((OperatorSymbol)operator).opcode;
  2558             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2559                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2560                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  2565     /**
  2566      * Check for empty statements after if
  2567      */
  2568     void checkEmptyIf(JCIf tree) {
  2569         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(LintCategory.EMPTY))
  2570             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  2573     /** Check that symbol is unique in given scope.
  2574      *  @param pos           Position for error reporting.
  2575      *  @param sym           The symbol.
  2576      *  @param s             The scope.
  2577      */
  2578     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2579         if (sym.type.isErroneous())
  2580             return true;
  2581         if (sym.owner.name == names.any) return false;
  2582         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2583             if (sym != e.sym &&
  2584                 sym.kind == e.sym.kind &&
  2585                 sym.name != names.error &&
  2586                 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2587                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2588                     varargsDuplicateError(pos, sym, e.sym);
  2589                 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
  2590                     duplicateErasureError(pos, sym, e.sym);
  2591                 else
  2592                     duplicateError(pos, e.sym);
  2593                 return false;
  2596         return true;
  2598     //where
  2599     /** Report duplicate declaration error.
  2600      */
  2601     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2602         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2603             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2607     /** Check that single-type import is not already imported or top-level defined,
  2608      *  but make an exception for two single-type imports which denote the same type.
  2609      *  @param pos           Position for error reporting.
  2610      *  @param sym           The symbol.
  2611      *  @param s             The scope
  2612      */
  2613     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2614         return checkUniqueImport(pos, sym, s, false);
  2617     /** Check that static single-type import is not already imported or top-level defined,
  2618      *  but make an exception for two single-type imports which denote the same type.
  2619      *  @param pos           Position for error reporting.
  2620      *  @param sym           The symbol.
  2621      *  @param s             The scope
  2622      *  @param staticImport  Whether or not this was a static import
  2623      */
  2624     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2625         return checkUniqueImport(pos, sym, s, true);
  2628     /** Check that single-type import is not already imported or top-level defined,
  2629      *  but make an exception for two single-type imports which denote the same type.
  2630      *  @param pos           Position for error reporting.
  2631      *  @param sym           The symbol.
  2632      *  @param s             The scope.
  2633      *  @param staticImport  Whether or not this was a static import
  2634      */
  2635     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2636         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2637             // is encountered class entered via a class declaration?
  2638             boolean isClassDecl = e.scope == s;
  2639             if ((isClassDecl || sym != e.sym) &&
  2640                 sym.kind == e.sym.kind &&
  2641                 sym.name != names.error) {
  2642                 if (!e.sym.type.isErroneous()) {
  2643                     String what = e.sym.toString();
  2644                     if (!isClassDecl) {
  2645                         if (staticImport)
  2646                             log.error(pos, "already.defined.static.single.import", what);
  2647                         else
  2648                             log.error(pos, "already.defined.single.import", what);
  2650                     else if (sym != e.sym)
  2651                         log.error(pos, "already.defined.this.unit", what);
  2653                 return false;
  2656         return true;
  2659     /** Check that a qualified name is in canonical form (for import decls).
  2660      */
  2661     public void checkCanonical(JCTree tree) {
  2662         if (!isCanonical(tree))
  2663             log.error(tree.pos(), "import.requires.canonical",
  2664                       TreeInfo.symbol(tree));
  2666         // where
  2667         private boolean isCanonical(JCTree tree) {
  2668             while (tree.getTag() == JCTree.SELECT) {
  2669                 JCFieldAccess s = (JCFieldAccess) tree;
  2670                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2671                     return false;
  2672                 tree = s.selected;
  2674             return true;
  2677     private class ConversionWarner extends Warner {
  2678         final String uncheckedKey;
  2679         final Type found;
  2680         final Type expected;
  2681         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  2682             super(pos);
  2683             this.uncheckedKey = uncheckedKey;
  2684             this.found = found;
  2685             this.expected = expected;
  2688         @Override
  2689         public void warn(LintCategory lint) {
  2690             boolean warned = this.warned;
  2691             super.warn(lint);
  2692             if (warned) return; // suppress redundant diagnostics
  2693             switch (lint) {
  2694                 case UNCHECKED:
  2695                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  2696                     break;
  2697                 case VARARGS:
  2698                     if (method != null &&
  2699                             method.attribute(syms.trustMeType.tsym) != null &&
  2700                             isTrustMeAllowedOnMethod(method) &&
  2701                             !types.isReifiable(method.type.getParameterTypes().last())) {
  2702                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  2704                     break;
  2705                 default:
  2706                     throw new AssertionError("Unexpected lint: " + lint);
  2711     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2712         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2715     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2716         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial