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

Thu, 24 Jul 2008 19:06:57 +0100

author
mcimadamore
date
Thu, 24 Jul 2008 19:06:57 +0100
changeset 80
5c9cdeb740f2
parent 79
36df13bde238
child 89
b6d5f53b3b29
permissions
-rw-r--r--

6717241: some diagnostic argument is prematurely converted into a String object
Summary: removed early toString() conversions applied to diagnostic arguments
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                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   580                       asFlagSet(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", asFlagSet(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 customized "cannot override" error message.
  1027      *  @param m      The overriding method.
  1028      *  @param other  The overridden method.
  1029      *  @return       An internationalized string.
  1030      */
  1031     static Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1032         String key;
  1033         if ((other.owner.flags() & INTERFACE) == 0)
  1034             key = "cant.override";
  1035         else if ((m.owner.flags() & INTERFACE) == 0)
  1036             key = "cant.implement";
  1037         else
  1038             key = "clashes.with";
  1039         return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
  1042     /** A customized "override" warning message.
  1043      *  @param m      The overriding method.
  1044      *  @param other  The overridden method.
  1045      *  @return       An internationalized string.
  1046      */
  1047     static Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1048         String key;
  1049         if ((other.owner.flags() & INTERFACE) == 0)
  1050             key = "unchecked.override";
  1051         else if ((m.owner.flags() & INTERFACE) == 0)
  1052             key = "unchecked.implement";
  1053         else
  1054             key = "unchecked.clash.with";
  1055         return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
  1058     /** A customized "override" warning message.
  1059      *  @param m      The overriding method.
  1060      *  @param other  The overridden method.
  1061      *  @return       An internationalized string.
  1062      */
  1063     static Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1064         String key;
  1065         if ((other.owner.flags() & INTERFACE) == 0)
  1066             key = "varargs.override";
  1067         else  if ((m.owner.flags() & INTERFACE) == 0)
  1068             key = "varargs.implement";
  1069         else
  1070             key = "varargs.clash.with";
  1071         return JCDiagnostic.fragment(key, m, m.location(), other, other.location());
  1074     /** Check that this method conforms with overridden method 'other'.
  1075      *  where `origin' is the class where checking started.
  1076      *  Complications:
  1077      *  (1) Do not check overriding of synthetic methods
  1078      *      (reason: they might be final).
  1079      *      todo: check whether this is still necessary.
  1080      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1081      *      than the method it implements. Augment the proxy methods with the
  1082      *      undeclared exceptions in this case.
  1083      *  (3) When generics are enabled, admit the case where an interface proxy
  1084      *      has a result type
  1085      *      extended by the result type of the method it implements.
  1086      *      Change the proxies result type to the smaller type in this case.
  1088      *  @param tree         The tree from which positions
  1089      *                      are extracted for errors.
  1090      *  @param m            The overriding method.
  1091      *  @param other        The overridden method.
  1092      *  @param origin       The class of which the overriding method
  1093      *                      is a member.
  1094      */
  1095     void checkOverride(JCTree tree,
  1096                        MethodSymbol m,
  1097                        MethodSymbol other,
  1098                        ClassSymbol origin) {
  1099         // Don't check overriding of synthetic methods or by bridge methods.
  1100         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1101             return;
  1104         // Error if static method overrides instance method (JLS 8.4.6.2).
  1105         if ((m.flags() & STATIC) != 0 &&
  1106                    (other.flags() & STATIC) == 0) {
  1107             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1108                       cannotOverride(m, other));
  1109             return;
  1112         // Error if instance method overrides static or final
  1113         // method (JLS 8.4.6.1).
  1114         if ((other.flags() & FINAL) != 0 ||
  1115                  (m.flags() & STATIC) == 0 &&
  1116                  (other.flags() & STATIC) != 0) {
  1117             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1118                       cannotOverride(m, other),
  1119                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1120             return;
  1123         if ((m.owner.flags() & ANNOTATION) != 0) {
  1124             // handled in validateAnnotationMethod
  1125             return;
  1128         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1129         if ((origin.flags() & INTERFACE) == 0 &&
  1130                  protection(m.flags()) > protection(other.flags())) {
  1131             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1132                       cannotOverride(m, other),
  1133                       other.flags() == 0 ?
  1134                           Flag.PACKAGE :
  1135                           asFlagSet(other.flags() & AccessFlags));
  1136             return;
  1139         Type mt = types.memberType(origin.type, m);
  1140         Type ot = types.memberType(origin.type, other);
  1141         // Error if overriding result type is different
  1142         // (or, in the case of generics mode, not a subtype) of
  1143         // overridden result type. We have to rename any type parameters
  1144         // before comparing types.
  1145         List<Type> mtvars = mt.getTypeArguments();
  1146         List<Type> otvars = ot.getTypeArguments();
  1147         Type mtres = mt.getReturnType();
  1148         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1150         overrideWarner.warned = false;
  1151         boolean resultTypesOK =
  1152             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1153         if (!resultTypesOK) {
  1154             if (!source.allowCovariantReturns() &&
  1155                 m.owner != origin &&
  1156                 m.owner.isSubClass(other.owner, types)) {
  1157                 // allow limited interoperability with covariant returns
  1158             } else {
  1159                 typeError(TreeInfo.diagnosticPositionFor(m, tree),
  1160                           JCDiagnostic.fragment("override.incompatible.ret",
  1161                                          cannotOverride(m, other)),
  1162                           mtres, otres);
  1163                 return;
  1165         } else if (overrideWarner.warned) {
  1166             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1167                           "prob.found.req",
  1168                           JCDiagnostic.fragment("override.unchecked.ret",
  1169                                               uncheckedOverrides(m, other)),
  1170                           mtres, otres);
  1173         // Error if overriding method throws an exception not reported
  1174         // by overridden method.
  1175         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1176         List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
  1177         if (unhandled.nonEmpty()) {
  1178             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1179                       "override.meth.doesnt.throw",
  1180                       cannotOverride(m, other),
  1181                       unhandled.head);
  1182             return;
  1185         // Optional warning if varargs don't agree
  1186         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1187             && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
  1188             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1189                         ((m.flags() & Flags.VARARGS) != 0)
  1190                         ? "override.varargs.missing"
  1191                         : "override.varargs.extra",
  1192                         varargsOverrides(m, other));
  1195         // Warn if instance method overrides bridge method (compiler spec ??)
  1196         if ((other.flags() & BRIDGE) != 0) {
  1197             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1198                         uncheckedOverrides(m, other));
  1201         // Warn if a deprecated method overridden by a non-deprecated one.
  1202         if ((other.flags() & DEPRECATED) != 0
  1203             && (m.flags() & DEPRECATED) == 0
  1204             && m.outermostClass() != other.outermostClass()
  1205             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1206             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1209     // where
  1210         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1211             // If the method, m, is defined in an interface, then ignore the issue if the method
  1212             // is only inherited via a supertype and also implemented in the supertype,
  1213             // because in that case, we will rediscover the issue when examining the method
  1214             // in the supertype.
  1215             // If the method, m, is not defined in an interface, then the only time we need to
  1216             // address the issue is when the method is the supertype implemementation: any other
  1217             // case, we will have dealt with when examining the supertype classes
  1218             ClassSymbol mc = m.enclClass();
  1219             Type st = types.supertype(origin.type);
  1220             if (st.tag != CLASS)
  1221                 return true;
  1222             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1224             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1225                 List<Type> intfs = types.interfaces(origin.type);
  1226                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1228             else
  1229                 return (stimpl != m);
  1233     // used to check if there were any unchecked conversions
  1234     Warner overrideWarner = new Warner();
  1236     /** Check that a class does not inherit two concrete methods
  1237      *  with the same signature.
  1238      *  @param pos          Position to be used for error reporting.
  1239      *  @param site         The class type to be checked.
  1240      */
  1241     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1242         Type sup = types.supertype(site);
  1243         if (sup.tag != CLASS) return;
  1245         for (Type t1 = sup;
  1246              t1.tsym.type.isParameterized();
  1247              t1 = types.supertype(t1)) {
  1248             for (Scope.Entry e1 = t1.tsym.members().elems;
  1249                  e1 != null;
  1250                  e1 = e1.sibling) {
  1251                 Symbol s1 = e1.sym;
  1252                 if (s1.kind != MTH ||
  1253                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1254                     !s1.isInheritedIn(site.tsym, types) ||
  1255                     ((MethodSymbol)s1).implementation(site.tsym,
  1256                                                       types,
  1257                                                       true) != s1)
  1258                     continue;
  1259                 Type st1 = types.memberType(t1, s1);
  1260                 int s1ArgsLength = st1.getParameterTypes().length();
  1261                 if (st1 == s1.type) continue;
  1263                 for (Type t2 = sup;
  1264                      t2.tag == CLASS;
  1265                      t2 = types.supertype(t2)) {
  1266                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1267                          e2.scope != null;
  1268                          e2 = e2.next()) {
  1269                         Symbol s2 = e2.sym;
  1270                         if (s2 == s1 ||
  1271                             s2.kind != MTH ||
  1272                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1273                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1274                             !s2.isInheritedIn(site.tsym, types) ||
  1275                             ((MethodSymbol)s2).implementation(site.tsym,
  1276                                                               types,
  1277                                                               true) != s2)
  1278                             continue;
  1279                         Type st2 = types.memberType(t2, s2);
  1280                         if (types.overrideEquivalent(st1, st2))
  1281                             log.error(pos, "concrete.inheritance.conflict",
  1282                                       s1, t1, s2, t2, sup);
  1289     /** Check that classes (or interfaces) do not each define an abstract
  1290      *  method with same name and arguments but incompatible return types.
  1291      *  @param pos          Position to be used for error reporting.
  1292      *  @param t1           The first argument type.
  1293      *  @param t2           The second argument type.
  1294      */
  1295     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1296                                             Type t1,
  1297                                             Type t2) {
  1298         return checkCompatibleAbstracts(pos, t1, t2,
  1299                                         types.makeCompoundType(t1, t2));
  1302     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1303                                             Type t1,
  1304                                             Type t2,
  1305                                             Type site) {
  1306         Symbol sym = firstIncompatibility(t1, t2, site);
  1307         if (sym != null) {
  1308             log.error(pos, "types.incompatible.diff.ret",
  1309                       t1, t2, sym.name +
  1310                       "(" + types.memberType(t2, sym).getParameterTypes() + ")");
  1311             return false;
  1313         return true;
  1316     /** Return the first method which is defined with same args
  1317      *  but different return types in two given interfaces, or null if none
  1318      *  exists.
  1319      *  @param t1     The first type.
  1320      *  @param t2     The second type.
  1321      *  @param site   The most derived type.
  1322      *  @returns symbol from t2 that conflicts with one in t1.
  1323      */
  1324     private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
  1325         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1326         closure(t1, interfaces1);
  1327         Map<TypeSymbol,Type> interfaces2;
  1328         if (t1 == t2)
  1329             interfaces2 = interfaces1;
  1330         else
  1331             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1333         for (Type t3 : interfaces1.values()) {
  1334             for (Type t4 : interfaces2.values()) {
  1335                 Symbol s = firstDirectIncompatibility(t3, t4, site);
  1336                 if (s != null) return s;
  1339         return null;
  1342     /** Compute all the supertypes of t, indexed by type symbol. */
  1343     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1344         if (t.tag != CLASS) return;
  1345         if (typeMap.put(t.tsym, t) == null) {
  1346             closure(types.supertype(t), typeMap);
  1347             for (Type i : types.interfaces(t))
  1348                 closure(i, typeMap);
  1352     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1353     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1354         if (t.tag != CLASS) return;
  1355         if (typesSkip.get(t.tsym) != null) return;
  1356         if (typeMap.put(t.tsym, t) == null) {
  1357             closure(types.supertype(t), typesSkip, typeMap);
  1358             for (Type i : types.interfaces(t))
  1359                 closure(i, typesSkip, typeMap);
  1363     /** Return the first method in t2 that conflicts with a method from t1. */
  1364     private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
  1365         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1366             Symbol s1 = e1.sym;
  1367             Type st1 = null;
  1368             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1369             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1370             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1371             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1372                 Symbol s2 = e2.sym;
  1373                 if (s1 == s2) continue;
  1374                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1375                 if (st1 == null) st1 = types.memberType(t1, s1);
  1376                 Type st2 = types.memberType(t2, s2);
  1377                 if (types.overrideEquivalent(st1, st2)) {
  1378                     List<Type> tvars1 = st1.getTypeArguments();
  1379                     List<Type> tvars2 = st2.getTypeArguments();
  1380                     Type rt1 = st1.getReturnType();
  1381                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1382                     boolean compat =
  1383                         types.isSameType(rt1, rt2) ||
  1384                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1385                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1386                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1387                          checkCommonOverriderIn(s1,s2,site);
  1388                     if (!compat) return s2;
  1392         return null;
  1394     //WHERE
  1395     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1396         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1397         Type st1 = types.memberType(site, s1);
  1398         Type st2 = types.memberType(site, s2);
  1399         closure(site, supertypes);
  1400         for (Type t : supertypes.values()) {
  1401             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1402                 Symbol s3 = e.sym;
  1403                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1404                 Type st3 = types.memberType(site,s3);
  1405                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1406                     if (s3.owner == site.tsym) {
  1407                         return true;
  1409                     List<Type> tvars1 = st1.getTypeArguments();
  1410                     List<Type> tvars2 = st2.getTypeArguments();
  1411                     List<Type> tvars3 = st3.getTypeArguments();
  1412                     Type rt1 = st1.getReturnType();
  1413                     Type rt2 = st2.getReturnType();
  1414                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1415                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1416                     boolean compat =
  1417                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1418                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1419                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1420                     if (compat)
  1421                         return true;
  1425         return false;
  1428     /** Check that a given method conforms with any method it overrides.
  1429      *  @param tree         The tree from which positions are extracted
  1430      *                      for errors.
  1431      *  @param m            The overriding method.
  1432      */
  1433     void checkOverride(JCTree tree, MethodSymbol m) {
  1434         ClassSymbol origin = (ClassSymbol)m.owner;
  1435         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1436             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1437                 log.error(tree.pos(), "enum.no.finalize");
  1438                 return;
  1440         for (Type t = types.supertype(origin.type); t.tag == CLASS;
  1441              t = types.supertype(t)) {
  1442             TypeSymbol c = t.tsym;
  1443             Scope.Entry e = c.members().lookup(m.name);
  1444             while (e.scope != null) {
  1445                 if (m.overrides(e.sym, origin, types, false))
  1446                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1447                 else if (e.sym.isInheritedIn(origin, types) && !m.isConstructor()) {
  1448                     Type er1 = m.erasure(types);
  1449                     Type er2 = e.sym.erasure(types);
  1450                     if (types.isSameType(er1,er2)) {
  1451                             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1452                                     "name.clash.same.erasure.no.override",
  1453                                     m, m.location(),
  1454                                     e.sym, e.sym.location());
  1457                 e = e.next();
  1462     /** Check that all abstract members of given class have definitions.
  1463      *  @param pos          Position to be used for error reporting.
  1464      *  @param c            The class.
  1465      */
  1466     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1467         try {
  1468             MethodSymbol undef = firstUndef(c, c);
  1469             if (undef != null) {
  1470                 if ((c.flags() & ENUM) != 0 &&
  1471                     types.supertype(c.type).tsym == syms.enumSym &&
  1472                     (c.flags() & FINAL) == 0) {
  1473                     // add the ABSTRACT flag to an enum
  1474                     c.flags_field |= ABSTRACT;
  1475                 } else {
  1476                     MethodSymbol undef1 =
  1477                         new MethodSymbol(undef.flags(), undef.name,
  1478                                          types.memberType(c.type, undef), undef.owner);
  1479                     log.error(pos, "does.not.override.abstract",
  1480                               c, undef1, undef1.location());
  1483         } catch (CompletionFailure ex) {
  1484             completionError(pos, ex);
  1487 //where
  1488         /** Return first abstract member of class `c' that is not defined
  1489          *  in `impl', null if there is none.
  1490          */
  1491         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1492             MethodSymbol undef = null;
  1493             // Do not bother to search in classes that are not abstract,
  1494             // since they cannot have abstract members.
  1495             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1496                 Scope s = c.members();
  1497                 for (Scope.Entry e = s.elems;
  1498                      undef == null && e != null;
  1499                      e = e.sibling) {
  1500                     if (e.sym.kind == MTH &&
  1501                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1502                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1503                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1504                         if (implmeth == null || implmeth == absmeth)
  1505                             undef = absmeth;
  1508                 if (undef == null) {
  1509                     Type st = types.supertype(c.type);
  1510                     if (st.tag == CLASS)
  1511                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1513                 for (List<Type> l = types.interfaces(c.type);
  1514                      undef == null && l.nonEmpty();
  1515                      l = l.tail) {
  1516                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1519             return undef;
  1522     /** Check for cyclic references. Issue an error if the
  1523      *  symbol of the type referred to has a LOCKED flag set.
  1525      *  @param pos      Position to be used for error reporting.
  1526      *  @param t        The type referred to.
  1527      */
  1528     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1529         checkNonCyclicInternal(pos, t);
  1533     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1534         checkNonCyclic1(pos, t, new HashSet<TypeVar>());
  1537     private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) {
  1538         final TypeVar tv;
  1539         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1540             return;
  1541         if (seen.contains(t)) {
  1542             tv = (TypeVar)t;
  1543             tv.bound = new ErrorType();
  1544             log.error(pos, "cyclic.inheritance", t);
  1545         } else if (t.tag == TYPEVAR) {
  1546             tv = (TypeVar)t;
  1547             seen.add(tv);
  1548             for (Type b : types.getBounds(tv))
  1549                 checkNonCyclic1(pos, b, seen);
  1553     /** Check for cyclic references. Issue an error if the
  1554      *  symbol of the type referred to has a LOCKED flag set.
  1556      *  @param pos      Position to be used for error reporting.
  1557      *  @param t        The type referred to.
  1558      *  @returns        True if the check completed on all attributed classes
  1559      */
  1560     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1561         boolean complete = true; // was the check complete?
  1562         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1563         Symbol c = t.tsym;
  1564         if ((c.flags_field & ACYCLIC) != 0) return true;
  1566         if ((c.flags_field & LOCKED) != 0) {
  1567             noteCyclic(pos, (ClassSymbol)c);
  1568         } else if (!c.type.isErroneous()) {
  1569             try {
  1570                 c.flags_field |= LOCKED;
  1571                 if (c.type.tag == CLASS) {
  1572                     ClassType clazz = (ClassType)c.type;
  1573                     if (clazz.interfaces_field != null)
  1574                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1575                             complete &= checkNonCyclicInternal(pos, l.head);
  1576                     if (clazz.supertype_field != null) {
  1577                         Type st = clazz.supertype_field;
  1578                         if (st != null && st.tag == CLASS)
  1579                             complete &= checkNonCyclicInternal(pos, st);
  1581                     if (c.owner.kind == TYP)
  1582                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1584             } finally {
  1585                 c.flags_field &= ~LOCKED;
  1588         if (complete)
  1589             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1590         if (complete) c.flags_field |= ACYCLIC;
  1591         return complete;
  1594     /** Note that we found an inheritance cycle. */
  1595     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1596         log.error(pos, "cyclic.inheritance", c);
  1597         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1598             l.head = new ErrorType((ClassSymbol)l.head.tsym);
  1599         Type st = types.supertype(c.type);
  1600         if (st.tag == CLASS)
  1601             ((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym);
  1602         c.type = new ErrorType(c);
  1603         c.flags_field |= ACYCLIC;
  1606     /** Check that all methods which implement some
  1607      *  method conform to the method they implement.
  1608      *  @param tree         The class definition whose members are checked.
  1609      */
  1610     void checkImplementations(JCClassDecl tree) {
  1611         checkImplementations(tree, tree.sym);
  1613 //where
  1614         /** Check that all methods which implement some
  1615          *  method in `ic' conform to the method they implement.
  1616          */
  1617         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1618             ClassSymbol origin = tree.sym;
  1619             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1620                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1621                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1622                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  1623                         if (e.sym.kind == MTH &&
  1624                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  1625                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  1626                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  1627                             if (implmeth != null && implmeth != absmeth &&
  1628                                 (implmeth.owner.flags() & INTERFACE) ==
  1629                                 (origin.flags() & INTERFACE)) {
  1630                                 // don't check if implmeth is in a class, yet
  1631                                 // origin is an interface. This case arises only
  1632                                 // if implmeth is declared in Object. The reason is
  1633                                 // that interfaces really don't inherit from
  1634                                 // Object it's just that the compiler represents
  1635                                 // things that way.
  1636                                 checkOverride(tree, implmeth, absmeth, origin);
  1644     /** Check that all abstract methods implemented by a class are
  1645      *  mutually compatible.
  1646      *  @param pos          Position to be used for error reporting.
  1647      *  @param c            The class whose interfaces are checked.
  1648      */
  1649     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  1650         List<Type> supertypes = types.interfaces(c);
  1651         Type supertype = types.supertype(c);
  1652         if (supertype.tag == CLASS &&
  1653             (supertype.tsym.flags() & ABSTRACT) != 0)
  1654             supertypes = supertypes.prepend(supertype);
  1655         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  1656             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  1657                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  1658                 return;
  1659             for (List<Type> m = supertypes; m != l; m = m.tail)
  1660                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  1661                     return;
  1663         checkCompatibleConcretes(pos, c);
  1666     /** Check that class c does not implement directly or indirectly
  1667      *  the same parameterized interface with two different argument lists.
  1668      *  @param pos          Position to be used for error reporting.
  1669      *  @param type         The type whose interfaces are checked.
  1670      */
  1671     void checkClassBounds(DiagnosticPosition pos, Type type) {
  1672         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  1674 //where
  1675         /** Enter all interfaces of type `type' into the hash table `seensofar'
  1676          *  with their class symbol as key and their type as value. Make
  1677          *  sure no class is entered with two different types.
  1678          */
  1679         void checkClassBounds(DiagnosticPosition pos,
  1680                               Map<TypeSymbol,Type> seensofar,
  1681                               Type type) {
  1682             if (type.isErroneous()) return;
  1683             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  1684                 Type it = l.head;
  1685                 Type oldit = seensofar.put(it.tsym, it);
  1686                 if (oldit != null) {
  1687                     List<Type> oldparams = oldit.allparams();
  1688                     List<Type> newparams = it.allparams();
  1689                     if (!types.containsTypeEquivalent(oldparams, newparams))
  1690                         log.error(pos, "cant.inherit.diff.arg",
  1691                                   it.tsym, Type.toString(oldparams),
  1692                                   Type.toString(newparams));
  1694                 checkClassBounds(pos, seensofar, it);
  1696             Type st = types.supertype(type);
  1697             if (st != null) checkClassBounds(pos, seensofar, st);
  1700     /** Enter interface into into set.
  1701      *  If it existed already, issue a "repeated interface" error.
  1702      */
  1703     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  1704         if (its.contains(it))
  1705             log.error(pos, "repeated.interface");
  1706         else {
  1707             its.add(it);
  1711 /* *************************************************************************
  1712  * Check annotations
  1713  **************************************************************************/
  1715     /** Annotation types are restricted to primitives, String, an
  1716      *  enum, an annotation, Class, Class<?>, Class<? extends
  1717      *  Anything>, arrays of the preceding.
  1718      */
  1719     void validateAnnotationType(JCTree restype) {
  1720         // restype may be null if an error occurred, so don't bother validating it
  1721         if (restype != null) {
  1722             validateAnnotationType(restype.pos(), restype.type);
  1726     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  1727         if (type.isPrimitive()) return;
  1728         if (types.isSameType(type, syms.stringType)) return;
  1729         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  1730         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  1731         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  1732         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  1733             validateAnnotationType(pos, types.elemtype(type));
  1734             return;
  1736         log.error(pos, "invalid.annotation.member.type");
  1739     /**
  1740      * "It is also a compile-time error if any method declared in an
  1741      * annotation type has a signature that is override-equivalent to
  1742      * that of any public or protected method declared in class Object
  1743      * or in the interface annotation.Annotation."
  1745      * @jls3 9.6 Annotation Types
  1746      */
  1747     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  1748         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  1749             Scope s = sup.tsym.members();
  1750             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  1751                 if (e.sym.kind == MTH &&
  1752                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  1753                     types.overrideEquivalent(m.type, e.sym.type))
  1754                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  1759     /** Check the annotations of a symbol.
  1760      */
  1761     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  1762         if (skipAnnotations) return;
  1763         for (JCAnnotation a : annotations)
  1764             validateAnnotation(a, s);
  1767     /** Check an annotation of a symbol.
  1768      */
  1769     public void validateAnnotation(JCAnnotation a, Symbol s) {
  1770         validateAnnotation(a);
  1772         if (!annotationApplicable(a, s))
  1773             log.error(a.pos(), "annotation.type.not.applicable");
  1775         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1776             if (!isOverrider(s))
  1777                 log.error(a.pos(), "method.does.not.override.superclass");
  1781     /** Is s a method symbol that overrides a method in a superclass? */
  1782     boolean isOverrider(Symbol s) {
  1783         if (s.kind != MTH || s.isStatic())
  1784             return false;
  1785         MethodSymbol m = (MethodSymbol)s;
  1786         TypeSymbol owner = (TypeSymbol)m.owner;
  1787         for (Type sup : types.closure(owner.type)) {
  1788             if (sup == owner.type)
  1789                 continue; // skip "this"
  1790             Scope scope = sup.tsym.members();
  1791             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  1792                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  1793                     return true;
  1796         return false;
  1799     /** Is the annotation applicable to the symbol? */
  1800     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  1801         Attribute.Compound atTarget =
  1802             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1803         if (atTarget == null) return true;
  1804         Attribute atValue = atTarget.member(names.value);
  1805         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1806         Attribute.Array arr = (Attribute.Array) atValue;
  1807         for (Attribute app : arr.values) {
  1808             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1809             Attribute.Enum e = (Attribute.Enum) app;
  1810             if (e.value.name == names.TYPE)
  1811                 { if (s.kind == TYP) return true; }
  1812             else if (e.value.name == names.FIELD)
  1813                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  1814             else if (e.value.name == names.METHOD)
  1815                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  1816             else if (e.value.name == names.PARAMETER)
  1817                 { if (s.kind == VAR &&
  1818                       s.owner.kind == MTH &&
  1819                       (s.flags() & PARAMETER) != 0)
  1820                     return true;
  1822             else if (e.value.name == names.CONSTRUCTOR)
  1823                 { if (s.kind == MTH && s.isConstructor()) return true; }
  1824             else if (e.value.name == names.LOCAL_VARIABLE)
  1825                 { if (s.kind == VAR && s.owner.kind == MTH &&
  1826                       (s.flags() & PARAMETER) == 0)
  1827                     return true;
  1829             else if (e.value.name == names.ANNOTATION_TYPE)
  1830                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  1831                     return true;
  1833             else if (e.value.name == names.PACKAGE)
  1834                 { if (s.kind == PCK) return true; }
  1835             else
  1836                 return true; // recovery
  1838         return false;
  1841     /** Check an annotation value.
  1842      */
  1843     public void validateAnnotation(JCAnnotation a) {
  1844         if (a.type.isErroneous()) return;
  1846         // collect an inventory of the members
  1847         Set<MethodSymbol> members = new HashSet<MethodSymbol>();
  1848         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  1849              e != null;
  1850              e = e.sibling)
  1851             if (e.sym.kind == MTH)
  1852                 members.add((MethodSymbol) e.sym);
  1854         // count them off as they're annotated
  1855         for (JCTree arg : a.args) {
  1856             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  1857             JCAssign assign = (JCAssign) arg;
  1858             Symbol m = TreeInfo.symbol(assign.lhs);
  1859             if (m == null || m.type.isErroneous()) continue;
  1860             if (!members.remove(m))
  1861                 log.error(arg.pos(), "duplicate.annotation.member.value",
  1862                           m.name, a.type);
  1863             if (assign.rhs.getTag() == ANNOTATION)
  1864                 validateAnnotation((JCAnnotation)assign.rhs);
  1867         // all the remaining ones better have default values
  1868         for (MethodSymbol m : members)
  1869             if (m.defaultValue == null && !m.type.isErroneous())
  1870                 log.error(a.pos(), "annotation.missing.default.value",
  1871                           a.type, m.name);
  1873         // special case: java.lang.annotation.Target must not have
  1874         // repeated values in its value member
  1875         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  1876             a.args.tail == null)
  1877             return;
  1879         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  1880         JCAssign assign = (JCAssign) a.args.head;
  1881         Symbol m = TreeInfo.symbol(assign.lhs);
  1882         if (m.name != names.value) return;
  1883         JCTree rhs = assign.rhs;
  1884         if (rhs.getTag() != JCTree.NEWARRAY) return;
  1885         JCNewArray na = (JCNewArray) rhs;
  1886         Set<Symbol> targets = new HashSet<Symbol>();
  1887         for (JCTree elem : na.elems) {
  1888             if (!targets.add(TreeInfo.symbol(elem))) {
  1889                 log.error(elem.pos(), "repeated.annotation.target");
  1894     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  1895         if (allowAnnotations &&
  1896             lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
  1897             (s.flags() & DEPRECATED) != 0 &&
  1898             !syms.deprecatedType.isErroneous() &&
  1899             s.attribute(syms.deprecatedType.tsym) == null) {
  1900             log.warning(pos, "missing.deprecated.annotation");
  1904 /* *************************************************************************
  1905  * Check for recursive annotation elements.
  1906  **************************************************************************/
  1908     /** Check for cycles in the graph of annotation elements.
  1909      */
  1910     void checkNonCyclicElements(JCClassDecl tree) {
  1911         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  1912         assert (tree.sym.flags_field & LOCKED) == 0;
  1913         try {
  1914             tree.sym.flags_field |= LOCKED;
  1915             for (JCTree def : tree.defs) {
  1916                 if (def.getTag() != JCTree.METHODDEF) continue;
  1917                 JCMethodDecl meth = (JCMethodDecl)def;
  1918                 checkAnnotationResType(meth.pos(), meth.restype.type);
  1920         } finally {
  1921             tree.sym.flags_field &= ~LOCKED;
  1922             tree.sym.flags_field |= ACYCLIC_ANN;
  1926     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  1927         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  1928             return;
  1929         if ((tsym.flags_field & LOCKED) != 0) {
  1930             log.error(pos, "cyclic.annotation.element");
  1931             return;
  1933         try {
  1934             tsym.flags_field |= LOCKED;
  1935             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  1936                 Symbol s = e.sym;
  1937                 if (s.kind != Kinds.MTH)
  1938                     continue;
  1939                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  1941         } finally {
  1942             tsym.flags_field &= ~LOCKED;
  1943             tsym.flags_field |= ACYCLIC_ANN;
  1947     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  1948         switch (type.tag) {
  1949         case TypeTags.CLASS:
  1950             if ((type.tsym.flags() & ANNOTATION) != 0)
  1951                 checkNonCyclicElementsInternal(pos, type.tsym);
  1952             break;
  1953         case TypeTags.ARRAY:
  1954             checkAnnotationResType(pos, types.elemtype(type));
  1955             break;
  1956         default:
  1957             break; // int etc
  1961 /* *************************************************************************
  1962  * Check for cycles in the constructor call graph.
  1963  **************************************************************************/
  1965     /** Check for cycles in the graph of constructors calling other
  1966      *  constructors.
  1967      */
  1968     void checkCyclicConstructors(JCClassDecl tree) {
  1969         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  1971         // enter each constructor this-call into the map
  1972         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1973             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  1974             if (app == null) continue;
  1975             JCMethodDecl meth = (JCMethodDecl) l.head;
  1976             if (TreeInfo.name(app.meth) == names._this) {
  1977                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  1978             } else {
  1979                 meth.sym.flags_field |= ACYCLIC;
  1983         // Check for cycles in the map
  1984         Symbol[] ctors = new Symbol[0];
  1985         ctors = callMap.keySet().toArray(ctors);
  1986         for (Symbol caller : ctors) {
  1987             checkCyclicConstructor(tree, caller, callMap);
  1991     /** Look in the map to see if the given constructor is part of a
  1992      *  call cycle.
  1993      */
  1994     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  1995                                         Map<Symbol,Symbol> callMap) {
  1996         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  1997             if ((ctor.flags_field & LOCKED) != 0) {
  1998                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  1999                           "recursive.ctor.invocation");
  2000             } else {
  2001                 ctor.flags_field |= LOCKED;
  2002                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2003                 ctor.flags_field &= ~LOCKED;
  2005             ctor.flags_field |= ACYCLIC;
  2009 /* *************************************************************************
  2010  * Miscellaneous
  2011  **************************************************************************/
  2013     /**
  2014      * Return the opcode of the operator but emit an error if it is an
  2015      * error.
  2016      * @param pos        position for error reporting.
  2017      * @param operator   an operator
  2018      * @param tag        a tree tag
  2019      * @param left       type of left hand side
  2020      * @param right      type of right hand side
  2021      */
  2022     int checkOperator(DiagnosticPosition pos,
  2023                        OperatorSymbol operator,
  2024                        int tag,
  2025                        Type left,
  2026                        Type right) {
  2027         if (operator.opcode == ByteCodes.error) {
  2028             log.error(pos,
  2029                       "operator.cant.be.applied",
  2030                       treeinfo.operatorName(tag),
  2031                       List.of(left, right));
  2033         return operator.opcode;
  2037     /**
  2038      *  Check for division by integer constant zero
  2039      *  @param pos           Position for error reporting.
  2040      *  @param operator      The operator for the expression
  2041      *  @param operand       The right hand operand for the expression
  2042      */
  2043     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2044         if (operand.constValue() != null
  2045             && lint.isEnabled(Lint.LintCategory.DIVZERO)
  2046             && operand.tag <= LONG
  2047             && ((Number) (operand.constValue())).longValue() == 0) {
  2048             int opc = ((OperatorSymbol)operator).opcode;
  2049             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2050                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2051                 log.warning(pos, "div.zero");
  2056     /**
  2057      * Check for empty statements after if
  2058      */
  2059     void checkEmptyIf(JCIf tree) {
  2060         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
  2061             log.warning(tree.thenpart.pos(), "empty.if");
  2064     /** Check that symbol is unique in given scope.
  2065      *  @param pos           Position for error reporting.
  2066      *  @param sym           The symbol.
  2067      *  @param s             The scope.
  2068      */
  2069     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2070         if (sym.type.isErroneous())
  2071             return true;
  2072         if (sym.owner.name == names.any) return false;
  2073         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2074             if (sym != e.sym &&
  2075                 sym.kind == e.sym.kind &&
  2076                 sym.name != names.error &&
  2077                 (sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) {
  2078                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2079                     varargsDuplicateError(pos, sym, e.sym);
  2080                 else
  2081                     duplicateError(pos, e.sym);
  2082                 return false;
  2085         return true;
  2088     /** Check that single-type import is not already imported or top-level defined,
  2089      *  but make an exception for two single-type imports which denote the same type.
  2090      *  @param pos           Position for error reporting.
  2091      *  @param sym           The symbol.
  2092      *  @param s             The scope
  2093      */
  2094     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2095         return checkUniqueImport(pos, sym, s, false);
  2098     /** Check that static single-type import is not already imported or top-level defined,
  2099      *  but make an exception for two single-type imports which denote the same type.
  2100      *  @param pos           Position for error reporting.
  2101      *  @param sym           The symbol.
  2102      *  @param s             The scope
  2103      *  @param staticImport  Whether or not this was a static import
  2104      */
  2105     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2106         return checkUniqueImport(pos, sym, s, true);
  2109     /** Check that single-type import is not already imported or top-level defined,
  2110      *  but make an exception for two single-type imports which denote the same type.
  2111      *  @param pos           Position for error reporting.
  2112      *  @param sym           The symbol.
  2113      *  @param s             The scope.
  2114      *  @param staticImport  Whether or not this was a static import
  2115      */
  2116     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2117         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2118             // is encountered class entered via a class declaration?
  2119             boolean isClassDecl = e.scope == s;
  2120             if ((isClassDecl || sym != e.sym) &&
  2121                 sym.kind == e.sym.kind &&
  2122                 sym.name != names.error) {
  2123                 if (!e.sym.type.isErroneous()) {
  2124                     String what = e.sym.toString();
  2125                     if (!isClassDecl) {
  2126                         if (staticImport)
  2127                             log.error(pos, "already.defined.static.single.import", what);
  2128                         else
  2129                             log.error(pos, "already.defined.single.import", what);
  2131                     else if (sym != e.sym)
  2132                         log.error(pos, "already.defined.this.unit", what);
  2134                 return false;
  2137         return true;
  2140     /** Check that a qualified name is in canonical form (for import decls).
  2141      */
  2142     public void checkCanonical(JCTree tree) {
  2143         if (!isCanonical(tree))
  2144             log.error(tree.pos(), "import.requires.canonical",
  2145                       TreeInfo.symbol(tree));
  2147         // where
  2148         private boolean isCanonical(JCTree tree) {
  2149             while (tree.getTag() == JCTree.SELECT) {
  2150                 JCFieldAccess s = (JCFieldAccess) tree;
  2151                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2152                     return false;
  2153                 tree = s.selected;
  2155             return true;
  2158     private class ConversionWarner extends Warner {
  2159         final String key;
  2160         final Type found;
  2161         final Type expected;
  2162         public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
  2163             super(pos);
  2164             this.key = key;
  2165             this.found = found;
  2166             this.expected = expected;
  2169         public void warnUnchecked() {
  2170             boolean warned = this.warned;
  2171             super.warnUnchecked();
  2172             if (warned) return; // suppress redundant diagnostics
  2173             Object problem = JCDiagnostic.fragment(key);
  2174             Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
  2178     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2179         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2182     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2183         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial