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

Thu, 24 Jul 2008 11:12:41 +0100

author
mcimadamore
date
Thu, 24 Jul 2008 11:12:41 +0100
changeset 79
36df13bde238
parent 78
77dba8b57346
child 80
5c9cdeb740f2
permissions
-rw-r--r--

6594284: NPE thrown when calling a method on an intersection type
Summary: javac should report an error when the capture of an actual type parameter does not exist
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2008 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    31 import com.sun.tools.javac.code.*;
    32 import com.sun.tools.javac.jvm.*;
    33 import com.sun.tools.javac.tree.*;
    34 import com.sun.tools.javac.util.*;
    35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    36 import com.sun.tools.javac.util.List;
    38 import com.sun.tools.javac.tree.JCTree.*;
    39 import com.sun.tools.javac.code.Lint;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    44 import static com.sun.tools.javac.code.Flags.*;
    45 import static com.sun.tools.javac.code.Kinds.*;
    46 import static com.sun.tools.javac.code.TypeTags.*;
    48 /** Type checking helper class for the attribution phase.
    49  *
    50  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    51  *  you write code that depends on this, you do so at your own risk.
    52  *  This code and its internal interfaces are subject to change or
    53  *  deletion without notice.</b>
    54  */
    55 public class Check {
    56     protected static final Context.Key<Check> checkKey =
    57         new Context.Key<Check>();
    59     private final Name.Table names;
    60     private final Log log;
    61     private final Symtab syms;
    62     private final Infer infer;
    63     private final Target target;
    64     private final Source source;
    65     private final Types types;
    66     private final boolean skipAnnotations;
    67     private final TreeInfo treeinfo;
    69     // The set of lint options currently in effect. It is initialized
    70     // from the context, and then is set/reset as needed by Attr as it
    71     // visits all the various parts of the trees during attribution.
    72     private Lint lint;
    74     public static Check instance(Context context) {
    75         Check instance = context.get(checkKey);
    76         if (instance == null)
    77             instance = new Check(context);
    78         return instance;
    79     }
    81     protected Check(Context context) {
    82         context.put(checkKey, this);
    84         names = Name.Table.instance(context);
    85         log = Log.instance(context);
    86         syms = Symtab.instance(context);
    87         infer = Infer.instance(context);
    88         this.types = Types.instance(context);
    89         Options options = Options.instance(context);
    90         target = Target.instance(context);
    91         source = Source.instance(context);
    92         lint = Lint.instance(context);
    93         treeinfo = TreeInfo.instance(context);
    95         Source source = Source.instance(context);
    96         allowGenerics = source.allowGenerics();
    97         allowAnnotations = source.allowAnnotations();
    98         complexInference = options.get("-complexinference") != null;
    99         skipAnnotations = options.get("skipAnnotations") != null;
   101         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   102         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   103         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   105         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   106                 enforceMandatoryWarnings, "deprecated");
   107         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   108                 enforceMandatoryWarnings, "unchecked");
   109     }
   111     /** Switch: generics enabled?
   112      */
   113     boolean allowGenerics;
   115     /** Switch: annotations enabled?
   116      */
   117     boolean allowAnnotations;
   119     /** Switch: -complexinference option set?
   120      */
   121     boolean complexInference;
   123     /** A table mapping flat names of all compiled classes in this run to their
   124      *  symbols; maintained from outside.
   125      */
   126     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   128     /** A handler for messages about deprecated usage.
   129      */
   130     private MandatoryWarningHandler deprecationHandler;
   132     /** A handler for messages about unchecked or unsafe usage.
   133      */
   134     private MandatoryWarningHandler uncheckedHandler;
   137 /* *************************************************************************
   138  * Errors and Warnings
   139  **************************************************************************/
   141     Lint setLint(Lint newLint) {
   142         Lint prev = lint;
   143         lint = newLint;
   144         return prev;
   145     }
   147     /** Warn about deprecated symbol.
   148      *  @param pos        Position to be used for error reporting.
   149      *  @param sym        The deprecated symbol.
   150      */
   151     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   152         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   153             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   154     }
   156     /** Warn about unchecked operation.
   157      *  @param pos        Position to be used for error reporting.
   158      *  @param msg        A string describing the problem.
   159      */
   160     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   161         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   162             uncheckedHandler.report(pos, msg, args);
   163     }
   165     /**
   166      * Report any deferred diagnostics.
   167      */
   168     public void reportDeferredDiagnostics() {
   169         deprecationHandler.reportDeferredDiagnostic();
   170         uncheckedHandler.reportDeferredDiagnostic();
   171     }
   174     /** Report a failure to complete a class.
   175      *  @param pos        Position to be used for error reporting.
   176      *  @param ex         The failure to report.
   177      */
   178     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   179         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   180         if (ex instanceof ClassReader.BadClassFile) throw new Abort();
   181         else return syms.errType;
   182     }
   184     /** Report a type error.
   185      *  @param pos        Position to be used for error reporting.
   186      *  @param problem    A string describing the error.
   187      *  @param found      The type that was found.
   188      *  @param req        The type that was required.
   189      */
   190     Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
   191         log.error(pos, "prob.found.req",
   192                   problem, found, req);
   193         return syms.errType;
   194     }
   196     Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
   197         log.error(pos, "prob.found.req.1", problem, found, req, explanation);
   198         return syms.errType;
   199     }
   201     /** Report an error that wrong type tag was found.
   202      *  @param pos        Position to be used for error reporting.
   203      *  @param required   An internationalized string describing the type tag
   204      *                    required.
   205      *  @param found      The type that was found.
   206      */
   207     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   208         log.error(pos, "type.found.req", found, required);
   209         return syms.errType;
   210     }
   212     /** Report an error that symbol cannot be referenced before super
   213      *  has been called.
   214      *  @param pos        Position to be used for error reporting.
   215      *  @param sym        The referenced symbol.
   216      */
   217     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   218         log.error(pos, "cant.ref.before.ctor.called", sym);
   219     }
   221     /** Report duplicate declaration error.
   222      */
   223     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   224         if (!sym.type.isErroneous()) {
   225             log.error(pos, "already.defined", sym, sym.location());
   226         }
   227     }
   229     /** Report array/varargs duplicate declaration
   230      */
   231     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   232         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   233             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   234         }
   235     }
   237 /* ************************************************************************
   238  * duplicate declaration checking
   239  *************************************************************************/
   241     /** Check that variable does not hide variable with same name in
   242      *  immediately enclosing local scope.
   243      *  @param pos           Position for error reporting.
   244      *  @param v             The symbol.
   245      *  @param s             The scope.
   246      */
   247     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   248         if (s.next != null) {
   249             for (Scope.Entry e = s.next.lookup(v.name);
   250                  e.scope != null && e.sym.owner == v.owner;
   251                  e = e.next()) {
   252                 if (e.sym.kind == VAR &&
   253                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   254                     v.name != names.error) {
   255                     duplicateError(pos, e.sym);
   256                     return;
   257                 }
   258             }
   259         }
   260     }
   262     /** Check that a class or interface does not hide a class or
   263      *  interface with same name in immediately enclosing local scope.
   264      *  @param pos           Position for error reporting.
   265      *  @param c             The symbol.
   266      *  @param s             The scope.
   267      */
   268     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   269         if (s.next != null) {
   270             for (Scope.Entry e = s.next.lookup(c.name);
   271                  e.scope != null && e.sym.owner == c.owner;
   272                  e = e.next()) {
   273                 if (e.sym.kind == TYP &&
   274                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   275                     c.name != names.error) {
   276                     duplicateError(pos, e.sym);
   277                     return;
   278                 }
   279             }
   280         }
   281     }
   283     /** Check that class does not have the same name as one of
   284      *  its enclosing classes, or as a class defined in its enclosing scope.
   285      *  return true if class is unique in its enclosing scope.
   286      *  @param pos           Position for error reporting.
   287      *  @param name          The class name.
   288      *  @param s             The enclosing scope.
   289      */
   290     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   291         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   292             if (e.sym.kind == TYP && e.sym.name != names.error) {
   293                 duplicateError(pos, e.sym);
   294                 return false;
   295             }
   296         }
   297         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   298             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   299                 duplicateError(pos, sym);
   300                 return true;
   301             }
   302         }
   303         return true;
   304     }
   306 /* *************************************************************************
   307  * Class name generation
   308  **************************************************************************/
   310     /** Return name of local class.
   311      *  This is of the form    <enclClass> $ n <classname>
   312      *  where
   313      *    enclClass is the flat name of the enclosing class,
   314      *    classname is the simple name of the local class
   315      */
   316     Name localClassName(ClassSymbol c) {
   317         for (int i=1; ; i++) {
   318             Name flatname = names.
   319                 fromString("" + c.owner.enclClass().flatname +
   320                            target.syntheticNameChar() + i +
   321                            c.name);
   322             if (compiled.get(flatname) == null) return flatname;
   323         }
   324     }
   326 /* *************************************************************************
   327  * Type Checking
   328  **************************************************************************/
   330     /** Check that a given type is assignable to a given proto-type.
   331      *  If it is, return the type, otherwise return errType.
   332      *  @param pos        Position to be used for error reporting.
   333      *  @param found      The type that was found.
   334      *  @param req        The type that was required.
   335      */
   336     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   337         if (req.tag == ERROR)
   338             return req;
   339         if (found.tag == FORALL)
   340             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   341         if (req.tag == NONE)
   342             return found;
   343         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   344             return found;
   345         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   346             return typeError(pos, JCDiagnostic.fragment("possible.loss.of.precision"), found, req);
   347         if (found.isSuperBound()) {
   348             log.error(pos, "assignment.from.super-bound", found);
   349             return syms.errType;
   350         }
   351         if (req.isExtendsBound()) {
   352             log.error(pos, "assignment.to.extends-bound", req);
   353             return syms.errType;
   354         }
   355         return typeError(pos, JCDiagnostic.fragment("incompatible.types"), found, req);
   356     }
   358     /** Instantiate polymorphic type to some prototype, unless
   359      *  prototype is `anyPoly' in which case polymorphic type
   360      *  is returned unchanged.
   361      */
   362     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) {
   363         if (pt == Infer.anyPoly && complexInference) {
   364             return t;
   365         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   366             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   367             return instantiatePoly(pos, t, newpt, warn);
   368         } else if (pt.tag == ERROR) {
   369             return pt;
   370         } else {
   371             try {
   372                 return infer.instantiateExpr(t, pt, warn);
   373             } catch (Infer.NoInstanceException ex) {
   374                 if (ex.isAmbiguous) {
   375                     JCDiagnostic d = ex.getDiagnostic();
   376                     log.error(pos,
   377                               "undetermined.type" + (d!=null ? ".1" : ""),
   378                               t, d);
   379                     return syms.errType;
   380                 } else {
   381                     JCDiagnostic d = ex.getDiagnostic();
   382                     return typeError(pos,
   383                                      JCDiagnostic.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   384                                      t, pt);
   385                 }
   386             }
   387         }
   388     }
   390     /** Check that a given type can be cast to a given target type.
   391      *  Return the result of the cast.
   392      *  @param pos        Position to be used for error reporting.
   393      *  @param found      The type that is being cast.
   394      *  @param req        The target type of the cast.
   395      */
   396     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   397         if (found.tag == FORALL) {
   398             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   399             return req;
   400         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   401             return req;
   402         } else {
   403             return typeError(pos,
   404                              JCDiagnostic.fragment("inconvertible.types"),
   405                              found, req);
   406         }
   407     }
   408 //where
   409         /** Is type a type variable, or a (possibly multi-dimensional) array of
   410          *  type variables?
   411          */
   412         boolean isTypeVar(Type t) {
   413             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   414         }
   416     /** Check that a type is within some bounds.
   417      *
   418      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   419      *  type argument.
   420      *  @param pos           Position to be used for error reporting.
   421      *  @param a             The type that should be bounded by bs.
   422      *  @param bs            The bound.
   423      */
   424     private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
   425         if (a.tag == TYPEVAR && ((TypeVar)a).isCaptured()) {
   426             CapturedType ct = (CapturedType)a;
   427             boolean ok;
   428             if (ct.bound.isErroneous()) {//capture doesn't exist
   429                 ok = false;
   430             }
   431             else {
   432                 switch (ct.wildcard.kind) {
   433                     case EXTENDS:
   434                         ok = types.isCastable(bs.getUpperBound(),
   435                                 types.upperBound(a),
   436                                 Warner.noWarnings);
   437                         break;
   438                     case SUPER:
   439                         ok = !types.notSoftSubtype(types.lowerBound(a),
   440                                 bs.getUpperBound());
   441                         break;
   442                     case UNBOUND:
   443                         ok = true;
   444                         break;
   445                     default:
   446                         throw new AssertionError("Invalid bound kind");
   447                 }
   448             }
   449             if (!ok)
   450                 log.error(pos, "not.within.bounds", a);
   451         }
   452         else {
   453             a = types.upperBound(a);
   454             for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
   455                 if (!types.isSubtype(a, l.head)) {
   456                     log.error(pos, "not.within.bounds", a);
   457                     return;
   458                 }
   459             }
   460         }
   461     }
   463     /** Check that type is different from 'void'.
   464      *  @param pos           Position to be used for error reporting.
   465      *  @param t             The type to be checked.
   466      */
   467     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   468         if (t.tag == VOID) {
   469             log.error(pos, "void.not.allowed.here");
   470             return syms.errType;
   471         } else {
   472             return t;
   473         }
   474     }
   476     /** Check that type is a class or interface type.
   477      *  @param pos           Position to be used for error reporting.
   478      *  @param t             The type to be checked.
   479      */
   480     Type checkClassType(DiagnosticPosition pos, Type t) {
   481         if (t.tag != CLASS && t.tag != ERROR)
   482             return typeTagError(pos,
   483                                 JCDiagnostic.fragment("type.req.class"),
   484                                 (t.tag == TYPEVAR)
   485                                 ? JCDiagnostic.fragment("type.parameter", t)
   486                                 : t);
   487         else
   488             return t;
   489     }
   491     /** Check that type is a class or interface type.
   492      *  @param pos           Position to be used for error reporting.
   493      *  @param t             The type to be checked.
   494      *  @param noBounds    True if type bounds are illegal here.
   495      */
   496     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   497         t = checkClassType(pos, t);
   498         if (noBounds && t.isParameterized()) {
   499             List<Type> args = t.getTypeArguments();
   500             while (args.nonEmpty()) {
   501                 if (args.head.tag == WILDCARD)
   502                     return typeTagError(pos,
   503                                         log.getLocalizedString("type.req.exact"),
   504                                         args.head);
   505                 args = args.tail;
   506             }
   507         }
   508         return t;
   509     }
   511     /** Check that type is a reifiable class, interface or array type.
   512      *  @param pos           Position to be used for error reporting.
   513      *  @param t             The type to be checked.
   514      */
   515     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   516         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   517             return typeTagError(pos,
   518                                 JCDiagnostic.fragment("type.req.class.array"),
   519                                 t);
   520         } else if (!types.isReifiable(t)) {
   521             log.error(pos, "illegal.generic.type.for.instof");
   522             return syms.errType;
   523         } else {
   524             return t;
   525         }
   526     }
   528     /** Check that type is a reference type, i.e. a class, interface or array type
   529      *  or a type variable.
   530      *  @param pos           Position to be used for error reporting.
   531      *  @param t             The type to be checked.
   532      */
   533     Type checkRefType(DiagnosticPosition pos, Type t) {
   534         switch (t.tag) {
   535         case CLASS:
   536         case ARRAY:
   537         case TYPEVAR:
   538         case WILDCARD:
   539         case ERROR:
   540             return t;
   541         default:
   542             return typeTagError(pos,
   543                                 JCDiagnostic.fragment("type.req.ref"),
   544                                 t);
   545         }
   546     }
   548     /** Check that type is a null or reference type.
   549      *  @param pos           Position to be used for error reporting.
   550      *  @param t             The type to be checked.
   551      */
   552     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   553         switch (t.tag) {
   554         case CLASS:
   555         case ARRAY:
   556         case TYPEVAR:
   557         case WILDCARD:
   558         case BOT:
   559         case ERROR:
   560             return t;
   561         default:
   562             return typeTagError(pos,
   563                                 JCDiagnostic.fragment("type.req.ref"),
   564                                 t);
   565         }
   566     }
   568     /** Check that flag set does not contain elements of two conflicting sets. s
   569      *  Return true if it doesn't.
   570      *  @param pos           Position to be used for error reporting.
   571      *  @param flags         The set of flags to be checked.
   572      *  @param set1          Conflicting flags set #1.
   573      *  @param set2          Conflicting flags set #2.
   574      */
   575     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   576         if ((flags & set1) != 0 && (flags & set2) != 0) {
   577             log.error(pos,
   578                       "illegal.combination.of.modifiers",
   579                       TreeInfo.flagNames(TreeInfo.firstFlag(flags & set1)),
   580                       TreeInfo.flagNames(TreeInfo.firstFlag(flags & set2)));
   581             return false;
   582         } else
   583             return true;
   584     }
   586     /** Check that given modifiers are legal for given symbol and
   587      *  return modifiers together with any implicit modififiers for that symbol.
   588      *  Warning: we can't use flags() here since this method
   589      *  is called during class enter, when flags() would cause a premature
   590      *  completion.
   591      *  @param pos           Position to be used for error reporting.
   592      *  @param flags         The set of modifiers given in a definition.
   593      *  @param sym           The defined symbol.
   594      */
   595     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   596         long mask;
   597         long implicit = 0;
   598         switch (sym.kind) {
   599         case VAR:
   600             if (sym.owner.kind != TYP)
   601                 mask = LocalVarFlags;
   602             else if ((sym.owner.flags_field & INTERFACE) != 0)
   603                 mask = implicit = InterfaceVarFlags;
   604             else
   605                 mask = VarFlags;
   606             break;
   607         case MTH:
   608             if (sym.name == names.init) {
   609                 if ((sym.owner.flags_field & ENUM) != 0) {
   610                     // enum constructors cannot be declared public or
   611                     // protected and must be implicitly or explicitly
   612                     // private
   613                     implicit = PRIVATE;
   614                     mask = PRIVATE;
   615                 } else
   616                     mask = ConstructorFlags;
   617             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   618                 mask = implicit = InterfaceMethodFlags;
   619             else {
   620                 mask = MethodFlags;
   621             }
   622             // Imply STRICTFP if owner has STRICTFP set.
   623             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   624               implicit |= sym.owner.flags_field & STRICTFP;
   625             break;
   626         case TYP:
   627             if (sym.isLocal()) {
   628                 mask = LocalClassFlags;
   629                 if (sym.name.len == 0) { // Anonymous class
   630                     // Anonymous classes in static methods are themselves static;
   631                     // that's why we admit STATIC here.
   632                     mask |= STATIC;
   633                     // JLS: Anonymous classes are final.
   634                     implicit |= FINAL;
   635                 }
   636                 if ((sym.owner.flags_field & STATIC) == 0 &&
   637                     (flags & ENUM) != 0)
   638                     log.error(pos, "enums.must.be.static");
   639             } else if (sym.owner.kind == TYP) {
   640                 mask = MemberClassFlags;
   641                 if (sym.owner.owner.kind == PCK ||
   642                     (sym.owner.flags_field & STATIC) != 0)
   643                     mask |= STATIC;
   644                 else if ((flags & ENUM) != 0)
   645                     log.error(pos, "enums.must.be.static");
   646                 // Nested interfaces and enums are always STATIC (Spec ???)
   647                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   648             } else {
   649                 mask = ClassFlags;
   650             }
   651             // Interfaces are always ABSTRACT
   652             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   654             if ((flags & ENUM) != 0) {
   655                 // enums can't be declared abstract or final
   656                 mask &= ~(ABSTRACT | FINAL);
   657                 implicit |= implicitEnumFinalFlag(tree);
   658             }
   659             // Imply STRICTFP if owner has STRICTFP set.
   660             implicit |= sym.owner.flags_field & STRICTFP;
   661             break;
   662         default:
   663             throw new AssertionError();
   664         }
   665         long illegal = flags & StandardFlags & ~mask;
   666         if (illegal != 0) {
   667             if ((illegal & INTERFACE) != 0) {
   668                 log.error(pos, "intf.not.allowed.here");
   669                 mask |= INTERFACE;
   670             }
   671             else {
   672                 log.error(pos,
   673                           "mod.not.allowed.here", TreeInfo.flagNames(illegal));
   674             }
   675         }
   676         else if ((sym.kind == TYP ||
   677                   // ISSUE: Disallowing abstract&private is no longer appropriate
   678                   // in the presence of inner classes. Should it be deleted here?
   679                   checkDisjoint(pos, flags,
   680                                 ABSTRACT,
   681                                 PRIVATE | STATIC))
   682                  &&
   683                  checkDisjoint(pos, flags,
   684                                ABSTRACT | INTERFACE,
   685                                FINAL | NATIVE | SYNCHRONIZED)
   686                  &&
   687                  checkDisjoint(pos, flags,
   688                                PUBLIC,
   689                                PRIVATE | PROTECTED)
   690                  &&
   691                  checkDisjoint(pos, flags,
   692                                PRIVATE,
   693                                PUBLIC | PROTECTED)
   694                  &&
   695                  checkDisjoint(pos, flags,
   696                                FINAL,
   697                                VOLATILE)
   698                  &&
   699                  (sym.kind == TYP ||
   700                   checkDisjoint(pos, flags,
   701                                 ABSTRACT | NATIVE,
   702                                 STRICTFP))) {
   703             // skip
   704         }
   705         return flags & (mask | ~StandardFlags) | implicit;
   706     }
   709     /** Determine if this enum should be implicitly final.
   710      *
   711      *  If the enum has no specialized enum contants, it is final.
   712      *
   713      *  If the enum does have specialized enum contants, it is
   714      *  <i>not</i> final.
   715      */
   716     private long implicitEnumFinalFlag(JCTree tree) {
   717         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   718         class SpecialTreeVisitor extends JCTree.Visitor {
   719             boolean specialized;
   720             SpecialTreeVisitor() {
   721                 this.specialized = false;
   722             };
   724             public void visitTree(JCTree tree) { /* no-op */ }
   726             public void visitVarDef(JCVariableDecl tree) {
   727                 if ((tree.mods.flags & ENUM) != 0) {
   728                     if (tree.init instanceof JCNewClass &&
   729                         ((JCNewClass) tree.init).def != null) {
   730                         specialized = true;
   731                     }
   732                 }
   733             }
   734         }
   736         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   737         JCClassDecl cdef = (JCClassDecl) tree;
   738         for (JCTree defs: cdef.defs) {
   739             defs.accept(sts);
   740             if (sts.specialized) return 0;
   741         }
   742         return FINAL;
   743     }
   745 /* *************************************************************************
   746  * Type Validation
   747  **************************************************************************/
   749     /** Validate a type expression. That is,
   750      *  check that all type arguments of a parametric type are within
   751      *  their bounds. This must be done in a second phase after type attributon
   752      *  since a class might have a subclass as type parameter bound. E.g:
   753      *
   754      *  class B<A extends C> { ... }
   755      *  class C extends B<C> { ... }
   756      *
   757      *  and we can't make sure that the bound is already attributed because
   758      *  of possible cycles.
   759      */
   760     private Validator validator = new Validator();
   762     /** Visitor method: Validate a type expression, if it is not null, catching
   763      *  and reporting any completion failures.
   764      */
   765     void validate(JCTree tree) {
   766         try {
   767             if (tree != null) tree.accept(validator);
   768         } catch (CompletionFailure ex) {
   769             completionError(tree.pos(), ex);
   770         }
   771     }
   773     /** Visitor method: Validate a list of type expressions.
   774      */
   775     void validate(List<? extends JCTree> trees) {
   776         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   777             validate(l.head);
   778     }
   780     /** Visitor method: Validate a list of type parameters.
   781      */
   782     void validateTypeParams(List<JCTypeParameter> trees) {
   783         for (List<JCTypeParameter> l = trees; l.nonEmpty(); l = l.tail)
   784             validate(l.head);
   785     }
   787     /** A visitor class for type validation.
   788      */
   789     class Validator extends JCTree.Visitor {
   791         public void visitTypeArray(JCArrayTypeTree tree) {
   792             validate(tree.elemtype);
   793         }
   795         public void visitTypeApply(JCTypeApply tree) {
   796             if (tree.type.tag == CLASS) {
   797                 List<Type> formals = tree.type.tsym.type.getTypeArguments();
   798                 List<Type> actuals = types.capture(tree.type).getTypeArguments();
   799                 List<JCExpression> args = tree.arguments;
   800                 List<Type> forms = formals;
   801                 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>();
   803                 // For matching pairs of actual argument types `a' and
   804                 // formal type parameters with declared bound `b' ...
   805                 while (args.nonEmpty() && forms.nonEmpty()) {
   806                     validate(args.head);
   808                     // exact type arguments needs to know their
   809                     // bounds (for upper and lower bound
   810                     // calculations).  So we create new TypeVars with
   811                     // bounds substed with actuals.
   812                     tvars_buf.append(types.substBound(((TypeVar)forms.head),
   813                                                       formals,
   814                                                       actuals));
   816                     args = args.tail;
   817                     forms = forms.tail;
   818                 }
   820                 args = tree.arguments;
   821                 List<TypeVar> tvars = tvars_buf.toList();
   822                 while (args.nonEmpty() && tvars.nonEmpty()) {
   823                     // Let the actual arguments know their bound
   824                     args.head.type.withTypeVar(tvars.head);
   825                     args = args.tail;
   826                     tvars = tvars.tail;
   827                 }
   829                 args = tree.arguments;
   830                 tvars = tvars_buf.toList();
   831                 while (args.nonEmpty() && tvars.nonEmpty()) {
   832                     checkExtends(args.head.pos(),
   833                                  actuals.head,
   834                                  tvars.head);
   835                     args = args.tail;
   836                     tvars = tvars.tail;
   837                     actuals = actuals.tail;
   838                 }
   840                 // Check that this type is either fully parameterized, or
   841                 // not parameterized at all.
   842                 if (tree.type.getEnclosingType().isRaw())
   843                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
   844                 if (tree.clazz.getTag() == JCTree.SELECT)
   845                     visitSelectInternal((JCFieldAccess)tree.clazz);
   846             }
   847         }
   849         public void visitTypeParameter(JCTypeParameter tree) {
   850             validate(tree.bounds);
   851             checkClassBounds(tree.pos(), tree.type);
   852         }
   854         @Override
   855         public void visitWildcard(JCWildcard tree) {
   856             if (tree.inner != null)
   857                 validate(tree.inner);
   858         }
   860         public void visitSelect(JCFieldAccess tree) {
   861             if (tree.type.tag == CLASS) {
   862                 visitSelectInternal(tree);
   864                 // Check that this type is either fully parameterized, or
   865                 // not parameterized at all.
   866                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
   867                     log.error(tree.pos(), "improperly.formed.type.param.missing");
   868             }
   869         }
   870         public void visitSelectInternal(JCFieldAccess tree) {
   871             if (tree.type.getEnclosingType().tag != CLASS &&
   872                 tree.selected.type.isParameterized()) {
   873                 // The enclosing type is not a class, so we are
   874                 // looking at a static member type.  However, the
   875                 // qualifying expression is parameterized.
   876                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
   877             } else {
   878                 // otherwise validate the rest of the expression
   879                 validate(tree.selected);
   880             }
   881         }
   883         /** Default visitor method: do nothing.
   884          */
   885         public void visitTree(JCTree tree) {
   886         }
   887     }
   889 /* *************************************************************************
   890  * Exception checking
   891  **************************************************************************/
   893     /* The following methods treat classes as sets that contain
   894      * the class itself and all their subclasses
   895      */
   897     /** Is given type a subtype of some of the types in given list?
   898      */
   899     boolean subset(Type t, List<Type> ts) {
   900         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   901             if (types.isSubtype(t, l.head)) return true;
   902         return false;
   903     }
   905     /** Is given type a subtype or supertype of
   906      *  some of the types in given list?
   907      */
   908     boolean intersects(Type t, List<Type> ts) {
   909         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   910             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
   911         return false;
   912     }
   914     /** Add type set to given type list, unless it is a subclass of some class
   915      *  in the list.
   916      */
   917     List<Type> incl(Type t, List<Type> ts) {
   918         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
   919     }
   921     /** Remove type set from type set list.
   922      */
   923     List<Type> excl(Type t, List<Type> ts) {
   924         if (ts.isEmpty()) {
   925             return ts;
   926         } else {
   927             List<Type> ts1 = excl(t, ts.tail);
   928             if (types.isSubtype(ts.head, t)) return ts1;
   929             else if (ts1 == ts.tail) return ts;
   930             else return ts1.prepend(ts.head);
   931         }
   932     }
   934     /** Form the union of two type set lists.
   935      */
   936     List<Type> union(List<Type> ts1, List<Type> ts2) {
   937         List<Type> ts = ts1;
   938         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   939             ts = incl(l.head, ts);
   940         return ts;
   941     }
   943     /** Form the difference of two type lists.
   944      */
   945     List<Type> diff(List<Type> ts1, List<Type> ts2) {
   946         List<Type> ts = ts1;
   947         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   948             ts = excl(l.head, ts);
   949         return ts;
   950     }
   952     /** Form the intersection of two type lists.
   953      */
   954     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
   955         List<Type> ts = List.nil();
   956         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
   957             if (subset(l.head, ts2)) ts = incl(l.head, ts);
   958         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   959             if (subset(l.head, ts1)) ts = incl(l.head, ts);
   960         return ts;
   961     }
   963     /** Is exc an exception symbol that need not be declared?
   964      */
   965     boolean isUnchecked(ClassSymbol exc) {
   966         return
   967             exc.kind == ERR ||
   968             exc.isSubClass(syms.errorType.tsym, types) ||
   969             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
   970     }
   972     /** Is exc an exception type that need not be declared?
   973      */
   974     boolean isUnchecked(Type exc) {
   975         return
   976             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
   977             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
   978             exc.tag == BOT;
   979     }
   981     /** Same, but handling completion failures.
   982      */
   983     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
   984         try {
   985             return isUnchecked(exc);
   986         } catch (CompletionFailure ex) {
   987             completionError(pos, ex);
   988             return true;
   989         }
   990     }
   992     /** Is exc handled by given exception list?
   993      */
   994     boolean isHandled(Type exc, List<Type> handled) {
   995         return isUnchecked(exc) || subset(exc, handled);
   996     }
   998     /** Return all exceptions in thrown list that are not in handled list.
   999      *  @param thrown     The list of thrown exceptions.
  1000      *  @param handled    The list of handled exceptions.
  1001      */
  1002     List<Type> unHandled(List<Type> thrown, List<Type> handled) {
  1003         List<Type> unhandled = List.nil();
  1004         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1005             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1006         return unhandled;
  1009 /* *************************************************************************
  1010  * Overriding/Implementation checking
  1011  **************************************************************************/
  1013     /** The level of access protection given by a flag set,
  1014      *  where PRIVATE is highest and PUBLIC is lowest.
  1015      */
  1016     static int protection(long flags) {
  1017         switch ((short)(flags & AccessFlags)) {
  1018         case PRIVATE: return 3;
  1019         case PROTECTED: return 1;
  1020         default:
  1021         case PUBLIC: return 0;
  1022         case 0: return 2;
  1026     /** A string describing the access permission given by a flag set.
  1027      *  This always returns a space-separated list of Java Keywords.
  1028      */
  1029     private static String protectionString(long flags) {
  1030         long flags1 = flags & AccessFlags;
  1031         return (flags1 == 0) ? "package" : TreeInfo.flagNames(flags1);
  1034     /** A customized "cannot override" error message.
  1035      *  @param m      The overriding method.
  1036      *  @param other  The overridden method.
  1037      *  @return       An internationalized string.
  1038      */
  1039     static Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1040         String key;
  1041         if ((other.owner.flags() & INTERFACE) == 0)
  1042             key = "cant.override";
  1043         else if ((m.owner.flags() & INTERFACE) == 0)
  1044             key = "cant.implement";
  1045         else
  1046             key = "clashes.with";
  1047         return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
  1050     /** A customized "override" warning message.
  1051      *  @param m      The overriding method.
  1052      *  @param other  The overridden method.
  1053      *  @return       An internationalized string.
  1054      */
  1055     static Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1056         String key;
  1057         if ((other.owner.flags() & INTERFACE) == 0)
  1058             key = "unchecked.override";
  1059         else if ((m.owner.flags() & INTERFACE) == 0)
  1060             key = "unchecked.implement";
  1061         else
  1062             key = "unchecked.clash.with";
  1063         return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
  1066     /** A customized "override" warning message.
  1067      *  @param m      The overriding method.
  1068      *  @param other  The overridden method.
  1069      *  @return       An internationalized string.
  1070      */
  1071     static Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1072         String key;
  1073         if ((other.owner.flags() & INTERFACE) == 0)
  1074             key = "varargs.override";
  1075         else  if ((m.owner.flags() & INTERFACE) == 0)
  1076             key = "varargs.implement";
  1077         else
  1078             key = "varargs.clash.with";
  1079         return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
  1082     /** Check that this method conforms with overridden method 'other'.
  1083      *  where `origin' is the class where checking started.
  1084      *  Complications:
  1085      *  (1) Do not check overriding of synthetic methods
  1086      *      (reason: they might be final).
  1087      *      todo: check whether this is still necessary.
  1088      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1089      *      than the method it implements. Augment the proxy methods with the
  1090      *      undeclared exceptions in this case.
  1091      *  (3) When generics are enabled, admit the case where an interface proxy
  1092      *      has a result type
  1093      *      extended by the result type of the method it implements.
  1094      *      Change the proxies result type to the smaller type in this case.
  1096      *  @param tree         The tree from which positions
  1097      *                      are extracted for errors.
  1098      *  @param m            The overriding method.
  1099      *  @param other        The overridden method.
  1100      *  @param origin       The class of which the overriding method
  1101      *                      is a member.
  1102      */
  1103     void checkOverride(JCTree tree,
  1104                        MethodSymbol m,
  1105                        MethodSymbol other,
  1106                        ClassSymbol origin) {
  1107         // Don't check overriding of synthetic methods or by bridge methods.
  1108         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1109             return;
  1112         // Error if static method overrides instance method (JLS 8.4.6.2).
  1113         if ((m.flags() & STATIC) != 0 &&
  1114                    (other.flags() & STATIC) == 0) {
  1115             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1116                       cannotOverride(m, other));
  1117             return;
  1120         // Error if instance method overrides static or final
  1121         // method (JLS 8.4.6.1).
  1122         if ((other.flags() & FINAL) != 0 ||
  1123                  (m.flags() & STATIC) == 0 &&
  1124                  (other.flags() & STATIC) != 0) {
  1125             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1126                       cannotOverride(m, other),
  1127                       TreeInfo.flagNames(other.flags() & (FINAL | STATIC)));
  1128             return;
  1131         if ((m.owner.flags() & ANNOTATION) != 0) {
  1132             // handled in validateAnnotationMethod
  1133             return;
  1136         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1137         if ((origin.flags() & INTERFACE) == 0 &&
  1138                  protection(m.flags()) > protection(other.flags())) {
  1139             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1140                       cannotOverride(m, other),
  1141                       protectionString(other.flags()));
  1142             return;
  1146         Type mt = types.memberType(origin.type, m);
  1147         Type ot = types.memberType(origin.type, other);
  1148         // Error if overriding result type is different
  1149         // (or, in the case of generics mode, not a subtype) of
  1150         // overridden result type. We have to rename any type parameters
  1151         // before comparing types.
  1152         List<Type> mtvars = mt.getTypeArguments();
  1153         List<Type> otvars = ot.getTypeArguments();
  1154         Type mtres = mt.getReturnType();
  1155         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1157         overrideWarner.warned = false;
  1158         boolean resultTypesOK =
  1159             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1160         if (!resultTypesOK) {
  1161             if (!source.allowCovariantReturns() &&
  1162                 m.owner != origin &&
  1163                 m.owner.isSubClass(other.owner, types)) {
  1164                 // allow limited interoperability with covariant returns
  1165             } else {
  1166                 typeError(TreeInfo.diagnosticPositionFor(m, tree),
  1167                           JCDiagnostic.fragment("override.incompatible.ret",
  1168                                          cannotOverride(m, other)),
  1169                           mtres, otres);
  1170                 return;
  1172         } else if (overrideWarner.warned) {
  1173             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1174                           "prob.found.req",
  1175                           JCDiagnostic.fragment("override.unchecked.ret",
  1176                                               uncheckedOverrides(m, other)),
  1177                           mtres, otres);
  1180         // Error if overriding method throws an exception not reported
  1181         // by overridden method.
  1182         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1183         List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
  1184         if (unhandled.nonEmpty()) {
  1185             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1186                       "override.meth.doesnt.throw",
  1187                       cannotOverride(m, other),
  1188                       unhandled.head);
  1189             return;
  1192         // Optional warning if varargs don't agree
  1193         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1194             && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
  1195             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1196                         ((m.flags() & Flags.VARARGS) != 0)
  1197                         ? "override.varargs.missing"
  1198                         : "override.varargs.extra",
  1199                         varargsOverrides(m, other));
  1202         // Warn if instance method overrides bridge method (compiler spec ??)
  1203         if ((other.flags() & BRIDGE) != 0) {
  1204             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1205                         uncheckedOverrides(m, other));
  1208         // Warn if a deprecated method overridden by a non-deprecated one.
  1209         if ((other.flags() & DEPRECATED) != 0
  1210             && (m.flags() & DEPRECATED) == 0
  1211             && m.outermostClass() != other.outermostClass()
  1212             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1213             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1216     // where
  1217         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1218             // If the method, m, is defined in an interface, then ignore the issue if the method
  1219             // is only inherited via a supertype and also implemented in the supertype,
  1220             // because in that case, we will rediscover the issue when examining the method
  1221             // in the supertype.
  1222             // If the method, m, is not defined in an interface, then the only time we need to
  1223             // address the issue is when the method is the supertype implemementation: any other
  1224             // case, we will have dealt with when examining the supertype classes
  1225             ClassSymbol mc = m.enclClass();
  1226             Type st = types.supertype(origin.type);
  1227             if (st.tag != CLASS)
  1228                 return true;
  1229             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1231             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1232                 List<Type> intfs = types.interfaces(origin.type);
  1233                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1235             else
  1236                 return (stimpl != m);
  1240     // used to check if there were any unchecked conversions
  1241     Warner overrideWarner = new Warner();
  1243     /** Check that a class does not inherit two concrete methods
  1244      *  with the same signature.
  1245      *  @param pos          Position to be used for error reporting.
  1246      *  @param site         The class type to be checked.
  1247      */
  1248     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1249         Type sup = types.supertype(site);
  1250         if (sup.tag != CLASS) return;
  1252         for (Type t1 = sup;
  1253              t1.tsym.type.isParameterized();
  1254              t1 = types.supertype(t1)) {
  1255             for (Scope.Entry e1 = t1.tsym.members().elems;
  1256                  e1 != null;
  1257                  e1 = e1.sibling) {
  1258                 Symbol s1 = e1.sym;
  1259                 if (s1.kind != MTH ||
  1260                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1261                     !s1.isInheritedIn(site.tsym, types) ||
  1262                     ((MethodSymbol)s1).implementation(site.tsym,
  1263                                                       types,
  1264                                                       true) != s1)
  1265                     continue;
  1266                 Type st1 = types.memberType(t1, s1);
  1267                 int s1ArgsLength = st1.getParameterTypes().length();
  1268                 if (st1 == s1.type) continue;
  1270                 for (Type t2 = sup;
  1271                      t2.tag == CLASS;
  1272                      t2 = types.supertype(t2)) {
  1273                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1274                          e2.scope != null;
  1275                          e2 = e2.next()) {
  1276                         Symbol s2 = e2.sym;
  1277                         if (s2 == s1 ||
  1278                             s2.kind != MTH ||
  1279                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1280                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1281                             !s2.isInheritedIn(site.tsym, types) ||
  1282                             ((MethodSymbol)s2).implementation(site.tsym,
  1283                                                               types,
  1284                                                               true) != s2)
  1285                             continue;
  1286                         Type st2 = types.memberType(t2, s2);
  1287                         if (types.overrideEquivalent(st1, st2))
  1288                             log.error(pos, "concrete.inheritance.conflict",
  1289                                       s1, t1, s2, t2, sup);
  1296     /** Check that classes (or interfaces) do not each define an abstract
  1297      *  method with same name and arguments but incompatible return types.
  1298      *  @param pos          Position to be used for error reporting.
  1299      *  @param t1           The first argument type.
  1300      *  @param t2           The second argument type.
  1301      */
  1302     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1303                                             Type t1,
  1304                                             Type t2) {
  1305         return checkCompatibleAbstracts(pos, t1, t2,
  1306                                         types.makeCompoundType(t1, t2));
  1309     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1310                                             Type t1,
  1311                                             Type t2,
  1312                                             Type site) {
  1313         Symbol sym = firstIncompatibility(t1, t2, site);
  1314         if (sym != null) {
  1315             log.error(pos, "types.incompatible.diff.ret",
  1316                       t1, t2, sym.name +
  1317                       "(" + types.memberType(t2, sym).getParameterTypes() + ")");
  1318             return false;
  1320         return true;
  1323     /** Return the first method which is defined with same args
  1324      *  but different return types in two given interfaces, or null if none
  1325      *  exists.
  1326      *  @param t1     The first type.
  1327      *  @param t2     The second type.
  1328      *  @param site   The most derived type.
  1329      *  @returns symbol from t2 that conflicts with one in t1.
  1330      */
  1331     private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
  1332         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1333         closure(t1, interfaces1);
  1334         Map<TypeSymbol,Type> interfaces2;
  1335         if (t1 == t2)
  1336             interfaces2 = interfaces1;
  1337         else
  1338             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1340         for (Type t3 : interfaces1.values()) {
  1341             for (Type t4 : interfaces2.values()) {
  1342                 Symbol s = firstDirectIncompatibility(t3, t4, site);
  1343                 if (s != null) return s;
  1346         return null;
  1349     /** Compute all the supertypes of t, indexed by type symbol. */
  1350     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1351         if (t.tag != CLASS) return;
  1352         if (typeMap.put(t.tsym, t) == null) {
  1353             closure(types.supertype(t), typeMap);
  1354             for (Type i : types.interfaces(t))
  1355                 closure(i, typeMap);
  1359     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1360     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1361         if (t.tag != CLASS) return;
  1362         if (typesSkip.get(t.tsym) != null) return;
  1363         if (typeMap.put(t.tsym, t) == null) {
  1364             closure(types.supertype(t), typesSkip, typeMap);
  1365             for (Type i : types.interfaces(t))
  1366                 closure(i, typesSkip, typeMap);
  1370     /** Return the first method in t2 that conflicts with a method from t1. */
  1371     private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
  1372         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1373             Symbol s1 = e1.sym;
  1374             Type st1 = null;
  1375             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1376             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1377             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1378             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1379                 Symbol s2 = e2.sym;
  1380                 if (s1 == s2) continue;
  1381                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1382                 if (st1 == null) st1 = types.memberType(t1, s1);
  1383                 Type st2 = types.memberType(t2, s2);
  1384                 if (types.overrideEquivalent(st1, st2)) {
  1385                     List<Type> tvars1 = st1.getTypeArguments();
  1386                     List<Type> tvars2 = st2.getTypeArguments();
  1387                     Type rt1 = st1.getReturnType();
  1388                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1389                     boolean compat =
  1390                         types.isSameType(rt1, rt2) ||
  1391                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1392                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1393                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1394                          checkCommonOverriderIn(s1,s2,site);
  1395                     if (!compat) return s2;
  1399         return null;
  1401     //WHERE
  1402     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1403         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1404         Type st1 = types.memberType(site, s1);
  1405         Type st2 = types.memberType(site, s2);
  1406         closure(site, supertypes);
  1407         for (Type t : supertypes.values()) {
  1408             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1409                 Symbol s3 = e.sym;
  1410                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1411                 Type st3 = types.memberType(site,s3);
  1412                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1413                     if (s3.owner == site.tsym) {
  1414                         return true;
  1416                     List<Type> tvars1 = st1.getTypeArguments();
  1417                     List<Type> tvars2 = st2.getTypeArguments();
  1418                     List<Type> tvars3 = st3.getTypeArguments();
  1419                     Type rt1 = st1.getReturnType();
  1420                     Type rt2 = st2.getReturnType();
  1421                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1422                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1423                     boolean compat =
  1424                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1425                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1426                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1427                     if (compat)
  1428                         return true;
  1432         return false;
  1435     /** Check that a given method conforms with any method it overrides.
  1436      *  @param tree         The tree from which positions are extracted
  1437      *                      for errors.
  1438      *  @param m            The overriding method.
  1439      */
  1440     void checkOverride(JCTree tree, MethodSymbol m) {
  1441         ClassSymbol origin = (ClassSymbol)m.owner;
  1442         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1443             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1444                 log.error(tree.pos(), "enum.no.finalize");
  1445                 return;
  1447         for (Type t = types.supertype(origin.type); t.tag == CLASS;
  1448              t = types.supertype(t)) {
  1449             TypeSymbol c = t.tsym;
  1450             Scope.Entry e = c.members().lookup(m.name);
  1451             while (e.scope != null) {
  1452                 if (m.overrides(e.sym, origin, types, false))
  1453                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1454                 else if (e.sym.isInheritedIn(origin, types) && !m.isConstructor()) {
  1455                     Type er1 = m.erasure(types);
  1456                     Type er2 = e.sym.erasure(types);
  1457                     if (types.isSameType(er1,er2)) {
  1458                             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1459                                     "name.clash.same.erasure.no.override",
  1460                                     m, m.location(),
  1461                                     e.sym, e.sym.location());
  1464                 e = e.next();
  1469     /** Check that all abstract members of given class have definitions.
  1470      *  @param pos          Position to be used for error reporting.
  1471      *  @param c            The class.
  1472      */
  1473     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1474         try {
  1475             MethodSymbol undef = firstUndef(c, c);
  1476             if (undef != null) {
  1477                 if ((c.flags() & ENUM) != 0 &&
  1478                     types.supertype(c.type).tsym == syms.enumSym &&
  1479                     (c.flags() & FINAL) == 0) {
  1480                     // add the ABSTRACT flag to an enum
  1481                     c.flags_field |= ABSTRACT;
  1482                 } else {
  1483                     MethodSymbol undef1 =
  1484                         new MethodSymbol(undef.flags(), undef.name,
  1485                                          types.memberType(c.type, undef), undef.owner);
  1486                     log.error(pos, "does.not.override.abstract",
  1487                               c, undef1, undef1.location());
  1490         } catch (CompletionFailure ex) {
  1491             completionError(pos, ex);
  1494 //where
  1495         /** Return first abstract member of class `c' that is not defined
  1496          *  in `impl', null if there is none.
  1497          */
  1498         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1499             MethodSymbol undef = null;
  1500             // Do not bother to search in classes that are not abstract,
  1501             // since they cannot have abstract members.
  1502             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1503                 Scope s = c.members();
  1504                 for (Scope.Entry e = s.elems;
  1505                      undef == null && e != null;
  1506                      e = e.sibling) {
  1507                     if (e.sym.kind == MTH &&
  1508                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1509                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1510                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1511                         if (implmeth == null || implmeth == absmeth)
  1512                             undef = absmeth;
  1515                 if (undef == null) {
  1516                     Type st = types.supertype(c.type);
  1517                     if (st.tag == CLASS)
  1518                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1520                 for (List<Type> l = types.interfaces(c.type);
  1521                      undef == null && l.nonEmpty();
  1522                      l = l.tail) {
  1523                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1526             return undef;
  1529     /** Check for cyclic references. Issue an error if the
  1530      *  symbol of the type referred to has a LOCKED flag set.
  1532      *  @param pos      Position to be used for error reporting.
  1533      *  @param t        The type referred to.
  1534      */
  1535     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1536         checkNonCyclicInternal(pos, t);
  1540     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1541         checkNonCyclic1(pos, t, new HashSet<TypeVar>());
  1544     private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) {
  1545         final TypeVar tv;
  1546         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1547             return;
  1548         if (seen.contains(t)) {
  1549             tv = (TypeVar)t;
  1550             tv.bound = new ErrorType();
  1551             log.error(pos, "cyclic.inheritance", t);
  1552         } else if (t.tag == TYPEVAR) {
  1553             tv = (TypeVar)t;
  1554             seen.add(tv);
  1555             for (Type b : types.getBounds(tv))
  1556                 checkNonCyclic1(pos, b, seen);
  1560     /** Check for cyclic references. Issue an error if the
  1561      *  symbol of the type referred to has a LOCKED flag set.
  1563      *  @param pos      Position to be used for error reporting.
  1564      *  @param t        The type referred to.
  1565      *  @returns        True if the check completed on all attributed classes
  1566      */
  1567     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1568         boolean complete = true; // was the check complete?
  1569         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1570         Symbol c = t.tsym;
  1571         if ((c.flags_field & ACYCLIC) != 0) return true;
  1573         if ((c.flags_field & LOCKED) != 0) {
  1574             noteCyclic(pos, (ClassSymbol)c);
  1575         } else if (!c.type.isErroneous()) {
  1576             try {
  1577                 c.flags_field |= LOCKED;
  1578                 if (c.type.tag == CLASS) {
  1579                     ClassType clazz = (ClassType)c.type;
  1580                     if (clazz.interfaces_field != null)
  1581                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1582                             complete &= checkNonCyclicInternal(pos, l.head);
  1583                     if (clazz.supertype_field != null) {
  1584                         Type st = clazz.supertype_field;
  1585                         if (st != null && st.tag == CLASS)
  1586                             complete &= checkNonCyclicInternal(pos, st);
  1588                     if (c.owner.kind == TYP)
  1589                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1591             } finally {
  1592                 c.flags_field &= ~LOCKED;
  1595         if (complete)
  1596             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1597         if (complete) c.flags_field |= ACYCLIC;
  1598         return complete;
  1601     /** Note that we found an inheritance cycle. */
  1602     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1603         log.error(pos, "cyclic.inheritance", c);
  1604         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1605             l.head = new ErrorType((ClassSymbol)l.head.tsym);
  1606         Type st = types.supertype(c.type);
  1607         if (st.tag == CLASS)
  1608             ((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym);
  1609         c.type = new ErrorType(c);
  1610         c.flags_field |= ACYCLIC;
  1613     /** Check that all methods which implement some
  1614      *  method conform to the method they implement.
  1615      *  @param tree         The class definition whose members are checked.
  1616      */
  1617     void checkImplementations(JCClassDecl tree) {
  1618         checkImplementations(tree, tree.sym);
  1620 //where
  1621         /** Check that all methods which implement some
  1622          *  method in `ic' conform to the method they implement.
  1623          */
  1624         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1625             ClassSymbol origin = tree.sym;
  1626             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1627                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1628                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1629                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  1630                         if (e.sym.kind == MTH &&
  1631                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  1632                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  1633                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  1634                             if (implmeth != null && implmeth != absmeth &&
  1635                                 (implmeth.owner.flags() & INTERFACE) ==
  1636                                 (origin.flags() & INTERFACE)) {
  1637                                 // don't check if implmeth is in a class, yet
  1638                                 // origin is an interface. This case arises only
  1639                                 // if implmeth is declared in Object. The reason is
  1640                                 // that interfaces really don't inherit from
  1641                                 // Object it's just that the compiler represents
  1642                                 // things that way.
  1643                                 checkOverride(tree, implmeth, absmeth, origin);
  1651     /** Check that all abstract methods implemented by a class are
  1652      *  mutually compatible.
  1653      *  @param pos          Position to be used for error reporting.
  1654      *  @param c            The class whose interfaces are checked.
  1655      */
  1656     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  1657         List<Type> supertypes = types.interfaces(c);
  1658         Type supertype = types.supertype(c);
  1659         if (supertype.tag == CLASS &&
  1660             (supertype.tsym.flags() & ABSTRACT) != 0)
  1661             supertypes = supertypes.prepend(supertype);
  1662         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  1663             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  1664                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  1665                 return;
  1666             for (List<Type> m = supertypes; m != l; m = m.tail)
  1667                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  1668                     return;
  1670         checkCompatibleConcretes(pos, c);
  1673     /** Check that class c does not implement directly or indirectly
  1674      *  the same parameterized interface with two different argument lists.
  1675      *  @param pos          Position to be used for error reporting.
  1676      *  @param type         The type whose interfaces are checked.
  1677      */
  1678     void checkClassBounds(DiagnosticPosition pos, Type type) {
  1679         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  1681 //where
  1682         /** Enter all interfaces of type `type' into the hash table `seensofar'
  1683          *  with their class symbol as key and their type as value. Make
  1684          *  sure no class is entered with two different types.
  1685          */
  1686         void checkClassBounds(DiagnosticPosition pos,
  1687                               Map<TypeSymbol,Type> seensofar,
  1688                               Type type) {
  1689             if (type.isErroneous()) return;
  1690             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  1691                 Type it = l.head;
  1692                 Type oldit = seensofar.put(it.tsym, it);
  1693                 if (oldit != null) {
  1694                     List<Type> oldparams = oldit.allparams();
  1695                     List<Type> newparams = it.allparams();
  1696                     if (!types.containsTypeEquivalent(oldparams, newparams))
  1697                         log.error(pos, "cant.inherit.diff.arg",
  1698                                   it.tsym, Type.toString(oldparams),
  1699                                   Type.toString(newparams));
  1701                 checkClassBounds(pos, seensofar, it);
  1703             Type st = types.supertype(type);
  1704             if (st != null) checkClassBounds(pos, seensofar, st);
  1707     /** Enter interface into into set.
  1708      *  If it existed already, issue a "repeated interface" error.
  1709      */
  1710     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  1711         if (its.contains(it))
  1712             log.error(pos, "repeated.interface");
  1713         else {
  1714             its.add(it);
  1718 /* *************************************************************************
  1719  * Check annotations
  1720  **************************************************************************/
  1722     /** Annotation types are restricted to primitives, String, an
  1723      *  enum, an annotation, Class, Class<?>, Class<? extends
  1724      *  Anything>, arrays of the preceding.
  1725      */
  1726     void validateAnnotationType(JCTree restype) {
  1727         // restype may be null if an error occurred, so don't bother validating it
  1728         if (restype != null) {
  1729             validateAnnotationType(restype.pos(), restype.type);
  1733     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  1734         if (type.isPrimitive()) return;
  1735         if (types.isSameType(type, syms.stringType)) return;
  1736         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  1737         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  1738         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  1739         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  1740             validateAnnotationType(pos, types.elemtype(type));
  1741             return;
  1743         log.error(pos, "invalid.annotation.member.type");
  1746     /**
  1747      * "It is also a compile-time error if any method declared in an
  1748      * annotation type has a signature that is override-equivalent to
  1749      * that of any public or protected method declared in class Object
  1750      * or in the interface annotation.Annotation."
  1752      * @jls3 9.6 Annotation Types
  1753      */
  1754     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  1755         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  1756             Scope s = sup.tsym.members();
  1757             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  1758                 if (e.sym.kind == MTH &&
  1759                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  1760                     types.overrideEquivalent(m.type, e.sym.type))
  1761                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  1766     /** Check the annotations of a symbol.
  1767      */
  1768     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  1769         if (skipAnnotations) return;
  1770         for (JCAnnotation a : annotations)
  1771             validateAnnotation(a, s);
  1774     /** Check an annotation of a symbol.
  1775      */
  1776     public void validateAnnotation(JCAnnotation a, Symbol s) {
  1777         validateAnnotation(a);
  1779         if (!annotationApplicable(a, s))
  1780             log.error(a.pos(), "annotation.type.not.applicable");
  1782         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1783             if (!isOverrider(s))
  1784                 log.error(a.pos(), "method.does.not.override.superclass");
  1788     /** Is s a method symbol that overrides a method in a superclass? */
  1789     boolean isOverrider(Symbol s) {
  1790         if (s.kind != MTH || s.isStatic())
  1791             return false;
  1792         MethodSymbol m = (MethodSymbol)s;
  1793         TypeSymbol owner = (TypeSymbol)m.owner;
  1794         for (Type sup : types.closure(owner.type)) {
  1795             if (sup == owner.type)
  1796                 continue; // skip "this"
  1797             Scope scope = sup.tsym.members();
  1798             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  1799                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  1800                     return true;
  1803         return false;
  1806     /** Is the annotation applicable to the symbol? */
  1807     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  1808         Attribute.Compound atTarget =
  1809             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1810         if (atTarget == null) return true;
  1811         Attribute atValue = atTarget.member(names.value);
  1812         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1813         Attribute.Array arr = (Attribute.Array) atValue;
  1814         for (Attribute app : arr.values) {
  1815             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1816             Attribute.Enum e = (Attribute.Enum) app;
  1817             if (e.value.name == names.TYPE)
  1818                 { if (s.kind == TYP) return true; }
  1819             else if (e.value.name == names.FIELD)
  1820                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  1821             else if (e.value.name == names.METHOD)
  1822                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  1823             else if (e.value.name == names.PARAMETER)
  1824                 { if (s.kind == VAR &&
  1825                       s.owner.kind == MTH &&
  1826                       (s.flags() & PARAMETER) != 0)
  1827                     return true;
  1829             else if (e.value.name == names.CONSTRUCTOR)
  1830                 { if (s.kind == MTH && s.isConstructor()) return true; }
  1831             else if (e.value.name == names.LOCAL_VARIABLE)
  1832                 { if (s.kind == VAR && s.owner.kind == MTH &&
  1833                       (s.flags() & PARAMETER) == 0)
  1834                     return true;
  1836             else if (e.value.name == names.ANNOTATION_TYPE)
  1837                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  1838                     return true;
  1840             else if (e.value.name == names.PACKAGE)
  1841                 { if (s.kind == PCK) return true; }
  1842             else
  1843                 return true; // recovery
  1845         return false;
  1848     /** Check an annotation value.
  1849      */
  1850     public void validateAnnotation(JCAnnotation a) {
  1851         if (a.type.isErroneous()) return;
  1853         // collect an inventory of the members
  1854         Set<MethodSymbol> members = new HashSet<MethodSymbol>();
  1855         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  1856              e != null;
  1857              e = e.sibling)
  1858             if (e.sym.kind == MTH)
  1859                 members.add((MethodSymbol) e.sym);
  1861         // count them off as they're annotated
  1862         for (JCTree arg : a.args) {
  1863             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  1864             JCAssign assign = (JCAssign) arg;
  1865             Symbol m = TreeInfo.symbol(assign.lhs);
  1866             if (m == null || m.type.isErroneous()) continue;
  1867             if (!members.remove(m))
  1868                 log.error(arg.pos(), "duplicate.annotation.member.value",
  1869                           m.name, a.type);
  1870             if (assign.rhs.getTag() == ANNOTATION)
  1871                 validateAnnotation((JCAnnotation)assign.rhs);
  1874         // all the remaining ones better have default values
  1875         for (MethodSymbol m : members)
  1876             if (m.defaultValue == null && !m.type.isErroneous())
  1877                 log.error(a.pos(), "annotation.missing.default.value",
  1878                           a.type, m.name);
  1880         // special case: java.lang.annotation.Target must not have
  1881         // repeated values in its value member
  1882         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  1883             a.args.tail == null)
  1884             return;
  1886         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  1887         JCAssign assign = (JCAssign) a.args.head;
  1888         Symbol m = TreeInfo.symbol(assign.lhs);
  1889         if (m.name != names.value) return;
  1890         JCTree rhs = assign.rhs;
  1891         if (rhs.getTag() != JCTree.NEWARRAY) return;
  1892         JCNewArray na = (JCNewArray) rhs;
  1893         Set<Symbol> targets = new HashSet<Symbol>();
  1894         for (JCTree elem : na.elems) {
  1895             if (!targets.add(TreeInfo.symbol(elem))) {
  1896                 log.error(elem.pos(), "repeated.annotation.target");
  1901     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  1902         if (allowAnnotations &&
  1903             lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
  1904             (s.flags() & DEPRECATED) != 0 &&
  1905             !syms.deprecatedType.isErroneous() &&
  1906             s.attribute(syms.deprecatedType.tsym) == null) {
  1907             log.warning(pos, "missing.deprecated.annotation");
  1911 /* *************************************************************************
  1912  * Check for recursive annotation elements.
  1913  **************************************************************************/
  1915     /** Check for cycles in the graph of annotation elements.
  1916      */
  1917     void checkNonCyclicElements(JCClassDecl tree) {
  1918         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  1919         assert (tree.sym.flags_field & LOCKED) == 0;
  1920         try {
  1921             tree.sym.flags_field |= LOCKED;
  1922             for (JCTree def : tree.defs) {
  1923                 if (def.getTag() != JCTree.METHODDEF) continue;
  1924                 JCMethodDecl meth = (JCMethodDecl)def;
  1925                 checkAnnotationResType(meth.pos(), meth.restype.type);
  1927         } finally {
  1928             tree.sym.flags_field &= ~LOCKED;
  1929             tree.sym.flags_field |= ACYCLIC_ANN;
  1933     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  1934         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  1935             return;
  1936         if ((tsym.flags_field & LOCKED) != 0) {
  1937             log.error(pos, "cyclic.annotation.element");
  1938             return;
  1940         try {
  1941             tsym.flags_field |= LOCKED;
  1942             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  1943                 Symbol s = e.sym;
  1944                 if (s.kind != Kinds.MTH)
  1945                     continue;
  1946                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  1948         } finally {
  1949             tsym.flags_field &= ~LOCKED;
  1950             tsym.flags_field |= ACYCLIC_ANN;
  1954     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  1955         switch (type.tag) {
  1956         case TypeTags.CLASS:
  1957             if ((type.tsym.flags() & ANNOTATION) != 0)
  1958                 checkNonCyclicElementsInternal(pos, type.tsym);
  1959             break;
  1960         case TypeTags.ARRAY:
  1961             checkAnnotationResType(pos, types.elemtype(type));
  1962             break;
  1963         default:
  1964             break; // int etc
  1968 /* *************************************************************************
  1969  * Check for cycles in the constructor call graph.
  1970  **************************************************************************/
  1972     /** Check for cycles in the graph of constructors calling other
  1973      *  constructors.
  1974      */
  1975     void checkCyclicConstructors(JCClassDecl tree) {
  1976         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  1978         // enter each constructor this-call into the map
  1979         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1980             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  1981             if (app == null) continue;
  1982             JCMethodDecl meth = (JCMethodDecl) l.head;
  1983             if (TreeInfo.name(app.meth) == names._this) {
  1984                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  1985             } else {
  1986                 meth.sym.flags_field |= ACYCLIC;
  1990         // Check for cycles in the map
  1991         Symbol[] ctors = new Symbol[0];
  1992         ctors = callMap.keySet().toArray(ctors);
  1993         for (Symbol caller : ctors) {
  1994             checkCyclicConstructor(tree, caller, callMap);
  1998     /** Look in the map to see if the given constructor is part of a
  1999      *  call cycle.
  2000      */
  2001     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2002                                         Map<Symbol,Symbol> callMap) {
  2003         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2004             if ((ctor.flags_field & LOCKED) != 0) {
  2005                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2006                           "recursive.ctor.invocation");
  2007             } else {
  2008                 ctor.flags_field |= LOCKED;
  2009                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2010                 ctor.flags_field &= ~LOCKED;
  2012             ctor.flags_field |= ACYCLIC;
  2016 /* *************************************************************************
  2017  * Miscellaneous
  2018  **************************************************************************/
  2020     /**
  2021      * Return the opcode of the operator but emit an error if it is an
  2022      * error.
  2023      * @param pos        position for error reporting.
  2024      * @param operator   an operator
  2025      * @param tag        a tree tag
  2026      * @param left       type of left hand side
  2027      * @param right      type of right hand side
  2028      */
  2029     int checkOperator(DiagnosticPosition pos,
  2030                        OperatorSymbol operator,
  2031                        int tag,
  2032                        Type left,
  2033                        Type right) {
  2034         if (operator.opcode == ByteCodes.error) {
  2035             log.error(pos,
  2036                       "operator.cant.be.applied",
  2037                       treeinfo.operatorName(tag),
  2038                       left + "," + right);
  2040         return operator.opcode;
  2044     /**
  2045      *  Check for division by integer constant zero
  2046      *  @param pos           Position for error reporting.
  2047      *  @param operator      The operator for the expression
  2048      *  @param operand       The right hand operand for the expression
  2049      */
  2050     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2051         if (operand.constValue() != null
  2052             && lint.isEnabled(Lint.LintCategory.DIVZERO)
  2053             && operand.tag <= LONG
  2054             && ((Number) (operand.constValue())).longValue() == 0) {
  2055             int opc = ((OperatorSymbol)operator).opcode;
  2056             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2057                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2058                 log.warning(pos, "div.zero");
  2063     /**
  2064      * Check for empty statements after if
  2065      */
  2066     void checkEmptyIf(JCIf tree) {
  2067         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
  2068             log.warning(tree.thenpart.pos(), "empty.if");
  2071     /** Check that symbol is unique in given scope.
  2072      *  @param pos           Position for error reporting.
  2073      *  @param sym           The symbol.
  2074      *  @param s             The scope.
  2075      */
  2076     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2077         if (sym.type.isErroneous())
  2078             return true;
  2079         if (sym.owner.name == names.any) return false;
  2080         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2081             if (sym != e.sym &&
  2082                 sym.kind == e.sym.kind &&
  2083                 sym.name != names.error &&
  2084                 (sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) {
  2085                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2086                     varargsDuplicateError(pos, sym, e.sym);
  2087                 else
  2088                     duplicateError(pos, e.sym);
  2089                 return false;
  2092         return true;
  2095     /** Check that single-type import is not already imported or top-level defined,
  2096      *  but make an exception for two single-type imports which denote the same type.
  2097      *  @param pos           Position for error reporting.
  2098      *  @param sym           The symbol.
  2099      *  @param s             The scope
  2100      */
  2101     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2102         return checkUniqueImport(pos, sym, s, false);
  2105     /** Check that static single-type import is not already imported or top-level defined,
  2106      *  but make an exception for two single-type imports which denote the same type.
  2107      *  @param pos           Position for error reporting.
  2108      *  @param sym           The symbol.
  2109      *  @param s             The scope
  2110      *  @param staticImport  Whether or not this was a static import
  2111      */
  2112     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2113         return checkUniqueImport(pos, sym, s, true);
  2116     /** Check that single-type import is not already imported or top-level defined,
  2117      *  but make an exception for two single-type imports which denote the same type.
  2118      *  @param pos           Position for error reporting.
  2119      *  @param sym           The symbol.
  2120      *  @param s             The scope.
  2121      *  @param staticImport  Whether or not this was a static import
  2122      */
  2123     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2124         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2125             // is encountered class entered via a class declaration?
  2126             boolean isClassDecl = e.scope == s;
  2127             if ((isClassDecl || sym != e.sym) &&
  2128                 sym.kind == e.sym.kind &&
  2129                 sym.name != names.error) {
  2130                 if (!e.sym.type.isErroneous()) {
  2131                     String what = e.sym.toString();
  2132                     if (!isClassDecl) {
  2133                         if (staticImport)
  2134                             log.error(pos, "already.defined.static.single.import", what);
  2135                         else
  2136                             log.error(pos, "already.defined.single.import", what);
  2138                     else if (sym != e.sym)
  2139                         log.error(pos, "already.defined.this.unit", what);
  2141                 return false;
  2144         return true;
  2147     /** Check that a qualified name is in canonical form (for import decls).
  2148      */
  2149     public void checkCanonical(JCTree tree) {
  2150         if (!isCanonical(tree))
  2151             log.error(tree.pos(), "import.requires.canonical",
  2152                       TreeInfo.symbol(tree));
  2154         // where
  2155         private boolean isCanonical(JCTree tree) {
  2156             while (tree.getTag() == JCTree.SELECT) {
  2157                 JCFieldAccess s = (JCFieldAccess) tree;
  2158                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2159                     return false;
  2160                 tree = s.selected;
  2162             return true;
  2165     private class ConversionWarner extends Warner {
  2166         final String key;
  2167         final Type found;
  2168         final Type expected;
  2169         public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
  2170             super(pos);
  2171             this.key = key;
  2172             this.found = found;
  2173             this.expected = expected;
  2176         public void warnUnchecked() {
  2177             boolean warned = this.warned;
  2178             super.warnUnchecked();
  2179             if (warned) return; // suppress redundant diagnostics
  2180             Object problem = JCDiagnostic.fragment(key);
  2181             Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
  2185     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2186         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2189     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2190         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial