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

Tue, 14 Feb 2012 15:43:52 -0800

author
mcimadamore
date
Tue, 14 Feb 2012 15:43:52 -0800
changeset 1198
84b61130cbed
parent 1157
3809292620c9
child 1216
6aafebe9a394
permissions
-rw-r--r--

7142086: performance problem in Check.checkOverrideClashes(...)
Summary: Code in Check.checkOverrideClashes() causes too many calls to MethodSymbol.overrides
Reviewed-by: jjg
Contributed-by: jan.lahoda@oracle.com

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    31 import com.sun.tools.javac.code.*;
    32 import com.sun.tools.javac.jvm.*;
    33 import com.sun.tools.javac.tree.*;
    34 import com.sun.tools.javac.util.*;
    35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    36 import com.sun.tools.javac.util.List;
    38 import com.sun.tools.javac.tree.JCTree.*;
    39 import com.sun.tools.javac.code.Lint;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    44 import static com.sun.tools.javac.code.Flags.*;
    45 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    46 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    47 import static com.sun.tools.javac.code.Kinds.*;
    48 import static com.sun.tools.javac.code.TypeTags.*;
    49 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    53 /** Type checking helper class for the attribution phase.
    54  *
    55  *  <p><b>This is NOT part of any supported API.
    56  *  If you write code that depends on this, you do so at your own risk.
    57  *  This code and its internal interfaces are subject to change or
    58  *  deletion without notice.</b>
    59  */
    60 public class Check {
    61     protected static final Context.Key<Check> checkKey =
    62         new Context.Key<Check>();
    64     private final Names names;
    65     private final Log log;
    66     private final Symtab syms;
    67     private final Enter enter;
    68     private final Infer infer;
    69     private final Types types;
    70     private final JCDiagnostic.Factory diags;
    71     private final boolean skipAnnotations;
    72     private boolean warnOnSyntheticConflicts;
    73     private boolean suppressAbortOnBadClassFile;
    74     private boolean enableSunApiLintControl;
    75     private final TreeInfo treeinfo;
    77     // The set of lint options currently in effect. It is initialized
    78     // from the context, and then is set/reset as needed by Attr as it
    79     // visits all the various parts of the trees during attribution.
    80     private Lint lint;
    82     // The method being analyzed in Attr - it is set/reset as needed by
    83     // Attr as it visits new method declarations.
    84     private MethodSymbol method;
    86     public static Check instance(Context context) {
    87         Check instance = context.get(checkKey);
    88         if (instance == null)
    89             instance = new Check(context);
    90         return instance;
    91     }
    93     protected Check(Context context) {
    94         context.put(checkKey, this);
    96         names = Names.instance(context);
    97         log = Log.instance(context);
    98         syms = Symtab.instance(context);
    99         enter = Enter.instance(context);
   100         infer = Infer.instance(context);
   101         this.types = Types.instance(context);
   102         diags = JCDiagnostic.Factory.instance(context);
   103         Options options = Options.instance(context);
   104         lint = Lint.instance(context);
   105         treeinfo = TreeInfo.instance(context);
   107         Source source = Source.instance(context);
   108         allowGenerics = source.allowGenerics();
   109         allowAnnotations = source.allowAnnotations();
   110         allowCovariantReturns = source.allowCovariantReturns();
   111         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   112         complexInference = options.isSet("complexinference");
   113         skipAnnotations = options.isSet("skipAnnotations");
   114         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   115         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   116         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   118         Target target = Target.instance(context);
   119         syntheticNameChar = target.syntheticNameChar();
   121         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   122         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   123         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   124         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   126         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   127                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   128         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   129                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   130         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   131                 enforceMandatoryWarnings, "sunapi", null);
   133         deferredLintHandler = DeferredLintHandler.immediateHandler;
   134     }
   136     /** Switch: generics enabled?
   137      */
   138     boolean allowGenerics;
   140     /** Switch: annotations enabled?
   141      */
   142     boolean allowAnnotations;
   144     /** Switch: covariant returns enabled?
   145      */
   146     boolean allowCovariantReturns;
   148     /** Switch: simplified varargs enabled?
   149      */
   150     boolean allowSimplifiedVarargs;
   152     /** Switch: -complexinference option set?
   153      */
   154     boolean complexInference;
   156     /** Character for synthetic names
   157      */
   158     char syntheticNameChar;
   160     /** A table mapping flat names of all compiled classes in this run to their
   161      *  symbols; maintained from outside.
   162      */
   163     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   165     /** A handler for messages about deprecated usage.
   166      */
   167     private MandatoryWarningHandler deprecationHandler;
   169     /** A handler for messages about unchecked or unsafe usage.
   170      */
   171     private MandatoryWarningHandler uncheckedHandler;
   173     /** A handler for messages about using proprietary API.
   174      */
   175     private MandatoryWarningHandler sunApiHandler;
   177     /** A handler for deferred lint warnings.
   178      */
   179     private DeferredLintHandler deferredLintHandler;
   181 /* *************************************************************************
   182  * Errors and Warnings
   183  **************************************************************************/
   185     Lint setLint(Lint newLint) {
   186         Lint prev = lint;
   187         lint = newLint;
   188         return prev;
   189     }
   191     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   192         DeferredLintHandler prev = deferredLintHandler;
   193         deferredLintHandler = newDeferredLintHandler;
   194         return prev;
   195     }
   197     MethodSymbol setMethod(MethodSymbol newMethod) {
   198         MethodSymbol prev = method;
   199         method = newMethod;
   200         return prev;
   201     }
   203     /** Warn about deprecated symbol.
   204      *  @param pos        Position to be used for error reporting.
   205      *  @param sym        The deprecated symbol.
   206      */
   207     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   208         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   209             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   210     }
   212     /** Warn about unchecked operation.
   213      *  @param pos        Position to be used for error reporting.
   214      *  @param msg        A string describing the problem.
   215      */
   216     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   217         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   218             uncheckedHandler.report(pos, msg, args);
   219     }
   221     /** Warn about unsafe vararg method decl.
   222      *  @param pos        Position to be used for error reporting.
   223      *  @param sym        The deprecated symbol.
   224      */
   225     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   226         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   227             log.warning(LintCategory.VARARGS, pos, key, args);
   228     }
   230     /** Warn about using proprietary API.
   231      *  @param pos        Position to be used for error reporting.
   232      *  @param msg        A string describing the problem.
   233      */
   234     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   235         if (!lint.isSuppressed(LintCategory.SUNAPI))
   236             sunApiHandler.report(pos, msg, args);
   237     }
   239     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   240         if (lint.isEnabled(LintCategory.STATIC))
   241             log.warning(LintCategory.STATIC, pos, msg, args);
   242     }
   244     /**
   245      * Report any deferred diagnostics.
   246      */
   247     public void reportDeferredDiagnostics() {
   248         deprecationHandler.reportDeferredDiagnostic();
   249         uncheckedHandler.reportDeferredDiagnostic();
   250         sunApiHandler.reportDeferredDiagnostic();
   251     }
   254     /** Report a failure to complete a class.
   255      *  @param pos        Position to be used for error reporting.
   256      *  @param ex         The failure to report.
   257      */
   258     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   259         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   260         if (ex instanceof ClassReader.BadClassFile
   261                 && !suppressAbortOnBadClassFile) throw new Abort();
   262         else return syms.errType;
   263     }
   265     /** Report a type error.
   266      *  @param pos        Position to be used for error reporting.
   267      *  @param problem    A string describing the error.
   268      *  @param found      The type that was found.
   269      *  @param req        The type that was required.
   270      */
   271     Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
   272         log.error(pos, "prob.found.req",
   273                   problem, found, req);
   274         return types.createErrorType(found);
   275     }
   277     Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
   278         log.error(pos, "prob.found.req.1", problem, found, req, explanation);
   279         return types.createErrorType(found);
   280     }
   282     /** Report an error that wrong type tag was found.
   283      *  @param pos        Position to be used for error reporting.
   284      *  @param required   An internationalized string describing the type tag
   285      *                    required.
   286      *  @param found      The type that was found.
   287      */
   288     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   289         // this error used to be raised by the parser,
   290         // but has been delayed to this point:
   291         if (found instanceof Type && ((Type)found).tag == VOID) {
   292             log.error(pos, "illegal.start.of.type");
   293             return syms.errType;
   294         }
   295         log.error(pos, "type.found.req", found, required);
   296         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   297     }
   299     /** Report an error that symbol cannot be referenced before super
   300      *  has been called.
   301      *  @param pos        Position to be used for error reporting.
   302      *  @param sym        The referenced symbol.
   303      */
   304     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   305         log.error(pos, "cant.ref.before.ctor.called", sym);
   306     }
   308     /** Report duplicate declaration error.
   309      */
   310     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   311         if (!sym.type.isErroneous()) {
   312             Symbol location = sym.location();
   313             if (location.kind == MTH &&
   314                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   315                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   316                         kindName(sym.location()), kindName(sym.location().enclClass()),
   317                         sym.location().enclClass());
   318             } else {
   319                 log.error(pos, "already.defined", kindName(sym), sym,
   320                         kindName(sym.location()), sym.location());
   321             }
   322         }
   323     }
   325     /** Report array/varargs duplicate declaration
   326      */
   327     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   328         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   329             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   330         }
   331     }
   333 /* ************************************************************************
   334  * duplicate declaration checking
   335  *************************************************************************/
   337     /** Check that variable does not hide variable with same name in
   338      *  immediately enclosing local scope.
   339      *  @param pos           Position for error reporting.
   340      *  @param v             The symbol.
   341      *  @param s             The scope.
   342      */
   343     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   344         if (s.next != null) {
   345             for (Scope.Entry e = s.next.lookup(v.name);
   346                  e.scope != null && e.sym.owner == v.owner;
   347                  e = e.next()) {
   348                 if (e.sym.kind == VAR &&
   349                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   350                     v.name != names.error) {
   351                     duplicateError(pos, e.sym);
   352                     return;
   353                 }
   354             }
   355         }
   356     }
   358     /** Check that a class or interface does not hide a class or
   359      *  interface with same name in immediately enclosing local scope.
   360      *  @param pos           Position for error reporting.
   361      *  @param c             The symbol.
   362      *  @param s             The scope.
   363      */
   364     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   365         if (s.next != null) {
   366             for (Scope.Entry e = s.next.lookup(c.name);
   367                  e.scope != null && e.sym.owner == c.owner;
   368                  e = e.next()) {
   369                 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
   370                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   371                     c.name != names.error) {
   372                     duplicateError(pos, e.sym);
   373                     return;
   374                 }
   375             }
   376         }
   377     }
   379     /** Check that class does not have the same name as one of
   380      *  its enclosing classes, or as a class defined in its enclosing scope.
   381      *  return true if class is unique in its enclosing scope.
   382      *  @param pos           Position for error reporting.
   383      *  @param name          The class name.
   384      *  @param s             The enclosing scope.
   385      */
   386     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   387         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   388             if (e.sym.kind == TYP && e.sym.name != names.error) {
   389                 duplicateError(pos, e.sym);
   390                 return false;
   391             }
   392         }
   393         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   394             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   395                 duplicateError(pos, sym);
   396                 return true;
   397             }
   398         }
   399         return true;
   400     }
   402 /* *************************************************************************
   403  * Class name generation
   404  **************************************************************************/
   406     /** Return name of local class.
   407      *  This is of the form    <enclClass> $ n <classname>
   408      *  where
   409      *    enclClass is the flat name of the enclosing class,
   410      *    classname is the simple name of the local class
   411      */
   412     Name localClassName(ClassSymbol c) {
   413         for (int i=1; ; i++) {
   414             Name flatname = names.
   415                 fromString("" + c.owner.enclClass().flatname +
   416                            syntheticNameChar + i +
   417                            c.name);
   418             if (compiled.get(flatname) == null) return flatname;
   419         }
   420     }
   422 /* *************************************************************************
   423  * Type Checking
   424  **************************************************************************/
   426     /** Check that a given type is assignable to a given proto-type.
   427      *  If it is, return the type, otherwise return errType.
   428      *  @param pos        Position to be used for error reporting.
   429      *  @param found      The type that was found.
   430      *  @param req        The type that was required.
   431      */
   432     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   433         return checkType(pos, found, req, "incompatible.types");
   434     }
   436     Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
   437         if (req.tag == ERROR)
   438             return req;
   439         if (found.tag == FORALL)
   440             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   441         if (req.tag == NONE)
   442             return found;
   443         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   444             return found;
   445         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   446             return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
   447         if (found.isSuperBound()) {
   448             log.error(pos, "assignment.from.super-bound", found);
   449             return types.createErrorType(found);
   450         }
   451         if (req.isExtendsBound()) {
   452             log.error(pos, "assignment.to.extends-bound", req);
   453             return types.createErrorType(found);
   454         }
   455         return typeError(pos, diags.fragment(errKey), found, req);
   456     }
   458     /** Instantiate polymorphic type to some prototype, unless
   459      *  prototype is `anyPoly' in which case polymorphic type
   460      *  is returned unchanged.
   461      */
   462     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
   463         if (pt == Infer.anyPoly && complexInference) {
   464             return t;
   465         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   466             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   467             return instantiatePoly(pos, t, newpt, warn);
   468         } else if (pt.tag == ERROR) {
   469             return pt;
   470         } else {
   471             try {
   472                 return infer.instantiateExpr(t, pt, warn);
   473             } catch (Infer.NoInstanceException ex) {
   474                 if (ex.isAmbiguous) {
   475                     JCDiagnostic d = ex.getDiagnostic();
   476                     log.error(pos,
   477                               "undetermined.type" + (d!=null ? ".1" : ""),
   478                               t, d);
   479                     return types.createErrorType(pt);
   480                 } else {
   481                     JCDiagnostic d = ex.getDiagnostic();
   482                     return typeError(pos,
   483                                      diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   484                                      t, pt);
   485                 }
   486             } catch (Infer.InvalidInstanceException ex) {
   487                 JCDiagnostic d = ex.getDiagnostic();
   488                 log.error(pos, "invalid.inferred.types", t.tvars, d);
   489                 return types.createErrorType(pt);
   490             }
   491         }
   492     }
   494     /** Check that a given type can be cast to a given target type.
   495      *  Return the result of the cast.
   496      *  @param pos        Position to be used for error reporting.
   497      *  @param found      The type that is being cast.
   498      *  @param req        The target type of the cast.
   499      */
   500     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   501         if (found.tag == FORALL) {
   502             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   503             return req;
   504         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   505             return req;
   506         } else {
   507             return typeError(pos,
   508                              diags.fragment("inconvertible.types"),
   509                              found, req);
   510         }
   511     }
   512 //where
   513         /** Is type a type variable, or a (possibly multi-dimensional) array of
   514          *  type variables?
   515          */
   516         boolean isTypeVar(Type t) {
   517             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   518         }
   520     /** Check that a type is within some bounds.
   521      *
   522      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   523      *  type argument.
   524      *  @param pos           Position to be used for error reporting.
   525      *  @param a             The type that should be bounded by bs.
   526      *  @param bs            The bound.
   527      */
   528     private boolean checkExtends(Type a, TypeVar bs) {
   529          if (a.isUnbound()) {
   530              return true;
   531          } else if (a.tag != WILDCARD) {
   532              a = types.upperBound(a);
   533              return types.isSubtype(a, bs.bound);
   534          } else if (a.isExtendsBound()) {
   535              return types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings);
   536          } else if (a.isSuperBound()) {
   537              return !types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound());
   538          }
   539          return true;
   540      }
   542     /** Check that type is different from 'void'.
   543      *  @param pos           Position to be used for error reporting.
   544      *  @param t             The type to be checked.
   545      */
   546     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   547         if (t.tag == VOID) {
   548             log.error(pos, "void.not.allowed.here");
   549             return types.createErrorType(t);
   550         } else {
   551             return t;
   552         }
   553     }
   555     /** Check that type is a class or interface type.
   556      *  @param pos           Position to be used for error reporting.
   557      *  @param t             The type to be checked.
   558      */
   559     Type checkClassType(DiagnosticPosition pos, Type t) {
   560         if (t.tag != CLASS && t.tag != ERROR)
   561             return typeTagError(pos,
   562                                 diags.fragment("type.req.class"),
   563                                 (t.tag == TYPEVAR)
   564                                 ? diags.fragment("type.parameter", t)
   565                                 : t);
   566         else
   567             return t;
   568     }
   570     /** Check that type is a class or interface type.
   571      *  @param pos           Position to be used for error reporting.
   572      *  @param t             The type to be checked.
   573      *  @param noBounds    True if type bounds are illegal here.
   574      */
   575     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   576         t = checkClassType(pos, t);
   577         if (noBounds && t.isParameterized()) {
   578             List<Type> args = t.getTypeArguments();
   579             while (args.nonEmpty()) {
   580                 if (args.head.tag == WILDCARD)
   581                     return typeTagError(pos,
   582                                         diags.fragment("type.req.exact"),
   583                                         args.head);
   584                 args = args.tail;
   585             }
   586         }
   587         return t;
   588     }
   590     /** Check that type is a reifiable class, interface or array type.
   591      *  @param pos           Position to be used for error reporting.
   592      *  @param t             The type to be checked.
   593      */
   594     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   595         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   596             return typeTagError(pos,
   597                                 diags.fragment("type.req.class.array"),
   598                                 t);
   599         } else if (!types.isReifiable(t)) {
   600             log.error(pos, "illegal.generic.type.for.instof");
   601             return types.createErrorType(t);
   602         } else {
   603             return t;
   604         }
   605     }
   607     /** Check that type is a reference type, i.e. a class, interface or array type
   608      *  or a type variable.
   609      *  @param pos           Position to be used for error reporting.
   610      *  @param t             The type to be checked.
   611      */
   612     Type checkRefType(DiagnosticPosition pos, Type t) {
   613         switch (t.tag) {
   614         case CLASS:
   615         case ARRAY:
   616         case TYPEVAR:
   617         case WILDCARD:
   618         case ERROR:
   619             return t;
   620         default:
   621             return typeTagError(pos,
   622                                 diags.fragment("type.req.ref"),
   623                                 t);
   624         }
   625     }
   627     /** Check that each type is a reference type, i.e. a class, interface or array type
   628      *  or a type variable.
   629      *  @param trees         Original trees, used for error reporting.
   630      *  @param types         The types to be checked.
   631      */
   632     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   633         List<JCExpression> tl = trees;
   634         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   635             l.head = checkRefType(tl.head.pos(), l.head);
   636             tl = tl.tail;
   637         }
   638         return types;
   639     }
   641     /** Check that type is a null or reference type.
   642      *  @param pos           Position to be used for error reporting.
   643      *  @param t             The type to be checked.
   644      */
   645     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   646         switch (t.tag) {
   647         case CLASS:
   648         case ARRAY:
   649         case TYPEVAR:
   650         case WILDCARD:
   651         case BOT:
   652         case ERROR:
   653             return t;
   654         default:
   655             return typeTagError(pos,
   656                                 diags.fragment("type.req.ref"),
   657                                 t);
   658         }
   659     }
   661     /** Check that flag set does not contain elements of two conflicting sets. s
   662      *  Return true if it doesn't.
   663      *  @param pos           Position to be used for error reporting.
   664      *  @param flags         The set of flags to be checked.
   665      *  @param set1          Conflicting flags set #1.
   666      *  @param set2          Conflicting flags set #2.
   667      */
   668     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   669         if ((flags & set1) != 0 && (flags & set2) != 0) {
   670             log.error(pos,
   671                       "illegal.combination.of.modifiers",
   672                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   673                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   674             return false;
   675         } else
   676             return true;
   677     }
   679     /** Check that usage of diamond operator is correct (i.e. diamond should not
   680      * be used with non-generic classes or in anonymous class creation expressions)
   681      */
   682     Type checkDiamond(JCNewClass tree, Type t) {
   683         if (!TreeInfo.isDiamond(tree) ||
   684                 t.isErroneous()) {
   685             return checkClassType(tree.clazz.pos(), t, true);
   686         } else if (tree.def != null) {
   687             log.error(tree.clazz.pos(),
   688                     "cant.apply.diamond.1",
   689                     t, diags.fragment("diamond.and.anon.class", t));
   690             return types.createErrorType(t);
   691         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   692             log.error(tree.clazz.pos(),
   693                 "cant.apply.diamond.1",
   694                 t, diags.fragment("diamond.non.generic", t));
   695             return types.createErrorType(t);
   696         } else if (tree.typeargs != null &&
   697                 tree.typeargs.nonEmpty()) {
   698             log.error(tree.clazz.pos(),
   699                 "cant.apply.diamond.1",
   700                 t, diags.fragment("diamond.and.explicit.params", t));
   701             return types.createErrorType(t);
   702         } else {
   703             return t;
   704         }
   705     }
   707     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   708         MethodSymbol m = tree.sym;
   709         if (!allowSimplifiedVarargs) return;
   710         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   711         Type varargElemType = null;
   712         if (m.isVarArgs()) {
   713             varargElemType = types.elemtype(tree.params.last().type);
   714         }
   715         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   716             if (varargElemType != null) {
   717                 log.error(tree,
   718                         "varargs.invalid.trustme.anno",
   719                         syms.trustMeType.tsym,
   720                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   721             } else {
   722                 log.error(tree,
   723                             "varargs.invalid.trustme.anno",
   724                             syms.trustMeType.tsym,
   725                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   726             }
   727         } else if (hasTrustMeAnno && varargElemType != null &&
   728                             types.isReifiable(varargElemType)) {
   729             warnUnsafeVararg(tree,
   730                             "varargs.redundant.trustme.anno",
   731                             syms.trustMeType.tsym,
   732                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   733         }
   734         else if (!hasTrustMeAnno && varargElemType != null &&
   735                 !types.isReifiable(varargElemType)) {
   736             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   737         }
   738     }
   739     //where
   740         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   741             return (s.flags() & VARARGS) != 0 &&
   742                 (s.isConstructor() ||
   743                     (s.flags() & (STATIC | FINAL)) != 0);
   744         }
   746     /**
   747      * Check that vararg method call is sound
   748      * @param pos Position to be used for error reporting.
   749      * @param argtypes Actual arguments supplied to vararg method.
   750      */
   751     void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
   752         Type argtype = argtypes.last();
   753         if (!types.isReifiable(argtype) &&
   754                 (!allowSimplifiedVarargs ||
   755                 msym.attribute(syms.trustMeType.tsym) == null ||
   756                 !isTrustMeAllowedOnMethod(msym))) {
   757             warnUnchecked(pos,
   758                               "unchecked.generic.array.creation",
   759                               argtype);
   760         }
   761     }
   763     /**
   764      * Check that type 't' is a valid instantiation of a generic class
   765      * (see JLS 4.5)
   766      *
   767      * @param t class type to be checked
   768      * @return true if 't' is well-formed
   769      */
   770     public boolean checkValidGenericType(Type t) {
   771         return firstIncompatibleTypeArg(t) == null;
   772     }
   773     //WHERE
   774         private Type firstIncompatibleTypeArg(Type type) {
   775             List<Type> formals = type.tsym.type.allparams();
   776             List<Type> actuals = type.allparams();
   777             List<Type> args = type.getTypeArguments();
   778             List<Type> forms = type.tsym.type.getTypeArguments();
   779             ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
   781             // For matching pairs of actual argument types `a' and
   782             // formal type parameters with declared bound `b' ...
   783             while (args.nonEmpty() && forms.nonEmpty()) {
   784                 // exact type arguments needs to know their
   785                 // bounds (for upper and lower bound
   786                 // calculations).  So we create new TypeVars with
   787                 // bounds substed with actuals.
   788                 tvars_buf.append(types.substBound(((TypeVar)forms.head),
   789                                                   formals,
   790                                                   actuals));
   791                 args = args.tail;
   792                 forms = forms.tail;
   793             }
   795             args = type.getTypeArguments();
   796             List<Type> tvars_cap = types.substBounds(formals,
   797                                       formals,
   798                                       types.capture(type).allparams());
   799             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   800                 // Let the actual arguments know their bound
   801                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   802                 args = args.tail;
   803                 tvars_cap = tvars_cap.tail;
   804             }
   806             args = type.getTypeArguments();
   807             List<Type> tvars = tvars_buf.toList();
   809             while (args.nonEmpty() && tvars.nonEmpty()) {
   810                 Type actual = types.subst(args.head,
   811                     type.tsym.type.getTypeArguments(),
   812                     tvars_buf.toList());
   813                 if (!isTypeArgErroneous(actual) &&
   814                         !tvars.head.getUpperBound().isErroneous() &&
   815                         !checkExtends(actual, (TypeVar)tvars.head)) {
   816                     return args.head;
   817                 }
   818                 args = args.tail;
   819                 tvars = tvars.tail;
   820             }
   822             args = type.getTypeArguments();
   823             tvars = tvars_buf.toList();
   825             for (Type arg : types.capture(type).getTypeArguments()) {
   826                 if (arg.tag == TYPEVAR &&
   827                         arg.getUpperBound().isErroneous() &&
   828                         !tvars.head.getUpperBound().isErroneous() &&
   829                         !isTypeArgErroneous(args.head)) {
   830                     return args.head;
   831                 }
   832                 tvars = tvars.tail;
   833                 args = args.tail;
   834             }
   836             return null;
   837         }
   838         //where
   839         boolean isTypeArgErroneous(Type t) {
   840             return isTypeArgErroneous.visit(t);
   841         }
   843         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
   844             public Boolean visitType(Type t, Void s) {
   845                 return t.isErroneous();
   846             }
   847             @Override
   848             public Boolean visitTypeVar(TypeVar t, Void s) {
   849                 return visit(t.getUpperBound());
   850             }
   851             @Override
   852             public Boolean visitCapturedType(CapturedType t, Void s) {
   853                 return visit(t.getUpperBound()) ||
   854                         visit(t.getLowerBound());
   855             }
   856             @Override
   857             public Boolean visitWildcardType(WildcardType t, Void s) {
   858                 return visit(t.type);
   859             }
   860         };
   862     /** Check that given modifiers are legal for given symbol and
   863      *  return modifiers together with any implicit modififiers for that symbol.
   864      *  Warning: we can't use flags() here since this method
   865      *  is called during class enter, when flags() would cause a premature
   866      *  completion.
   867      *  @param pos           Position to be used for error reporting.
   868      *  @param flags         The set of modifiers given in a definition.
   869      *  @param sym           The defined symbol.
   870      */
   871     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   872         long mask;
   873         long implicit = 0;
   874         switch (sym.kind) {
   875         case VAR:
   876             if (sym.owner.kind != TYP)
   877                 mask = LocalVarFlags;
   878             else if ((sym.owner.flags_field & INTERFACE) != 0)
   879                 mask = implicit = InterfaceVarFlags;
   880             else
   881                 mask = VarFlags;
   882             break;
   883         case MTH:
   884             if (sym.name == names.init) {
   885                 if ((sym.owner.flags_field & ENUM) != 0) {
   886                     // enum constructors cannot be declared public or
   887                     // protected and must be implicitly or explicitly
   888                     // private
   889                     implicit = PRIVATE;
   890                     mask = PRIVATE;
   891                 } else
   892                     mask = ConstructorFlags;
   893             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   894                 mask = implicit = InterfaceMethodFlags;
   895             else {
   896                 mask = MethodFlags;
   897             }
   898             // Imply STRICTFP if owner has STRICTFP set.
   899             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   900               implicit |= sym.owner.flags_field & STRICTFP;
   901             break;
   902         case TYP:
   903             if (sym.isLocal()) {
   904                 mask = LocalClassFlags;
   905                 if (sym.name.isEmpty()) { // Anonymous class
   906                     // Anonymous classes in static methods are themselves static;
   907                     // that's why we admit STATIC here.
   908                     mask |= STATIC;
   909                     // JLS: Anonymous classes are final.
   910                     implicit |= FINAL;
   911                 }
   912                 if ((sym.owner.flags_field & STATIC) == 0 &&
   913                     (flags & ENUM) != 0)
   914                     log.error(pos, "enums.must.be.static");
   915             } else if (sym.owner.kind == TYP) {
   916                 mask = MemberClassFlags;
   917                 if (sym.owner.owner.kind == PCK ||
   918                     (sym.owner.flags_field & STATIC) != 0)
   919                     mask |= STATIC;
   920                 else if ((flags & ENUM) != 0)
   921                     log.error(pos, "enums.must.be.static");
   922                 // Nested interfaces and enums are always STATIC (Spec ???)
   923                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   924             } else {
   925                 mask = ClassFlags;
   926             }
   927             // Interfaces are always ABSTRACT
   928             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   930             if ((flags & ENUM) != 0) {
   931                 // enums can't be declared abstract or final
   932                 mask &= ~(ABSTRACT | FINAL);
   933                 implicit |= implicitEnumFinalFlag(tree);
   934             }
   935             // Imply STRICTFP if owner has STRICTFP set.
   936             implicit |= sym.owner.flags_field & STRICTFP;
   937             break;
   938         default:
   939             throw new AssertionError();
   940         }
   941         long illegal = flags & StandardFlags & ~mask;
   942         if (illegal != 0) {
   943             if ((illegal & INTERFACE) != 0) {
   944                 log.error(pos, "intf.not.allowed.here");
   945                 mask |= INTERFACE;
   946             }
   947             else {
   948                 log.error(pos,
   949                           "mod.not.allowed.here", asFlagSet(illegal));
   950             }
   951         }
   952         else if ((sym.kind == TYP ||
   953                   // ISSUE: Disallowing abstract&private is no longer appropriate
   954                   // in the presence of inner classes. Should it be deleted here?
   955                   checkDisjoint(pos, flags,
   956                                 ABSTRACT,
   957                                 PRIVATE | STATIC))
   958                  &&
   959                  checkDisjoint(pos, flags,
   960                                ABSTRACT | INTERFACE,
   961                                FINAL | NATIVE | SYNCHRONIZED)
   962                  &&
   963                  checkDisjoint(pos, flags,
   964                                PUBLIC,
   965                                PRIVATE | PROTECTED)
   966                  &&
   967                  checkDisjoint(pos, flags,
   968                                PRIVATE,
   969                                PUBLIC | PROTECTED)
   970                  &&
   971                  checkDisjoint(pos, flags,
   972                                FINAL,
   973                                VOLATILE)
   974                  &&
   975                  (sym.kind == TYP ||
   976                   checkDisjoint(pos, flags,
   977                                 ABSTRACT | NATIVE,
   978                                 STRICTFP))) {
   979             // skip
   980         }
   981         return flags & (mask | ~StandardFlags) | implicit;
   982     }
   985     /** Determine if this enum should be implicitly final.
   986      *
   987      *  If the enum has no specialized enum contants, it is final.
   988      *
   989      *  If the enum does have specialized enum contants, it is
   990      *  <i>not</i> final.
   991      */
   992     private long implicitEnumFinalFlag(JCTree tree) {
   993         if (!tree.hasTag(CLASSDEF)) return 0;
   994         class SpecialTreeVisitor extends JCTree.Visitor {
   995             boolean specialized;
   996             SpecialTreeVisitor() {
   997                 this.specialized = false;
   998             };
  1000             @Override
  1001             public void visitTree(JCTree tree) { /* no-op */ }
  1003             @Override
  1004             public void visitVarDef(JCVariableDecl tree) {
  1005                 if ((tree.mods.flags & ENUM) != 0) {
  1006                     if (tree.init instanceof JCNewClass &&
  1007                         ((JCNewClass) tree.init).def != null) {
  1008                         specialized = true;
  1014         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1015         JCClassDecl cdef = (JCClassDecl) tree;
  1016         for (JCTree defs: cdef.defs) {
  1017             defs.accept(sts);
  1018             if (sts.specialized) return 0;
  1020         return FINAL;
  1023 /* *************************************************************************
  1024  * Type Validation
  1025  **************************************************************************/
  1027     /** Validate a type expression. That is,
  1028      *  check that all type arguments of a parametric type are within
  1029      *  their bounds. This must be done in a second phase after type attributon
  1030      *  since a class might have a subclass as type parameter bound. E.g:
  1032      *  class B<A extends C> { ... }
  1033      *  class C extends B<C> { ... }
  1035      *  and we can't make sure that the bound is already attributed because
  1036      *  of possible cycles.
  1038      * Visitor method: Validate a type expression, if it is not null, catching
  1039      *  and reporting any completion failures.
  1040      */
  1041     void validate(JCTree tree, Env<AttrContext> env) {
  1042         validate(tree, env, true);
  1044     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1045         new Validator(env).validateTree(tree, checkRaw, true);
  1048     /** Visitor method: Validate a list of type expressions.
  1049      */
  1050     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1051         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1052             validate(l.head, env);
  1055     /** A visitor class for type validation.
  1056      */
  1057     class Validator extends JCTree.Visitor {
  1059         boolean isOuter;
  1060         Env<AttrContext> env;
  1062         Validator(Env<AttrContext> env) {
  1063             this.env = env;
  1066         @Override
  1067         public void visitTypeArray(JCArrayTypeTree tree) {
  1068             tree.elemtype.accept(this);
  1071         @Override
  1072         public void visitTypeApply(JCTypeApply tree) {
  1073             if (tree.type.tag == CLASS) {
  1074                 List<JCExpression> args = tree.arguments;
  1075                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1077                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1078                 if (incompatibleArg != null) {
  1079                     for (JCTree arg : tree.arguments) {
  1080                         if (arg.type == incompatibleArg) {
  1081                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1083                         forms = forms.tail;
  1087                 forms = tree.type.tsym.type.getTypeArguments();
  1089                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1091                 // For matching pairs of actual argument types `a' and
  1092                 // formal type parameters with declared bound `b' ...
  1093                 while (args.nonEmpty() && forms.nonEmpty()) {
  1094                     validateTree(args.head,
  1095                             !(isOuter && is_java_lang_Class),
  1096                             false);
  1097                     args = args.tail;
  1098                     forms = forms.tail;
  1101                 // Check that this type is either fully parameterized, or
  1102                 // not parameterized at all.
  1103                 if (tree.type.getEnclosingType().isRaw())
  1104                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1105                 if (tree.clazz.hasTag(SELECT))
  1106                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1110         @Override
  1111         public void visitTypeParameter(JCTypeParameter tree) {
  1112             validateTrees(tree.bounds, true, isOuter);
  1113             checkClassBounds(tree.pos(), tree.type);
  1116         @Override
  1117         public void visitWildcard(JCWildcard tree) {
  1118             if (tree.inner != null)
  1119                 validateTree(tree.inner, true, isOuter);
  1122         @Override
  1123         public void visitSelect(JCFieldAccess tree) {
  1124             if (tree.type.tag == CLASS) {
  1125                 visitSelectInternal(tree);
  1127                 // Check that this type is either fully parameterized, or
  1128                 // not parameterized at all.
  1129                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1130                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1134         public void visitSelectInternal(JCFieldAccess tree) {
  1135             if (tree.type.tsym.isStatic() &&
  1136                 tree.selected.type.isParameterized()) {
  1137                 // The enclosing type is not a class, so we are
  1138                 // looking at a static member type.  However, the
  1139                 // qualifying expression is parameterized.
  1140                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1141             } else {
  1142                 // otherwise validate the rest of the expression
  1143                 tree.selected.accept(this);
  1147         /** Default visitor method: do nothing.
  1148          */
  1149         @Override
  1150         public void visitTree(JCTree tree) {
  1153         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1154             try {
  1155                 if (tree != null) {
  1156                     this.isOuter = isOuter;
  1157                     tree.accept(this);
  1158                     if (checkRaw)
  1159                         checkRaw(tree, env);
  1161             } catch (CompletionFailure ex) {
  1162                 completionError(tree.pos(), ex);
  1166         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1167             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1168                 validateTree(l.head, checkRaw, isOuter);
  1171         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1172             if (lint.isEnabled(LintCategory.RAW) &&
  1173                 tree.type.tag == CLASS &&
  1174                 !TreeInfo.isDiamond(tree) &&
  1175                 !withinAnonConstr(env) &&
  1176                 tree.type.isRaw()) {
  1177                 log.warning(LintCategory.RAW,
  1178                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1182         boolean withinAnonConstr(Env<AttrContext> env) {
  1183             return env.enclClass.name.isEmpty() &&
  1184                     env.enclMethod != null && env.enclMethod.name == names.init;
  1188 /* *************************************************************************
  1189  * Exception checking
  1190  **************************************************************************/
  1192     /* The following methods treat classes as sets that contain
  1193      * the class itself and all their subclasses
  1194      */
  1196     /** Is given type a subtype of some of the types in given list?
  1197      */
  1198     boolean subset(Type t, List<Type> ts) {
  1199         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1200             if (types.isSubtype(t, l.head)) return true;
  1201         return false;
  1204     /** Is given type a subtype or supertype of
  1205      *  some of the types in given list?
  1206      */
  1207     boolean intersects(Type t, List<Type> ts) {
  1208         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1209             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1210         return false;
  1213     /** Add type set to given type list, unless it is a subclass of some class
  1214      *  in the list.
  1215      */
  1216     List<Type> incl(Type t, List<Type> ts) {
  1217         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1220     /** Remove type set from type set list.
  1221      */
  1222     List<Type> excl(Type t, List<Type> ts) {
  1223         if (ts.isEmpty()) {
  1224             return ts;
  1225         } else {
  1226             List<Type> ts1 = excl(t, ts.tail);
  1227             if (types.isSubtype(ts.head, t)) return ts1;
  1228             else if (ts1 == ts.tail) return ts;
  1229             else return ts1.prepend(ts.head);
  1233     /** Form the union of two type set lists.
  1234      */
  1235     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1236         List<Type> ts = ts1;
  1237         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1238             ts = incl(l.head, ts);
  1239         return ts;
  1242     /** Form the difference of two type lists.
  1243      */
  1244     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1245         List<Type> ts = ts1;
  1246         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1247             ts = excl(l.head, ts);
  1248         return ts;
  1251     /** Form the intersection of two type lists.
  1252      */
  1253     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1254         List<Type> ts = List.nil();
  1255         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1256             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1257         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1258             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1259         return ts;
  1262     /** Is exc an exception symbol that need not be declared?
  1263      */
  1264     boolean isUnchecked(ClassSymbol exc) {
  1265         return
  1266             exc.kind == ERR ||
  1267             exc.isSubClass(syms.errorType.tsym, types) ||
  1268             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1271     /** Is exc an exception type that need not be declared?
  1272      */
  1273     boolean isUnchecked(Type exc) {
  1274         return
  1275             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1276             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1277             exc.tag == BOT;
  1280     /** Same, but handling completion failures.
  1281      */
  1282     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1283         try {
  1284             return isUnchecked(exc);
  1285         } catch (CompletionFailure ex) {
  1286             completionError(pos, ex);
  1287             return true;
  1291     /** Is exc handled by given exception list?
  1292      */
  1293     boolean isHandled(Type exc, List<Type> handled) {
  1294         return isUnchecked(exc) || subset(exc, handled);
  1297     /** Return all exceptions in thrown list that are not in handled list.
  1298      *  @param thrown     The list of thrown exceptions.
  1299      *  @param handled    The list of handled exceptions.
  1300      */
  1301     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1302         List<Type> unhandled = List.nil();
  1303         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1304             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1305         return unhandled;
  1308 /* *************************************************************************
  1309  * Overriding/Implementation checking
  1310  **************************************************************************/
  1312     /** The level of access protection given by a flag set,
  1313      *  where PRIVATE is highest and PUBLIC is lowest.
  1314      */
  1315     static int protection(long flags) {
  1316         switch ((short)(flags & AccessFlags)) {
  1317         case PRIVATE: return 3;
  1318         case PROTECTED: return 1;
  1319         default:
  1320         case PUBLIC: return 0;
  1321         case 0: return 2;
  1325     /** A customized "cannot override" error message.
  1326      *  @param m      The overriding method.
  1327      *  @param other  The overridden method.
  1328      *  @return       An internationalized string.
  1329      */
  1330     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1331         String key;
  1332         if ((other.owner.flags() & INTERFACE) == 0)
  1333             key = "cant.override";
  1334         else if ((m.owner.flags() & INTERFACE) == 0)
  1335             key = "cant.implement";
  1336         else
  1337             key = "clashes.with";
  1338         return diags.fragment(key, m, m.location(), other, other.location());
  1341     /** A customized "override" warning message.
  1342      *  @param m      The overriding method.
  1343      *  @param other  The overridden method.
  1344      *  @return       An internationalized string.
  1345      */
  1346     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1347         String key;
  1348         if ((other.owner.flags() & INTERFACE) == 0)
  1349             key = "unchecked.override";
  1350         else if ((m.owner.flags() & INTERFACE) == 0)
  1351             key = "unchecked.implement";
  1352         else
  1353             key = "unchecked.clash.with";
  1354         return diags.fragment(key, m, m.location(), other, other.location());
  1357     /** A customized "override" warning message.
  1358      *  @param m      The overriding method.
  1359      *  @param other  The overridden method.
  1360      *  @return       An internationalized string.
  1361      */
  1362     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1363         String key;
  1364         if ((other.owner.flags() & INTERFACE) == 0)
  1365             key = "varargs.override";
  1366         else  if ((m.owner.flags() & INTERFACE) == 0)
  1367             key = "varargs.implement";
  1368         else
  1369             key = "varargs.clash.with";
  1370         return diags.fragment(key, m, m.location(), other, other.location());
  1373     /** Check that this method conforms with overridden method 'other'.
  1374      *  where `origin' is the class where checking started.
  1375      *  Complications:
  1376      *  (1) Do not check overriding of synthetic methods
  1377      *      (reason: they might be final).
  1378      *      todo: check whether this is still necessary.
  1379      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1380      *      than the method it implements. Augment the proxy methods with the
  1381      *      undeclared exceptions in this case.
  1382      *  (3) When generics are enabled, admit the case where an interface proxy
  1383      *      has a result type
  1384      *      extended by the result type of the method it implements.
  1385      *      Change the proxies result type to the smaller type in this case.
  1387      *  @param tree         The tree from which positions
  1388      *                      are extracted for errors.
  1389      *  @param m            The overriding method.
  1390      *  @param other        The overridden method.
  1391      *  @param origin       The class of which the overriding method
  1392      *                      is a member.
  1393      */
  1394     void checkOverride(JCTree tree,
  1395                        MethodSymbol m,
  1396                        MethodSymbol other,
  1397                        ClassSymbol origin) {
  1398         // Don't check overriding of synthetic methods or by bridge methods.
  1399         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1400             return;
  1403         // Error if static method overrides instance method (JLS 8.4.6.2).
  1404         if ((m.flags() & STATIC) != 0 &&
  1405                    (other.flags() & STATIC) == 0) {
  1406             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1407                       cannotOverride(m, other));
  1408             return;
  1411         // Error if instance method overrides static or final
  1412         // method (JLS 8.4.6.1).
  1413         if ((other.flags() & FINAL) != 0 ||
  1414                  (m.flags() & STATIC) == 0 &&
  1415                  (other.flags() & STATIC) != 0) {
  1416             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1417                       cannotOverride(m, other),
  1418                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1419             return;
  1422         if ((m.owner.flags() & ANNOTATION) != 0) {
  1423             // handled in validateAnnotationMethod
  1424             return;
  1427         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1428         if ((origin.flags() & INTERFACE) == 0 &&
  1429                  protection(m.flags()) > protection(other.flags())) {
  1430             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1431                       cannotOverride(m, other),
  1432                       other.flags() == 0 ?
  1433                           Flag.PACKAGE :
  1434                           asFlagSet(other.flags() & AccessFlags));
  1435             return;
  1438         Type mt = types.memberType(origin.type, m);
  1439         Type ot = types.memberType(origin.type, other);
  1440         // Error if overriding result type is different
  1441         // (or, in the case of generics mode, not a subtype) of
  1442         // overridden result type. We have to rename any type parameters
  1443         // before comparing types.
  1444         List<Type> mtvars = mt.getTypeArguments();
  1445         List<Type> otvars = ot.getTypeArguments();
  1446         Type mtres = mt.getReturnType();
  1447         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1449         overrideWarner.clear();
  1450         boolean resultTypesOK =
  1451             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1452         if (!resultTypesOK) {
  1453             if (!allowCovariantReturns &&
  1454                 m.owner != origin &&
  1455                 m.owner.isSubClass(other.owner, types)) {
  1456                 // allow limited interoperability with covariant returns
  1457             } else {
  1458                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1459                           "override.incompatible.ret",
  1460                           cannotOverride(m, other),
  1461                           mtres, otres);
  1462                 return;
  1464         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1465             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1466                     "override.unchecked.ret",
  1467                     uncheckedOverrides(m, other),
  1468                     mtres, otres);
  1471         // Error if overriding method throws an exception not reported
  1472         // by overridden method.
  1473         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1474         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1475         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1476         if (unhandledErased.nonEmpty()) {
  1477             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1478                       "override.meth.doesnt.throw",
  1479                       cannotOverride(m, other),
  1480                       unhandledUnerased.head);
  1481             return;
  1483         else if (unhandledUnerased.nonEmpty()) {
  1484             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1485                           "override.unchecked.thrown",
  1486                          cannotOverride(m, other),
  1487                          unhandledUnerased.head);
  1488             return;
  1491         // Optional warning if varargs don't agree
  1492         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1493             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1494             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1495                         ((m.flags() & Flags.VARARGS) != 0)
  1496                         ? "override.varargs.missing"
  1497                         : "override.varargs.extra",
  1498                         varargsOverrides(m, other));
  1501         // Warn if instance method overrides bridge method (compiler spec ??)
  1502         if ((other.flags() & BRIDGE) != 0) {
  1503             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1504                         uncheckedOverrides(m, other));
  1507         // Warn if a deprecated method overridden by a non-deprecated one.
  1508         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1509             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1512     // where
  1513         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1514             // If the method, m, is defined in an interface, then ignore the issue if the method
  1515             // is only inherited via a supertype and also implemented in the supertype,
  1516             // because in that case, we will rediscover the issue when examining the method
  1517             // in the supertype.
  1518             // If the method, m, is not defined in an interface, then the only time we need to
  1519             // address the issue is when the method is the supertype implemementation: any other
  1520             // case, we will have dealt with when examining the supertype classes
  1521             ClassSymbol mc = m.enclClass();
  1522             Type st = types.supertype(origin.type);
  1523             if (st.tag != CLASS)
  1524                 return true;
  1525             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1527             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1528                 List<Type> intfs = types.interfaces(origin.type);
  1529                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1531             else
  1532                 return (stimpl != m);
  1536     // used to check if there were any unchecked conversions
  1537     Warner overrideWarner = new Warner();
  1539     /** Check that a class does not inherit two concrete methods
  1540      *  with the same signature.
  1541      *  @param pos          Position to be used for error reporting.
  1542      *  @param site         The class type to be checked.
  1543      */
  1544     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1545         Type sup = types.supertype(site);
  1546         if (sup.tag != CLASS) return;
  1548         for (Type t1 = sup;
  1549              t1.tsym.type.isParameterized();
  1550              t1 = types.supertype(t1)) {
  1551             for (Scope.Entry e1 = t1.tsym.members().elems;
  1552                  e1 != null;
  1553                  e1 = e1.sibling) {
  1554                 Symbol s1 = e1.sym;
  1555                 if (s1.kind != MTH ||
  1556                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1557                     !s1.isInheritedIn(site.tsym, types) ||
  1558                     ((MethodSymbol)s1).implementation(site.tsym,
  1559                                                       types,
  1560                                                       true) != s1)
  1561                     continue;
  1562                 Type st1 = types.memberType(t1, s1);
  1563                 int s1ArgsLength = st1.getParameterTypes().length();
  1564                 if (st1 == s1.type) continue;
  1566                 for (Type t2 = sup;
  1567                      t2.tag == CLASS;
  1568                      t2 = types.supertype(t2)) {
  1569                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1570                          e2.scope != null;
  1571                          e2 = e2.next()) {
  1572                         Symbol s2 = e2.sym;
  1573                         if (s2 == s1 ||
  1574                             s2.kind != MTH ||
  1575                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1576                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1577                             !s2.isInheritedIn(site.tsym, types) ||
  1578                             ((MethodSymbol)s2).implementation(site.tsym,
  1579                                                               types,
  1580                                                               true) != s2)
  1581                             continue;
  1582                         Type st2 = types.memberType(t2, s2);
  1583                         if (types.overrideEquivalent(st1, st2))
  1584                             log.error(pos, "concrete.inheritance.conflict",
  1585                                       s1, t1, s2, t2, sup);
  1592     /** Check that classes (or interfaces) do not each define an abstract
  1593      *  method with same name and arguments but incompatible return types.
  1594      *  @param pos          Position to be used for error reporting.
  1595      *  @param t1           The first argument type.
  1596      *  @param t2           The second argument type.
  1597      */
  1598     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1599                                             Type t1,
  1600                                             Type t2) {
  1601         return checkCompatibleAbstracts(pos, t1, t2,
  1602                                         types.makeCompoundType(t1, t2));
  1605     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1606                                             Type t1,
  1607                                             Type t2,
  1608                                             Type site) {
  1609         return firstIncompatibility(pos, t1, t2, site) == null;
  1612     /** Return the first method which is defined with same args
  1613      *  but different return types in two given interfaces, or null if none
  1614      *  exists.
  1615      *  @param t1     The first type.
  1616      *  @param t2     The second type.
  1617      *  @param site   The most derived type.
  1618      *  @returns symbol from t2 that conflicts with one in t1.
  1619      */
  1620     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1621         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1622         closure(t1, interfaces1);
  1623         Map<TypeSymbol,Type> interfaces2;
  1624         if (t1 == t2)
  1625             interfaces2 = interfaces1;
  1626         else
  1627             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1629         for (Type t3 : interfaces1.values()) {
  1630             for (Type t4 : interfaces2.values()) {
  1631                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1632                 if (s != null) return s;
  1635         return null;
  1638     /** Compute all the supertypes of t, indexed by type symbol. */
  1639     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1640         if (t.tag != CLASS) return;
  1641         if (typeMap.put(t.tsym, t) == null) {
  1642             closure(types.supertype(t), typeMap);
  1643             for (Type i : types.interfaces(t))
  1644                 closure(i, typeMap);
  1648     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1649     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1650         if (t.tag != CLASS) return;
  1651         if (typesSkip.get(t.tsym) != null) return;
  1652         if (typeMap.put(t.tsym, t) == null) {
  1653             closure(types.supertype(t), typesSkip, typeMap);
  1654             for (Type i : types.interfaces(t))
  1655                 closure(i, typesSkip, typeMap);
  1659     /** Return the first method in t2 that conflicts with a method from t1. */
  1660     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1661         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1662             Symbol s1 = e1.sym;
  1663             Type st1 = null;
  1664             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1665             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1666             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1667             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1668                 Symbol s2 = e2.sym;
  1669                 if (s1 == s2) continue;
  1670                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1671                 if (st1 == null) st1 = types.memberType(t1, s1);
  1672                 Type st2 = types.memberType(t2, s2);
  1673                 if (types.overrideEquivalent(st1, st2)) {
  1674                     List<Type> tvars1 = st1.getTypeArguments();
  1675                     List<Type> tvars2 = st2.getTypeArguments();
  1676                     Type rt1 = st1.getReturnType();
  1677                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1678                     boolean compat =
  1679                         types.isSameType(rt1, rt2) ||
  1680                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1681                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1682                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1683                          checkCommonOverriderIn(s1,s2,site);
  1684                     if (!compat) {
  1685                         log.error(pos, "types.incompatible.diff.ret",
  1686                             t1, t2, s2.name +
  1687                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1688                         return s2;
  1690                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1691                         !checkCommonOverriderIn(s1, s2, site)) {
  1692                     log.error(pos,
  1693                             "name.clash.same.erasure.no.override",
  1694                             s1, s1.location(),
  1695                             s2, s2.location());
  1696                     return s2;
  1700         return null;
  1702     //WHERE
  1703     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1704         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1705         Type st1 = types.memberType(site, s1);
  1706         Type st2 = types.memberType(site, s2);
  1707         closure(site, supertypes);
  1708         for (Type t : supertypes.values()) {
  1709             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1710                 Symbol s3 = e.sym;
  1711                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1712                 Type st3 = types.memberType(site,s3);
  1713                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1714                     if (s3.owner == site.tsym) {
  1715                         return true;
  1717                     List<Type> tvars1 = st1.getTypeArguments();
  1718                     List<Type> tvars2 = st2.getTypeArguments();
  1719                     List<Type> tvars3 = st3.getTypeArguments();
  1720                     Type rt1 = st1.getReturnType();
  1721                     Type rt2 = st2.getReturnType();
  1722                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1723                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1724                     boolean compat =
  1725                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1726                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1727                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1728                     if (compat)
  1729                         return true;
  1733         return false;
  1736     /** Check that a given method conforms with any method it overrides.
  1737      *  @param tree         The tree from which positions are extracted
  1738      *                      for errors.
  1739      *  @param m            The overriding method.
  1740      */
  1741     void checkOverride(JCTree tree, MethodSymbol m) {
  1742         ClassSymbol origin = (ClassSymbol)m.owner;
  1743         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1744             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1745                 log.error(tree.pos(), "enum.no.finalize");
  1746                 return;
  1748         for (Type t = origin.type; t.tag == CLASS;
  1749              t = types.supertype(t)) {
  1750             if (t != origin.type) {
  1751                 checkOverride(tree, t, origin, m);
  1753             for (Type t2 : types.interfaces(t)) {
  1754                 checkOverride(tree, t2, origin, m);
  1759     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1760         TypeSymbol c = site.tsym;
  1761         Scope.Entry e = c.members().lookup(m.name);
  1762         while (e.scope != null) {
  1763             if (m.overrides(e.sym, origin, types, false)) {
  1764                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1765                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1768             e = e.next();
  1772     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1773         ClashFilter cf = new ClashFilter(origin.type);
  1774         return (cf.accepts(s1) &&
  1775                 cf.accepts(s2) &&
  1776                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1780     /** Check that all abstract members of given class have definitions.
  1781      *  @param pos          Position to be used for error reporting.
  1782      *  @param c            The class.
  1783      */
  1784     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1785         try {
  1786             MethodSymbol undef = firstUndef(c, c);
  1787             if (undef != null) {
  1788                 if ((c.flags() & ENUM) != 0 &&
  1789                     types.supertype(c.type).tsym == syms.enumSym &&
  1790                     (c.flags() & FINAL) == 0) {
  1791                     // add the ABSTRACT flag to an enum
  1792                     c.flags_field |= ABSTRACT;
  1793                 } else {
  1794                     MethodSymbol undef1 =
  1795                         new MethodSymbol(undef.flags(), undef.name,
  1796                                          types.memberType(c.type, undef), undef.owner);
  1797                     log.error(pos, "does.not.override.abstract",
  1798                               c, undef1, undef1.location());
  1801         } catch (CompletionFailure ex) {
  1802             completionError(pos, ex);
  1805 //where
  1806         /** Return first abstract member of class `c' that is not defined
  1807          *  in `impl', null if there is none.
  1808          */
  1809         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1810             MethodSymbol undef = null;
  1811             // Do not bother to search in classes that are not abstract,
  1812             // since they cannot have abstract members.
  1813             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1814                 Scope s = c.members();
  1815                 for (Scope.Entry e = s.elems;
  1816                      undef == null && e != null;
  1817                      e = e.sibling) {
  1818                     if (e.sym.kind == MTH &&
  1819                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1820                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1821                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1822                         if (implmeth == null || implmeth == absmeth)
  1823                             undef = absmeth;
  1826                 if (undef == null) {
  1827                     Type st = types.supertype(c.type);
  1828                     if (st.tag == CLASS)
  1829                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1831                 for (List<Type> l = types.interfaces(c.type);
  1832                      undef == null && l.nonEmpty();
  1833                      l = l.tail) {
  1834                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1837             return undef;
  1840     void checkNonCyclicDecl(JCClassDecl tree) {
  1841         CycleChecker cc = new CycleChecker();
  1842         cc.scan(tree);
  1843         if (!cc.errorFound && !cc.partialCheck) {
  1844             tree.sym.flags_field |= ACYCLIC;
  1848     class CycleChecker extends TreeScanner {
  1850         List<Symbol> seenClasses = List.nil();
  1851         boolean errorFound = false;
  1852         boolean partialCheck = false;
  1854         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  1855             if (sym != null && sym.kind == TYP) {
  1856                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  1857                 if (classEnv != null) {
  1858                     DiagnosticSource prevSource = log.currentSource();
  1859                     try {
  1860                         log.useSource(classEnv.toplevel.sourcefile);
  1861                         scan(classEnv.tree);
  1863                     finally {
  1864                         log.useSource(prevSource.getFile());
  1866                 } else if (sym.kind == TYP) {
  1867                     checkClass(pos, sym, List.<JCTree>nil());
  1869             } else {
  1870                 //not completed yet
  1871                 partialCheck = true;
  1875         @Override
  1876         public void visitSelect(JCFieldAccess tree) {
  1877             super.visitSelect(tree);
  1878             checkSymbol(tree.pos(), tree.sym);
  1881         @Override
  1882         public void visitIdent(JCIdent tree) {
  1883             checkSymbol(tree.pos(), tree.sym);
  1886         @Override
  1887         public void visitTypeApply(JCTypeApply tree) {
  1888             scan(tree.clazz);
  1891         @Override
  1892         public void visitTypeArray(JCArrayTypeTree tree) {
  1893             scan(tree.elemtype);
  1896         @Override
  1897         public void visitClassDef(JCClassDecl tree) {
  1898             List<JCTree> supertypes = List.nil();
  1899             if (tree.getExtendsClause() != null) {
  1900                 supertypes = supertypes.prepend(tree.getExtendsClause());
  1902             if (tree.getImplementsClause() != null) {
  1903                 for (JCTree intf : tree.getImplementsClause()) {
  1904                     supertypes = supertypes.prepend(intf);
  1907             checkClass(tree.pos(), tree.sym, supertypes);
  1910         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  1911             if ((c.flags_field & ACYCLIC) != 0)
  1912                 return;
  1913             if (seenClasses.contains(c)) {
  1914                 errorFound = true;
  1915                 noteCyclic(pos, (ClassSymbol)c);
  1916             } else if (!c.type.isErroneous()) {
  1917                 try {
  1918                     seenClasses = seenClasses.prepend(c);
  1919                     if (c.type.tag == CLASS) {
  1920                         if (supertypes.nonEmpty()) {
  1921                             scan(supertypes);
  1923                         else {
  1924                             ClassType ct = (ClassType)c.type;
  1925                             if (ct.supertype_field == null ||
  1926                                     ct.interfaces_field == null) {
  1927                                 //not completed yet
  1928                                 partialCheck = true;
  1929                                 return;
  1931                             checkSymbol(pos, ct.supertype_field.tsym);
  1932                             for (Type intf : ct.interfaces_field) {
  1933                                 checkSymbol(pos, intf.tsym);
  1936                         if (c.owner.kind == TYP) {
  1937                             checkSymbol(pos, c.owner);
  1940                 } finally {
  1941                     seenClasses = seenClasses.tail;
  1947     /** Check for cyclic references. Issue an error if the
  1948      *  symbol of the type referred to has a LOCKED flag set.
  1950      *  @param pos      Position to be used for error reporting.
  1951      *  @param t        The type referred to.
  1952      */
  1953     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1954         checkNonCyclicInternal(pos, t);
  1958     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1959         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1962     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1963         final TypeVar tv;
  1964         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1965             return;
  1966         if (seen.contains(t)) {
  1967             tv = (TypeVar)t;
  1968             tv.bound = types.createErrorType(t);
  1969             log.error(pos, "cyclic.inheritance", t);
  1970         } else if (t.tag == TYPEVAR) {
  1971             tv = (TypeVar)t;
  1972             seen = seen.prepend(tv);
  1973             for (Type b : types.getBounds(tv))
  1974                 checkNonCyclic1(pos, b, seen);
  1978     /** Check for cyclic references. Issue an error if the
  1979      *  symbol of the type referred to has a LOCKED flag set.
  1981      *  @param pos      Position to be used for error reporting.
  1982      *  @param t        The type referred to.
  1983      *  @returns        True if the check completed on all attributed classes
  1984      */
  1985     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1986         boolean complete = true; // was the check complete?
  1987         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1988         Symbol c = t.tsym;
  1989         if ((c.flags_field & ACYCLIC) != 0) return true;
  1991         if ((c.flags_field & LOCKED) != 0) {
  1992             noteCyclic(pos, (ClassSymbol)c);
  1993         } else if (!c.type.isErroneous()) {
  1994             try {
  1995                 c.flags_field |= LOCKED;
  1996                 if (c.type.tag == CLASS) {
  1997                     ClassType clazz = (ClassType)c.type;
  1998                     if (clazz.interfaces_field != null)
  1999                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  2000                             complete &= checkNonCyclicInternal(pos, l.head);
  2001                     if (clazz.supertype_field != null) {
  2002                         Type st = clazz.supertype_field;
  2003                         if (st != null && st.tag == CLASS)
  2004                             complete &= checkNonCyclicInternal(pos, st);
  2006                     if (c.owner.kind == TYP)
  2007                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2009             } finally {
  2010                 c.flags_field &= ~LOCKED;
  2013         if (complete)
  2014             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2015         if (complete) c.flags_field |= ACYCLIC;
  2016         return complete;
  2019     /** Note that we found an inheritance cycle. */
  2020     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2021         log.error(pos, "cyclic.inheritance", c);
  2022         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2023             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2024         Type st = types.supertype(c.type);
  2025         if (st.tag == CLASS)
  2026             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2027         c.type = types.createErrorType(c, c.type);
  2028         c.flags_field |= ACYCLIC;
  2031     /** Check that all methods which implement some
  2032      *  method conform to the method they implement.
  2033      *  @param tree         The class definition whose members are checked.
  2034      */
  2035     void checkImplementations(JCClassDecl tree) {
  2036         checkImplementations(tree, tree.sym);
  2038 //where
  2039         /** Check that all methods which implement some
  2040          *  method in `ic' conform to the method they implement.
  2041          */
  2042         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  2043             ClassSymbol origin = tree.sym;
  2044             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2045                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2046                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2047                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2048                         if (e.sym.kind == MTH &&
  2049                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2050                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2051                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2052                             if (implmeth != null && implmeth != absmeth &&
  2053                                 (implmeth.owner.flags() & INTERFACE) ==
  2054                                 (origin.flags() & INTERFACE)) {
  2055                                 // don't check if implmeth is in a class, yet
  2056                                 // origin is an interface. This case arises only
  2057                                 // if implmeth is declared in Object. The reason is
  2058                                 // that interfaces really don't inherit from
  2059                                 // Object it's just that the compiler represents
  2060                                 // things that way.
  2061                                 checkOverride(tree, implmeth, absmeth, origin);
  2069     /** Check that all abstract methods implemented by a class are
  2070      *  mutually compatible.
  2071      *  @param pos          Position to be used for error reporting.
  2072      *  @param c            The class whose interfaces are checked.
  2073      */
  2074     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2075         List<Type> supertypes = types.interfaces(c);
  2076         Type supertype = types.supertype(c);
  2077         if (supertype.tag == CLASS &&
  2078             (supertype.tsym.flags() & ABSTRACT) != 0)
  2079             supertypes = supertypes.prepend(supertype);
  2080         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2081             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2082                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2083                 return;
  2084             for (List<Type> m = supertypes; m != l; m = m.tail)
  2085                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2086                     return;
  2088         checkCompatibleConcretes(pos, c);
  2091     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2092         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2093             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2094                 // VM allows methods and variables with differing types
  2095                 if (sym.kind == e.sym.kind &&
  2096                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2097                     sym != e.sym &&
  2098                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2099                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2100                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2101                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2102                     return;
  2108     /** Check that all non-override equivalent methods accessible from 'site'
  2109      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2111      *  @param pos  Position to be used for error reporting.
  2112      *  @param site The class whose methods are checked.
  2113      *  @param sym  The method symbol to be checked.
  2114      */
  2115     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2116          ClashFilter cf = new ClashFilter(site);
  2117         //for each method m1 that is overridden (directly or indirectly)
  2118         //by method 'sym' in 'site'...
  2119         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2120             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2121              //...check each method m2 that is a member of 'site'
  2122              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2123                 if (m2 == m1) continue;
  2124                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2125                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2126                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
  2127                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2128                     sym.flags_field |= CLASH;
  2129                     String key = m1 == sym ?
  2130                             "name.clash.same.erasure.no.override" :
  2131                             "name.clash.same.erasure.no.override.1";
  2132                     log.error(pos,
  2133                             key,
  2134                             sym, sym.location(),
  2135                             m2, m2.location(),
  2136                             m1, m1.location());
  2137                     return;
  2145     /** Check that all static methods accessible from 'site' are
  2146      *  mutually compatible (JLS 8.4.8).
  2148      *  @param pos  Position to be used for error reporting.
  2149      *  @param site The class whose methods are checked.
  2150      *  @param sym  The method symbol to be checked.
  2151      */
  2152     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2153         ClashFilter cf = new ClashFilter(site);
  2154         //for each method m1 that is a member of 'site'...
  2155         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2156             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2157             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2158             if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
  2159                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2160                 log.error(pos,
  2161                         "name.clash.same.erasure.no.hide",
  2162                         sym, sym.location(),
  2163                         s, s.location());
  2164                 return;
  2169      //where
  2170      private class ClashFilter implements Filter<Symbol> {
  2172          Type site;
  2174          ClashFilter(Type site) {
  2175              this.site = site;
  2178          boolean shouldSkip(Symbol s) {
  2179              return (s.flags() & CLASH) != 0 &&
  2180                 s.owner == site.tsym;
  2183          public boolean accepts(Symbol s) {
  2184              return s.kind == MTH &&
  2185                      (s.flags() & SYNTHETIC) == 0 &&
  2186                      !shouldSkip(s) &&
  2187                      s.isInheritedIn(site.tsym, types) &&
  2188                      !s.isConstructor();
  2192     /** Report a conflict between a user symbol and a synthetic symbol.
  2193      */
  2194     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2195         if (!sym.type.isErroneous()) {
  2196             if (warnOnSyntheticConflicts) {
  2197                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2199             else {
  2200                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2205     /** Check that class c does not implement directly or indirectly
  2206      *  the same parameterized interface with two different argument lists.
  2207      *  @param pos          Position to be used for error reporting.
  2208      *  @param type         The type whose interfaces are checked.
  2209      */
  2210     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2211         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2213 //where
  2214         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2215          *  with their class symbol as key and their type as value. Make
  2216          *  sure no class is entered with two different types.
  2217          */
  2218         void checkClassBounds(DiagnosticPosition pos,
  2219                               Map<TypeSymbol,Type> seensofar,
  2220                               Type type) {
  2221             if (type.isErroneous()) return;
  2222             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2223                 Type it = l.head;
  2224                 Type oldit = seensofar.put(it.tsym, it);
  2225                 if (oldit != null) {
  2226                     List<Type> oldparams = oldit.allparams();
  2227                     List<Type> newparams = it.allparams();
  2228                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2229                         log.error(pos, "cant.inherit.diff.arg",
  2230                                   it.tsym, Type.toString(oldparams),
  2231                                   Type.toString(newparams));
  2233                 checkClassBounds(pos, seensofar, it);
  2235             Type st = types.supertype(type);
  2236             if (st != null) checkClassBounds(pos, seensofar, st);
  2239     /** Enter interface into into set.
  2240      *  If it existed already, issue a "repeated interface" error.
  2241      */
  2242     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2243         if (its.contains(it))
  2244             log.error(pos, "repeated.interface");
  2245         else {
  2246             its.add(it);
  2250 /* *************************************************************************
  2251  * Check annotations
  2252  **************************************************************************/
  2254     /**
  2255      * Recursively validate annotations values
  2256      */
  2257     void validateAnnotationTree(JCTree tree) {
  2258         class AnnotationValidator extends TreeScanner {
  2259             @Override
  2260             public void visitAnnotation(JCAnnotation tree) {
  2261                 if (!tree.type.isErroneous()) {
  2262                     super.visitAnnotation(tree);
  2263                     validateAnnotation(tree);
  2267         tree.accept(new AnnotationValidator());
  2270     /** Annotation types are restricted to primitives, String, an
  2271      *  enum, an annotation, Class, Class<?>, Class<? extends
  2272      *  Anything>, arrays of the preceding.
  2273      */
  2274     void validateAnnotationType(JCTree restype) {
  2275         // restype may be null if an error occurred, so don't bother validating it
  2276         if (restype != null) {
  2277             validateAnnotationType(restype.pos(), restype.type);
  2281     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2282         if (type.isPrimitive()) return;
  2283         if (types.isSameType(type, syms.stringType)) return;
  2284         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2285         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2286         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2287         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2288             validateAnnotationType(pos, types.elemtype(type));
  2289             return;
  2291         log.error(pos, "invalid.annotation.member.type");
  2294     /**
  2295      * "It is also a compile-time error if any method declared in an
  2296      * annotation type has a signature that is override-equivalent to
  2297      * that of any public or protected method declared in class Object
  2298      * or in the interface annotation.Annotation."
  2300      * @jls 9.6 Annotation Types
  2301      */
  2302     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2303         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2304             Scope s = sup.tsym.members();
  2305             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2306                 if (e.sym.kind == MTH &&
  2307                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2308                     types.overrideEquivalent(m.type, e.sym.type))
  2309                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2314     /** Check the annotations of a symbol.
  2315      */
  2316     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2317         if (skipAnnotations) return;
  2318         for (JCAnnotation a : annotations)
  2319             validateAnnotation(a, s);
  2322     /** Check an annotation of a symbol.
  2323      */
  2324     public void validateAnnotation(JCAnnotation a, Symbol s) {
  2325         validateAnnotationTree(a);
  2327         if (!annotationApplicable(a, s))
  2328             log.error(a.pos(), "annotation.type.not.applicable");
  2330         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2331             if (!isOverrider(s))
  2332                 log.error(a.pos(), "method.does.not.override.superclass");
  2336     /** Is s a method symbol that overrides a method in a superclass? */
  2337     boolean isOverrider(Symbol s) {
  2338         if (s.kind != MTH || s.isStatic())
  2339             return false;
  2340         MethodSymbol m = (MethodSymbol)s;
  2341         TypeSymbol owner = (TypeSymbol)m.owner;
  2342         for (Type sup : types.closure(owner.type)) {
  2343             if (sup == owner.type)
  2344                 continue; // skip "this"
  2345             Scope scope = sup.tsym.members();
  2346             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2347                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2348                     return true;
  2351         return false;
  2354     /** Is the annotation applicable to the symbol? */
  2355     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2356         Attribute.Compound atTarget =
  2357             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2358         if (atTarget == null) return true;
  2359         Attribute atValue = atTarget.member(names.value);
  2360         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2361         Attribute.Array arr = (Attribute.Array) atValue;
  2362         for (Attribute app : arr.values) {
  2363             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2364             Attribute.Enum e = (Attribute.Enum) app;
  2365             if (e.value.name == names.TYPE)
  2366                 { if (s.kind == TYP) return true; }
  2367             else if (e.value.name == names.FIELD)
  2368                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2369             else if (e.value.name == names.METHOD)
  2370                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2371             else if (e.value.name == names.PARAMETER)
  2372                 { if (s.kind == VAR &&
  2373                       s.owner.kind == MTH &&
  2374                       (s.flags() & PARAMETER) != 0)
  2375                     return true;
  2377             else if (e.value.name == names.CONSTRUCTOR)
  2378                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2379             else if (e.value.name == names.LOCAL_VARIABLE)
  2380                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2381                       (s.flags() & PARAMETER) == 0)
  2382                     return true;
  2384             else if (e.value.name == names.ANNOTATION_TYPE)
  2385                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2386                     return true;
  2388             else if (e.value.name == names.PACKAGE)
  2389                 { if (s.kind == PCK) return true; }
  2390             else if (e.value.name == names.TYPE_USE)
  2391                 { if (s.kind == TYP ||
  2392                       s.kind == VAR ||
  2393                       (s.kind == MTH && !s.isConstructor() &&
  2394                        s.type.getReturnType().tag != VOID))
  2395                     return true;
  2397             else
  2398                 return true; // recovery
  2400         return false;
  2403     /** Check an annotation value.
  2404      */
  2405     public void validateAnnotation(JCAnnotation a) {
  2406         // collect an inventory of the members (sorted alphabetically)
  2407         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2408             public int compare(Symbol t, Symbol t1) {
  2409                 return t.name.compareTo(t1.name);
  2411         });
  2412         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2413              e != null;
  2414              e = e.sibling)
  2415             if (e.sym.kind == MTH)
  2416                 members.add((MethodSymbol) e.sym);
  2418         // count them off as they're annotated
  2419         for (JCTree arg : a.args) {
  2420             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2421             JCAssign assign = (JCAssign) arg;
  2422             Symbol m = TreeInfo.symbol(assign.lhs);
  2423             if (m == null || m.type.isErroneous()) continue;
  2424             if (!members.remove(m))
  2425                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2426                           m.name, a.type);
  2429         // all the remaining ones better have default values
  2430         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2431         for (MethodSymbol m : members) {
  2432             if (m.defaultValue == null && !m.type.isErroneous()) {
  2433                 missingDefaults.append(m.name);
  2436         if (missingDefaults.nonEmpty()) {
  2437             String key = (missingDefaults.size() > 1)
  2438                     ? "annotation.missing.default.value.1"
  2439                     : "annotation.missing.default.value";
  2440             log.error(a.pos(), key, a.type, missingDefaults);
  2443         // special case: java.lang.annotation.Target must not have
  2444         // repeated values in its value member
  2445         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2446             a.args.tail == null)
  2447             return;
  2449         if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
  2450         JCAssign assign = (JCAssign) a.args.head;
  2451         Symbol m = TreeInfo.symbol(assign.lhs);
  2452         if (m.name != names.value) return;
  2453         JCTree rhs = assign.rhs;
  2454         if (!rhs.hasTag(NEWARRAY)) return;
  2455         JCNewArray na = (JCNewArray) rhs;
  2456         Set<Symbol> targets = new HashSet<Symbol>();
  2457         for (JCTree elem : na.elems) {
  2458             if (!targets.add(TreeInfo.symbol(elem))) {
  2459                 log.error(elem.pos(), "repeated.annotation.target");
  2464     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2465         if (allowAnnotations &&
  2466             lint.isEnabled(LintCategory.DEP_ANN) &&
  2467             (s.flags() & DEPRECATED) != 0 &&
  2468             !syms.deprecatedType.isErroneous() &&
  2469             s.attribute(syms.deprecatedType.tsym) == null) {
  2470             log.warning(LintCategory.DEP_ANN,
  2471                     pos, "missing.deprecated.annotation");
  2475     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2476         if ((s.flags() & DEPRECATED) != 0 &&
  2477                 (other.flags() & DEPRECATED) == 0 &&
  2478                 s.outermostClass() != other.outermostClass()) {
  2479             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2480                 @Override
  2481                 public void report() {
  2482                     warnDeprecated(pos, s);
  2484             });
  2488     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2489         if ((s.flags() & PROPRIETARY) != 0) {
  2490             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2491                 public void report() {
  2492                     if (enableSunApiLintControl)
  2493                       warnSunApi(pos, "sun.proprietary", s);
  2494                     else
  2495                       log.strictWarning(pos, "sun.proprietary", s);
  2497             });
  2501 /* *************************************************************************
  2502  * Check for recursive annotation elements.
  2503  **************************************************************************/
  2505     /** Check for cycles in the graph of annotation elements.
  2506      */
  2507     void checkNonCyclicElements(JCClassDecl tree) {
  2508         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2509         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2510         try {
  2511             tree.sym.flags_field |= LOCKED;
  2512             for (JCTree def : tree.defs) {
  2513                 if (!def.hasTag(METHODDEF)) continue;
  2514                 JCMethodDecl meth = (JCMethodDecl)def;
  2515                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2517         } finally {
  2518             tree.sym.flags_field &= ~LOCKED;
  2519             tree.sym.flags_field |= ACYCLIC_ANN;
  2523     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2524         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2525             return;
  2526         if ((tsym.flags_field & LOCKED) != 0) {
  2527             log.error(pos, "cyclic.annotation.element");
  2528             return;
  2530         try {
  2531             tsym.flags_field |= LOCKED;
  2532             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2533                 Symbol s = e.sym;
  2534                 if (s.kind != Kinds.MTH)
  2535                     continue;
  2536                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2538         } finally {
  2539             tsym.flags_field &= ~LOCKED;
  2540             tsym.flags_field |= ACYCLIC_ANN;
  2544     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2545         switch (type.tag) {
  2546         case TypeTags.CLASS:
  2547             if ((type.tsym.flags() & ANNOTATION) != 0)
  2548                 checkNonCyclicElementsInternal(pos, type.tsym);
  2549             break;
  2550         case TypeTags.ARRAY:
  2551             checkAnnotationResType(pos, types.elemtype(type));
  2552             break;
  2553         default:
  2554             break; // int etc
  2558 /* *************************************************************************
  2559  * Check for cycles in the constructor call graph.
  2560  **************************************************************************/
  2562     /** Check for cycles in the graph of constructors calling other
  2563      *  constructors.
  2564      */
  2565     void checkCyclicConstructors(JCClassDecl tree) {
  2566         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2568         // enter each constructor this-call into the map
  2569         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2570             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2571             if (app == null) continue;
  2572             JCMethodDecl meth = (JCMethodDecl) l.head;
  2573             if (TreeInfo.name(app.meth) == names._this) {
  2574                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2575             } else {
  2576                 meth.sym.flags_field |= ACYCLIC;
  2580         // Check for cycles in the map
  2581         Symbol[] ctors = new Symbol[0];
  2582         ctors = callMap.keySet().toArray(ctors);
  2583         for (Symbol caller : ctors) {
  2584             checkCyclicConstructor(tree, caller, callMap);
  2588     /** Look in the map to see if the given constructor is part of a
  2589      *  call cycle.
  2590      */
  2591     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2592                                         Map<Symbol,Symbol> callMap) {
  2593         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2594             if ((ctor.flags_field & LOCKED) != 0) {
  2595                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2596                           "recursive.ctor.invocation");
  2597             } else {
  2598                 ctor.flags_field |= LOCKED;
  2599                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2600                 ctor.flags_field &= ~LOCKED;
  2602             ctor.flags_field |= ACYCLIC;
  2606 /* *************************************************************************
  2607  * Miscellaneous
  2608  **************************************************************************/
  2610     /**
  2611      * Return the opcode of the operator but emit an error if it is an
  2612      * error.
  2613      * @param pos        position for error reporting.
  2614      * @param operator   an operator
  2615      * @param tag        a tree tag
  2616      * @param left       type of left hand side
  2617      * @param right      type of right hand side
  2618      */
  2619     int checkOperator(DiagnosticPosition pos,
  2620                        OperatorSymbol operator,
  2621                        JCTree.Tag tag,
  2622                        Type left,
  2623                        Type right) {
  2624         if (operator.opcode == ByteCodes.error) {
  2625             log.error(pos,
  2626                       "operator.cant.be.applied.1",
  2627                       treeinfo.operatorName(tag),
  2628                       left, right);
  2630         return operator.opcode;
  2634     /**
  2635      *  Check for division by integer constant zero
  2636      *  @param pos           Position for error reporting.
  2637      *  @param operator      The operator for the expression
  2638      *  @param operand       The right hand operand for the expression
  2639      */
  2640     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2641         if (operand.constValue() != null
  2642             && lint.isEnabled(LintCategory.DIVZERO)
  2643             && operand.tag <= LONG
  2644             && ((Number) (operand.constValue())).longValue() == 0) {
  2645             int opc = ((OperatorSymbol)operator).opcode;
  2646             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2647                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2648                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  2653     /**
  2654      * Check for empty statements after if
  2655      */
  2656     void checkEmptyIf(JCIf tree) {
  2657         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  2658                 lint.isEnabled(LintCategory.EMPTY))
  2659             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  2662     /** Check that symbol is unique in given scope.
  2663      *  @param pos           Position for error reporting.
  2664      *  @param sym           The symbol.
  2665      *  @param s             The scope.
  2666      */
  2667     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2668         if (sym.type.isErroneous())
  2669             return true;
  2670         if (sym.owner.name == names.any) return false;
  2671         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2672             if (sym != e.sym &&
  2673                     (e.sym.flags() & CLASH) == 0 &&
  2674                     sym.kind == e.sym.kind &&
  2675                     sym.name != names.error &&
  2676                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2677                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  2678                     varargsDuplicateError(pos, sym, e.sym);
  2679                     return true;
  2680                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  2681                     duplicateErasureError(pos, sym, e.sym);
  2682                     sym.flags_field |= CLASH;
  2683                     return true;
  2684                 } else {
  2685                     duplicateError(pos, e.sym);
  2686                     return false;
  2690         return true;
  2693     /** Report duplicate declaration error.
  2694      */
  2695     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2696         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2697             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2701     /** Check that single-type import is not already imported or top-level defined,
  2702      *  but make an exception for two single-type imports which denote the same type.
  2703      *  @param pos           Position for error reporting.
  2704      *  @param sym           The symbol.
  2705      *  @param s             The scope
  2706      */
  2707     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2708         return checkUniqueImport(pos, sym, s, false);
  2711     /** Check that static single-type import is not already imported or top-level defined,
  2712      *  but make an exception for two single-type imports which denote the same type.
  2713      *  @param pos           Position for error reporting.
  2714      *  @param sym           The symbol.
  2715      *  @param s             The scope
  2716      *  @param staticImport  Whether or not this was a static import
  2717      */
  2718     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2719         return checkUniqueImport(pos, sym, s, true);
  2722     /** Check that single-type import is not already imported or top-level defined,
  2723      *  but make an exception for two single-type imports which denote the same type.
  2724      *  @param pos           Position for error reporting.
  2725      *  @param sym           The symbol.
  2726      *  @param s             The scope.
  2727      *  @param staticImport  Whether or not this was a static import
  2728      */
  2729     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2730         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2731             // is encountered class entered via a class declaration?
  2732             boolean isClassDecl = e.scope == s;
  2733             if ((isClassDecl || sym != e.sym) &&
  2734                 sym.kind == e.sym.kind &&
  2735                 sym.name != names.error) {
  2736                 if (!e.sym.type.isErroneous()) {
  2737                     String what = e.sym.toString();
  2738                     if (!isClassDecl) {
  2739                         if (staticImport)
  2740                             log.error(pos, "already.defined.static.single.import", what);
  2741                         else
  2742                             log.error(pos, "already.defined.single.import", what);
  2744                     else if (sym != e.sym)
  2745                         log.error(pos, "already.defined.this.unit", what);
  2747                 return false;
  2750         return true;
  2753     /** Check that a qualified name is in canonical form (for import decls).
  2754      */
  2755     public void checkCanonical(JCTree tree) {
  2756         if (!isCanonical(tree))
  2757             log.error(tree.pos(), "import.requires.canonical",
  2758                       TreeInfo.symbol(tree));
  2760         // where
  2761         private boolean isCanonical(JCTree tree) {
  2762             while (tree.hasTag(SELECT)) {
  2763                 JCFieldAccess s = (JCFieldAccess) tree;
  2764                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2765                     return false;
  2766                 tree = s.selected;
  2768             return true;
  2771     private class ConversionWarner extends Warner {
  2772         final String uncheckedKey;
  2773         final Type found;
  2774         final Type expected;
  2775         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  2776             super(pos);
  2777             this.uncheckedKey = uncheckedKey;
  2778             this.found = found;
  2779             this.expected = expected;
  2782         @Override
  2783         public void warn(LintCategory lint) {
  2784             boolean warned = this.warned;
  2785             super.warn(lint);
  2786             if (warned) return; // suppress redundant diagnostics
  2787             switch (lint) {
  2788                 case UNCHECKED:
  2789                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  2790                     break;
  2791                 case VARARGS:
  2792                     if (method != null &&
  2793                             method.attribute(syms.trustMeType.tsym) != null &&
  2794                             isTrustMeAllowedOnMethod(method) &&
  2795                             !types.isReifiable(method.type.getParameterTypes().last())) {
  2796                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  2798                     break;
  2799                 default:
  2800                     throw new AssertionError("Unexpected lint: " + lint);
  2805     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2806         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2809     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2810         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial