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

Thu, 24 Jul 2008 10:35:38 +0100

author
mcimadamore
date
Thu, 24 Jul 2008 10:35:38 +0100
changeset 78
77dba8b57346
parent 62
07c916ecfc71
child 79
36df13bde238
permissions
-rw-r--r--

6651719: Compiler crashes possibly during forward reference of TypeParameter
Summary: compiler should apply capture conversion when checking for bound conformance
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 instanceof CapturedType)) {
   426             a = types.upperBound(a);
   427             for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
   428                 if (!types.isSubtype(a, l.head)) {
   429                     log.error(pos, "not.within.bounds", a);
   430                     return;
   431                 }
   432             }
   433         }
   434         else {
   435             CapturedType ct = (CapturedType)a;
   436             boolean ok = false;
   437             switch (ct.wildcard.kind) {
   438                 case EXTENDS:
   439                     ok = types.isCastable(bs.getUpperBound(),
   440                             types.upperBound(a),
   441                             Warner.noWarnings);
   442                     break;
   443                 case SUPER:
   444                     ok = !types.notSoftSubtype(types.lowerBound(a),
   445                             bs.getUpperBound());
   446                     break;
   447                 case UNBOUND:
   448                     ok = true;
   449             }
   450             if (!ok)
   451                 log.error(pos, "not.within.bounds", a);
   452         }
   453     }
   455     /** Check that type is different from 'void'.
   456      *  @param pos           Position to be used for error reporting.
   457      *  @param t             The type to be checked.
   458      */
   459     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   460         if (t.tag == VOID) {
   461             log.error(pos, "void.not.allowed.here");
   462             return syms.errType;
   463         } else {
   464             return t;
   465         }
   466     }
   468     /** Check that type is a class or interface type.
   469      *  @param pos           Position to be used for error reporting.
   470      *  @param t             The type to be checked.
   471      */
   472     Type checkClassType(DiagnosticPosition pos, Type t) {
   473         if (t.tag != CLASS && t.tag != ERROR)
   474             return typeTagError(pos,
   475                                 JCDiagnostic.fragment("type.req.class"),
   476                                 (t.tag == TYPEVAR)
   477                                 ? JCDiagnostic.fragment("type.parameter", t)
   478                                 : t);
   479         else
   480             return t;
   481     }
   483     /** Check that type is a class or interface type.
   484      *  @param pos           Position to be used for error reporting.
   485      *  @param t             The type to be checked.
   486      *  @param noBounds    True if type bounds are illegal here.
   487      */
   488     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   489         t = checkClassType(pos, t);
   490         if (noBounds && t.isParameterized()) {
   491             List<Type> args = t.getTypeArguments();
   492             while (args.nonEmpty()) {
   493                 if (args.head.tag == WILDCARD)
   494                     return typeTagError(pos,
   495                                         log.getLocalizedString("type.req.exact"),
   496                                         args.head);
   497                 args = args.tail;
   498             }
   499         }
   500         return t;
   501     }
   503     /** Check that type is a reifiable class, interface or array type.
   504      *  @param pos           Position to be used for error reporting.
   505      *  @param t             The type to be checked.
   506      */
   507     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   508         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   509             return typeTagError(pos,
   510                                 JCDiagnostic.fragment("type.req.class.array"),
   511                                 t);
   512         } else if (!types.isReifiable(t)) {
   513             log.error(pos, "illegal.generic.type.for.instof");
   514             return syms.errType;
   515         } else {
   516             return t;
   517         }
   518     }
   520     /** Check that type is a reference type, i.e. a class, interface or array type
   521      *  or a type variable.
   522      *  @param pos           Position to be used for error reporting.
   523      *  @param t             The type to be checked.
   524      */
   525     Type checkRefType(DiagnosticPosition pos, Type t) {
   526         switch (t.tag) {
   527         case CLASS:
   528         case ARRAY:
   529         case TYPEVAR:
   530         case WILDCARD:
   531         case ERROR:
   532             return t;
   533         default:
   534             return typeTagError(pos,
   535                                 JCDiagnostic.fragment("type.req.ref"),
   536                                 t);
   537         }
   538     }
   540     /** Check that type is a null or reference type.
   541      *  @param pos           Position to be used for error reporting.
   542      *  @param t             The type to be checked.
   543      */
   544     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   545         switch (t.tag) {
   546         case CLASS:
   547         case ARRAY:
   548         case TYPEVAR:
   549         case WILDCARD:
   550         case BOT:
   551         case ERROR:
   552             return t;
   553         default:
   554             return typeTagError(pos,
   555                                 JCDiagnostic.fragment("type.req.ref"),
   556                                 t);
   557         }
   558     }
   560     /** Check that flag set does not contain elements of two conflicting sets. s
   561      *  Return true if it doesn't.
   562      *  @param pos           Position to be used for error reporting.
   563      *  @param flags         The set of flags to be checked.
   564      *  @param set1          Conflicting flags set #1.
   565      *  @param set2          Conflicting flags set #2.
   566      */
   567     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   568         if ((flags & set1) != 0 && (flags & set2) != 0) {
   569             log.error(pos,
   570                       "illegal.combination.of.modifiers",
   571                       TreeInfo.flagNames(TreeInfo.firstFlag(flags & set1)),
   572                       TreeInfo.flagNames(TreeInfo.firstFlag(flags & set2)));
   573             return false;
   574         } else
   575             return true;
   576     }
   578     /** Check that given modifiers are legal for given symbol and
   579      *  return modifiers together with any implicit modififiers for that symbol.
   580      *  Warning: we can't use flags() here since this method
   581      *  is called during class enter, when flags() would cause a premature
   582      *  completion.
   583      *  @param pos           Position to be used for error reporting.
   584      *  @param flags         The set of modifiers given in a definition.
   585      *  @param sym           The defined symbol.
   586      */
   587     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   588         long mask;
   589         long implicit = 0;
   590         switch (sym.kind) {
   591         case VAR:
   592             if (sym.owner.kind != TYP)
   593                 mask = LocalVarFlags;
   594             else if ((sym.owner.flags_field & INTERFACE) != 0)
   595                 mask = implicit = InterfaceVarFlags;
   596             else
   597                 mask = VarFlags;
   598             break;
   599         case MTH:
   600             if (sym.name == names.init) {
   601                 if ((sym.owner.flags_field & ENUM) != 0) {
   602                     // enum constructors cannot be declared public or
   603                     // protected and must be implicitly or explicitly
   604                     // private
   605                     implicit = PRIVATE;
   606                     mask = PRIVATE;
   607                 } else
   608                     mask = ConstructorFlags;
   609             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   610                 mask = implicit = InterfaceMethodFlags;
   611             else {
   612                 mask = MethodFlags;
   613             }
   614             // Imply STRICTFP if owner has STRICTFP set.
   615             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   616               implicit |= sym.owner.flags_field & STRICTFP;
   617             break;
   618         case TYP:
   619             if (sym.isLocal()) {
   620                 mask = LocalClassFlags;
   621                 if (sym.name.len == 0) { // Anonymous class
   622                     // Anonymous classes in static methods are themselves static;
   623                     // that's why we admit STATIC here.
   624                     mask |= STATIC;
   625                     // JLS: Anonymous classes are final.
   626                     implicit |= FINAL;
   627                 }
   628                 if ((sym.owner.flags_field & STATIC) == 0 &&
   629                     (flags & ENUM) != 0)
   630                     log.error(pos, "enums.must.be.static");
   631             } else if (sym.owner.kind == TYP) {
   632                 mask = MemberClassFlags;
   633                 if (sym.owner.owner.kind == PCK ||
   634                     (sym.owner.flags_field & STATIC) != 0)
   635                     mask |= STATIC;
   636                 else if ((flags & ENUM) != 0)
   637                     log.error(pos, "enums.must.be.static");
   638                 // Nested interfaces and enums are always STATIC (Spec ???)
   639                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   640             } else {
   641                 mask = ClassFlags;
   642             }
   643             // Interfaces are always ABSTRACT
   644             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   646             if ((flags & ENUM) != 0) {
   647                 // enums can't be declared abstract or final
   648                 mask &= ~(ABSTRACT | FINAL);
   649                 implicit |= implicitEnumFinalFlag(tree);
   650             }
   651             // Imply STRICTFP if owner has STRICTFP set.
   652             implicit |= sym.owner.flags_field & STRICTFP;
   653             break;
   654         default:
   655             throw new AssertionError();
   656         }
   657         long illegal = flags & StandardFlags & ~mask;
   658         if (illegal != 0) {
   659             if ((illegal & INTERFACE) != 0) {
   660                 log.error(pos, "intf.not.allowed.here");
   661                 mask |= INTERFACE;
   662             }
   663             else {
   664                 log.error(pos,
   665                           "mod.not.allowed.here", TreeInfo.flagNames(illegal));
   666             }
   667         }
   668         else if ((sym.kind == TYP ||
   669                   // ISSUE: Disallowing abstract&private is no longer appropriate
   670                   // in the presence of inner classes. Should it be deleted here?
   671                   checkDisjoint(pos, flags,
   672                                 ABSTRACT,
   673                                 PRIVATE | STATIC))
   674                  &&
   675                  checkDisjoint(pos, flags,
   676                                ABSTRACT | INTERFACE,
   677                                FINAL | NATIVE | SYNCHRONIZED)
   678                  &&
   679                  checkDisjoint(pos, flags,
   680                                PUBLIC,
   681                                PRIVATE | PROTECTED)
   682                  &&
   683                  checkDisjoint(pos, flags,
   684                                PRIVATE,
   685                                PUBLIC | PROTECTED)
   686                  &&
   687                  checkDisjoint(pos, flags,
   688                                FINAL,
   689                                VOLATILE)
   690                  &&
   691                  (sym.kind == TYP ||
   692                   checkDisjoint(pos, flags,
   693                                 ABSTRACT | NATIVE,
   694                                 STRICTFP))) {
   695             // skip
   696         }
   697         return flags & (mask | ~StandardFlags) | implicit;
   698     }
   701     /** Determine if this enum should be implicitly final.
   702      *
   703      *  If the enum has no specialized enum contants, it is final.
   704      *
   705      *  If the enum does have specialized enum contants, it is
   706      *  <i>not</i> final.
   707      */
   708     private long implicitEnumFinalFlag(JCTree tree) {
   709         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   710         class SpecialTreeVisitor extends JCTree.Visitor {
   711             boolean specialized;
   712             SpecialTreeVisitor() {
   713                 this.specialized = false;
   714             };
   716             public void visitTree(JCTree tree) { /* no-op */ }
   718             public void visitVarDef(JCVariableDecl tree) {
   719                 if ((tree.mods.flags & ENUM) != 0) {
   720                     if (tree.init instanceof JCNewClass &&
   721                         ((JCNewClass) tree.init).def != null) {
   722                         specialized = true;
   723                     }
   724                 }
   725             }
   726         }
   728         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   729         JCClassDecl cdef = (JCClassDecl) tree;
   730         for (JCTree defs: cdef.defs) {
   731             defs.accept(sts);
   732             if (sts.specialized) return 0;
   733         }
   734         return FINAL;
   735     }
   737 /* *************************************************************************
   738  * Type Validation
   739  **************************************************************************/
   741     /** Validate a type expression. That is,
   742      *  check that all type arguments of a parametric type are within
   743      *  their bounds. This must be done in a second phase after type attributon
   744      *  since a class might have a subclass as type parameter bound. E.g:
   745      *
   746      *  class B<A extends C> { ... }
   747      *  class C extends B<C> { ... }
   748      *
   749      *  and we can't make sure that the bound is already attributed because
   750      *  of possible cycles.
   751      */
   752     private Validator validator = new Validator();
   754     /** Visitor method: Validate a type expression, if it is not null, catching
   755      *  and reporting any completion failures.
   756      */
   757     void validate(JCTree tree) {
   758         try {
   759             if (tree != null) tree.accept(validator);
   760         } catch (CompletionFailure ex) {
   761             completionError(tree.pos(), ex);
   762         }
   763     }
   765     /** Visitor method: Validate a list of type expressions.
   766      */
   767     void validate(List<? extends JCTree> trees) {
   768         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   769             validate(l.head);
   770     }
   772     /** Visitor method: Validate a list of type parameters.
   773      */
   774     void validateTypeParams(List<JCTypeParameter> trees) {
   775         for (List<JCTypeParameter> l = trees; l.nonEmpty(); l = l.tail)
   776             validate(l.head);
   777     }
   779     /** A visitor class for type validation.
   780      */
   781     class Validator extends JCTree.Visitor {
   783         public void visitTypeArray(JCArrayTypeTree tree) {
   784             validate(tree.elemtype);
   785         }
   787         public void visitTypeApply(JCTypeApply tree) {
   788             if (tree.type.tag == CLASS) {
   789                 List<Type> formals = tree.type.tsym.type.getTypeArguments();
   790                 List<Type> actuals = types.capture(tree.type).getTypeArguments();
   791                 List<JCExpression> args = tree.arguments;
   792                 List<Type> forms = formals;
   793                 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>();
   795                 // For matching pairs of actual argument types `a' and
   796                 // formal type parameters with declared bound `b' ...
   797                 while (args.nonEmpty() && forms.nonEmpty()) {
   798                     validate(args.head);
   800                     // exact type arguments needs to know their
   801                     // bounds (for upper and lower bound
   802                     // calculations).  So we create new TypeVars with
   803                     // bounds substed with actuals.
   804                     tvars_buf.append(types.substBound(((TypeVar)forms.head),
   805                                                       formals,
   806                                                       actuals));
   808                     args = args.tail;
   809                     forms = forms.tail;
   810                 }
   812                 args = tree.arguments;
   813                 List<TypeVar> tvars = tvars_buf.toList();
   814                 while (args.nonEmpty() && tvars.nonEmpty()) {
   815                     // Let the actual arguments know their bound
   816                     args.head.type.withTypeVar(tvars.head);
   817                     args = args.tail;
   818                     tvars = tvars.tail;
   819                 }
   821                 args = tree.arguments;
   822                 tvars = tvars_buf.toList();
   823                 while (args.nonEmpty() && tvars.nonEmpty()) {
   824                     checkExtends(args.head.pos(),
   825                                  actuals.head,
   826                                  tvars.head);
   827                     args = args.tail;
   828                     tvars = tvars.tail;
   829                     actuals = actuals.tail;
   830                 }
   832                 // Check that this type is either fully parameterized, or
   833                 // not parameterized at all.
   834                 if (tree.type.getEnclosingType().isRaw())
   835                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
   836                 if (tree.clazz.getTag() == JCTree.SELECT)
   837                     visitSelectInternal((JCFieldAccess)tree.clazz);
   838             }
   839         }
   841         public void visitTypeParameter(JCTypeParameter tree) {
   842             validate(tree.bounds);
   843             checkClassBounds(tree.pos(), tree.type);
   844         }
   846         @Override
   847         public void visitWildcard(JCWildcard tree) {
   848             if (tree.inner != null)
   849                 validate(tree.inner);
   850         }
   852         public void visitSelect(JCFieldAccess tree) {
   853             if (tree.type.tag == CLASS) {
   854                 visitSelectInternal(tree);
   856                 // Check that this type is either fully parameterized, or
   857                 // not parameterized at all.
   858                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
   859                     log.error(tree.pos(), "improperly.formed.type.param.missing");
   860             }
   861         }
   862         public void visitSelectInternal(JCFieldAccess tree) {
   863             if (tree.type.getEnclosingType().tag != CLASS &&
   864                 tree.selected.type.isParameterized()) {
   865                 // The enclosing type is not a class, so we are
   866                 // looking at a static member type.  However, the
   867                 // qualifying expression is parameterized.
   868                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
   869             } else {
   870                 // otherwise validate the rest of the expression
   871                 validate(tree.selected);
   872             }
   873         }
   875         /** Default visitor method: do nothing.
   876          */
   877         public void visitTree(JCTree tree) {
   878         }
   879     }
   881 /* *************************************************************************
   882  * Exception checking
   883  **************************************************************************/
   885     /* The following methods treat classes as sets that contain
   886      * the class itself and all their subclasses
   887      */
   889     /** Is given type a subtype of some of the types in given list?
   890      */
   891     boolean subset(Type t, List<Type> ts) {
   892         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   893             if (types.isSubtype(t, l.head)) return true;
   894         return false;
   895     }
   897     /** Is given type a subtype or supertype of
   898      *  some of the types in given list?
   899      */
   900     boolean intersects(Type t, List<Type> ts) {
   901         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   902             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
   903         return false;
   904     }
   906     /** Add type set to given type list, unless it is a subclass of some class
   907      *  in the list.
   908      */
   909     List<Type> incl(Type t, List<Type> ts) {
   910         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
   911     }
   913     /** Remove type set from type set list.
   914      */
   915     List<Type> excl(Type t, List<Type> ts) {
   916         if (ts.isEmpty()) {
   917             return ts;
   918         } else {
   919             List<Type> ts1 = excl(t, ts.tail);
   920             if (types.isSubtype(ts.head, t)) return ts1;
   921             else if (ts1 == ts.tail) return ts;
   922             else return ts1.prepend(ts.head);
   923         }
   924     }
   926     /** Form the union of two type set lists.
   927      */
   928     List<Type> union(List<Type> ts1, List<Type> ts2) {
   929         List<Type> ts = ts1;
   930         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   931             ts = incl(l.head, ts);
   932         return ts;
   933     }
   935     /** Form the difference of two type lists.
   936      */
   937     List<Type> diff(List<Type> ts1, List<Type> ts2) {
   938         List<Type> ts = ts1;
   939         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   940             ts = excl(l.head, ts);
   941         return ts;
   942     }
   944     /** Form the intersection of two type lists.
   945      */
   946     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
   947         List<Type> ts = List.nil();
   948         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
   949             if (subset(l.head, ts2)) ts = incl(l.head, ts);
   950         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   951             if (subset(l.head, ts1)) ts = incl(l.head, ts);
   952         return ts;
   953     }
   955     /** Is exc an exception symbol that need not be declared?
   956      */
   957     boolean isUnchecked(ClassSymbol exc) {
   958         return
   959             exc.kind == ERR ||
   960             exc.isSubClass(syms.errorType.tsym, types) ||
   961             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
   962     }
   964     /** Is exc an exception type that need not be declared?
   965      */
   966     boolean isUnchecked(Type exc) {
   967         return
   968             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
   969             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
   970             exc.tag == BOT;
   971     }
   973     /** Same, but handling completion failures.
   974      */
   975     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
   976         try {
   977             return isUnchecked(exc);
   978         } catch (CompletionFailure ex) {
   979             completionError(pos, ex);
   980             return true;
   981         }
   982     }
   984     /** Is exc handled by given exception list?
   985      */
   986     boolean isHandled(Type exc, List<Type> handled) {
   987         return isUnchecked(exc) || subset(exc, handled);
   988     }
   990     /** Return all exceptions in thrown list that are not in handled list.
   991      *  @param thrown     The list of thrown exceptions.
   992      *  @param handled    The list of handled exceptions.
   993      */
   994     List<Type> unHandled(List<Type> thrown, List<Type> handled) {
   995         List<Type> unhandled = List.nil();
   996         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
   997             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
   998         return unhandled;
   999     }
  1001 /* *************************************************************************
  1002  * Overriding/Implementation checking
  1003  **************************************************************************/
  1005     /** The level of access protection given by a flag set,
  1006      *  where PRIVATE is highest and PUBLIC is lowest.
  1007      */
  1008     static int protection(long flags) {
  1009         switch ((short)(flags & AccessFlags)) {
  1010         case PRIVATE: return 3;
  1011         case PROTECTED: return 1;
  1012         default:
  1013         case PUBLIC: return 0;
  1014         case 0: return 2;
  1018     /** A string describing the access permission given by a flag set.
  1019      *  This always returns a space-separated list of Java Keywords.
  1020      */
  1021     private static String protectionString(long flags) {
  1022         long flags1 = flags & AccessFlags;
  1023         return (flags1 == 0) ? "package" : TreeInfo.flagNames(flags1);
  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                       TreeInfo.flagNames(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                       protectionString(other.flags()));
  1134             return;
  1138         Type mt = types.memberType(origin.type, m);
  1139         Type ot = types.memberType(origin.type, other);
  1140         // Error if overriding result type is different
  1141         // (or, in the case of generics mode, not a subtype) of
  1142         // overridden result type. We have to rename any type parameters
  1143         // before comparing types.
  1144         List<Type> mtvars = mt.getTypeArguments();
  1145         List<Type> otvars = ot.getTypeArguments();
  1146         Type mtres = mt.getReturnType();
  1147         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1149         overrideWarner.warned = false;
  1150         boolean resultTypesOK =
  1151             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1152         if (!resultTypesOK) {
  1153             if (!source.allowCovariantReturns() &&
  1154                 m.owner != origin &&
  1155                 m.owner.isSubClass(other.owner, types)) {
  1156                 // allow limited interoperability with covariant returns
  1157             } else {
  1158                 typeError(TreeInfo.diagnosticPositionFor(m, tree),
  1159                           JCDiagnostic.fragment("override.incompatible.ret",
  1160                                          cannotOverride(m, other)),
  1161                           mtres, otres);
  1162                 return;
  1164         } else if (overrideWarner.warned) {
  1165             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1166                           "prob.found.req",
  1167                           JCDiagnostic.fragment("override.unchecked.ret",
  1168                                               uncheckedOverrides(m, other)),
  1169                           mtres, otres);
  1172         // Error if overriding method throws an exception not reported
  1173         // by overridden method.
  1174         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1175         List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
  1176         if (unhandled.nonEmpty()) {
  1177             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1178                       "override.meth.doesnt.throw",
  1179                       cannotOverride(m, other),
  1180                       unhandled.head);
  1181             return;
  1184         // Optional warning if varargs don't agree
  1185         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1186             && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
  1187             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1188                         ((m.flags() & Flags.VARARGS) != 0)
  1189                         ? "override.varargs.missing"
  1190                         : "override.varargs.extra",
  1191                         varargsOverrides(m, other));
  1194         // Warn if instance method overrides bridge method (compiler spec ??)
  1195         if ((other.flags() & BRIDGE) != 0) {
  1196             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1197                         uncheckedOverrides(m, other));
  1200         // Warn if a deprecated method overridden by a non-deprecated one.
  1201         if ((other.flags() & DEPRECATED) != 0
  1202             && (m.flags() & DEPRECATED) == 0
  1203             && m.outermostClass() != other.outermostClass()
  1204             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1205             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1208     // where
  1209         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1210             // If the method, m, is defined in an interface, then ignore the issue if the method
  1211             // is only inherited via a supertype and also implemented in the supertype,
  1212             // because in that case, we will rediscover the issue when examining the method
  1213             // in the supertype.
  1214             // If the method, m, is not defined in an interface, then the only time we need to
  1215             // address the issue is when the method is the supertype implemementation: any other
  1216             // case, we will have dealt with when examining the supertype classes
  1217             ClassSymbol mc = m.enclClass();
  1218             Type st = types.supertype(origin.type);
  1219             if (st.tag != CLASS)
  1220                 return true;
  1221             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1223             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1224                 List<Type> intfs = types.interfaces(origin.type);
  1225                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1227             else
  1228                 return (stimpl != m);
  1232     // used to check if there were any unchecked conversions
  1233     Warner overrideWarner = new Warner();
  1235     /** Check that a class does not inherit two concrete methods
  1236      *  with the same signature.
  1237      *  @param pos          Position to be used for error reporting.
  1238      *  @param site         The class type to be checked.
  1239      */
  1240     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1241         Type sup = types.supertype(site);
  1242         if (sup.tag != CLASS) return;
  1244         for (Type t1 = sup;
  1245              t1.tsym.type.isParameterized();
  1246              t1 = types.supertype(t1)) {
  1247             for (Scope.Entry e1 = t1.tsym.members().elems;
  1248                  e1 != null;
  1249                  e1 = e1.sibling) {
  1250                 Symbol s1 = e1.sym;
  1251                 if (s1.kind != MTH ||
  1252                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1253                     !s1.isInheritedIn(site.tsym, types) ||
  1254                     ((MethodSymbol)s1).implementation(site.tsym,
  1255                                                       types,
  1256                                                       true) != s1)
  1257                     continue;
  1258                 Type st1 = types.memberType(t1, s1);
  1259                 int s1ArgsLength = st1.getParameterTypes().length();
  1260                 if (st1 == s1.type) continue;
  1262                 for (Type t2 = sup;
  1263                      t2.tag == CLASS;
  1264                      t2 = types.supertype(t2)) {
  1265                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1266                          e2.scope != null;
  1267                          e2 = e2.next()) {
  1268                         Symbol s2 = e2.sym;
  1269                         if (s2 == s1 ||
  1270                             s2.kind != MTH ||
  1271                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1272                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1273                             !s2.isInheritedIn(site.tsym, types) ||
  1274                             ((MethodSymbol)s2).implementation(site.tsym,
  1275                                                               types,
  1276                                                               true) != s2)
  1277                             continue;
  1278                         Type st2 = types.memberType(t2, s2);
  1279                         if (types.overrideEquivalent(st1, st2))
  1280                             log.error(pos, "concrete.inheritance.conflict",
  1281                                       s1, t1, s2, t2, sup);
  1288     /** Check that classes (or interfaces) do not each define an abstract
  1289      *  method with same name and arguments but incompatible return types.
  1290      *  @param pos          Position to be used for error reporting.
  1291      *  @param t1           The first argument type.
  1292      *  @param t2           The second argument type.
  1293      */
  1294     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1295                                             Type t1,
  1296                                             Type t2) {
  1297         return checkCompatibleAbstracts(pos, t1, t2,
  1298                                         types.makeCompoundType(t1, t2));
  1301     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1302                                             Type t1,
  1303                                             Type t2,
  1304                                             Type site) {
  1305         Symbol sym = firstIncompatibility(t1, t2, site);
  1306         if (sym != null) {
  1307             log.error(pos, "types.incompatible.diff.ret",
  1308                       t1, t2, sym.name +
  1309                       "(" + types.memberType(t2, sym).getParameterTypes() + ")");
  1310             return false;
  1312         return true;
  1315     /** Return the first method which is defined with same args
  1316      *  but different return types in two given interfaces, or null if none
  1317      *  exists.
  1318      *  @param t1     The first type.
  1319      *  @param t2     The second type.
  1320      *  @param site   The most derived type.
  1321      *  @returns symbol from t2 that conflicts with one in t1.
  1322      */
  1323     private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
  1324         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1325         closure(t1, interfaces1);
  1326         Map<TypeSymbol,Type> interfaces2;
  1327         if (t1 == t2)
  1328             interfaces2 = interfaces1;
  1329         else
  1330             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1332         for (Type t3 : interfaces1.values()) {
  1333             for (Type t4 : interfaces2.values()) {
  1334                 Symbol s = firstDirectIncompatibility(t3, t4, site);
  1335                 if (s != null) return s;
  1338         return null;
  1341     /** Compute all the supertypes of t, indexed by type symbol. */
  1342     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1343         if (t.tag != CLASS) return;
  1344         if (typeMap.put(t.tsym, t) == null) {
  1345             closure(types.supertype(t), typeMap);
  1346             for (Type i : types.interfaces(t))
  1347                 closure(i, typeMap);
  1351     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1352     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1353         if (t.tag != CLASS) return;
  1354         if (typesSkip.get(t.tsym) != null) return;
  1355         if (typeMap.put(t.tsym, t) == null) {
  1356             closure(types.supertype(t), typesSkip, typeMap);
  1357             for (Type i : types.interfaces(t))
  1358                 closure(i, typesSkip, typeMap);
  1362     /** Return the first method in t2 that conflicts with a method from t1. */
  1363     private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
  1364         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1365             Symbol s1 = e1.sym;
  1366             Type st1 = null;
  1367             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1368             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1369             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1370             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1371                 Symbol s2 = e2.sym;
  1372                 if (s1 == s2) continue;
  1373                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1374                 if (st1 == null) st1 = types.memberType(t1, s1);
  1375                 Type st2 = types.memberType(t2, s2);
  1376                 if (types.overrideEquivalent(st1, st2)) {
  1377                     List<Type> tvars1 = st1.getTypeArguments();
  1378                     List<Type> tvars2 = st2.getTypeArguments();
  1379                     Type rt1 = st1.getReturnType();
  1380                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1381                     boolean compat =
  1382                         types.isSameType(rt1, rt2) ||
  1383                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1384                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1385                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1386                          checkCommonOverriderIn(s1,s2,site);
  1387                     if (!compat) return s2;
  1391         return null;
  1393     //WHERE
  1394     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1395         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1396         Type st1 = types.memberType(site, s1);
  1397         Type st2 = types.memberType(site, s2);
  1398         closure(site, supertypes);
  1399         for (Type t : supertypes.values()) {
  1400             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1401                 Symbol s3 = e.sym;
  1402                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1403                 Type st3 = types.memberType(site,s3);
  1404                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1405                     if (s3.owner == site.tsym) {
  1406                         return true;
  1408                     List<Type> tvars1 = st1.getTypeArguments();
  1409                     List<Type> tvars2 = st2.getTypeArguments();
  1410                     List<Type> tvars3 = st3.getTypeArguments();
  1411                     Type rt1 = st1.getReturnType();
  1412                     Type rt2 = st2.getReturnType();
  1413                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1414                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1415                     boolean compat =
  1416                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1417                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1418                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1419                     if (compat)
  1420                         return true;
  1424         return false;
  1427     /** Check that a given method conforms with any method it overrides.
  1428      *  @param tree         The tree from which positions are extracted
  1429      *                      for errors.
  1430      *  @param m            The overriding method.
  1431      */
  1432     void checkOverride(JCTree tree, MethodSymbol m) {
  1433         ClassSymbol origin = (ClassSymbol)m.owner;
  1434         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1435             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1436                 log.error(tree.pos(), "enum.no.finalize");
  1437                 return;
  1439         for (Type t = types.supertype(origin.type); t.tag == CLASS;
  1440              t = types.supertype(t)) {
  1441             TypeSymbol c = t.tsym;
  1442             Scope.Entry e = c.members().lookup(m.name);
  1443             while (e.scope != null) {
  1444                 if (m.overrides(e.sym, origin, types, false))
  1445                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1446                 else if (e.sym.isInheritedIn(origin, types) && !m.isConstructor()) {
  1447                     Type er1 = m.erasure(types);
  1448                     Type er2 = e.sym.erasure(types);
  1449                     if (types.isSameType(er1,er2)) {
  1450                             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1451                                     "name.clash.same.erasure.no.override",
  1452                                     m, m.location(),
  1453                                     e.sym, e.sym.location());
  1456                 e = e.next();
  1461     /** Check that all abstract members of given class have definitions.
  1462      *  @param pos          Position to be used for error reporting.
  1463      *  @param c            The class.
  1464      */
  1465     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1466         try {
  1467             MethodSymbol undef = firstUndef(c, c);
  1468             if (undef != null) {
  1469                 if ((c.flags() & ENUM) != 0 &&
  1470                     types.supertype(c.type).tsym == syms.enumSym &&
  1471                     (c.flags() & FINAL) == 0) {
  1472                     // add the ABSTRACT flag to an enum
  1473                     c.flags_field |= ABSTRACT;
  1474                 } else {
  1475                     MethodSymbol undef1 =
  1476                         new MethodSymbol(undef.flags(), undef.name,
  1477                                          types.memberType(c.type, undef), undef.owner);
  1478                     log.error(pos, "does.not.override.abstract",
  1479                               c, undef1, undef1.location());
  1482         } catch (CompletionFailure ex) {
  1483             completionError(pos, ex);
  1486 //where
  1487         /** Return first abstract member of class `c' that is not defined
  1488          *  in `impl', null if there is none.
  1489          */
  1490         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1491             MethodSymbol undef = null;
  1492             // Do not bother to search in classes that are not abstract,
  1493             // since they cannot have abstract members.
  1494             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1495                 Scope s = c.members();
  1496                 for (Scope.Entry e = s.elems;
  1497                      undef == null && e != null;
  1498                      e = e.sibling) {
  1499                     if (e.sym.kind == MTH &&
  1500                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1501                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1502                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1503                         if (implmeth == null || implmeth == absmeth)
  1504                             undef = absmeth;
  1507                 if (undef == null) {
  1508                     Type st = types.supertype(c.type);
  1509                     if (st.tag == CLASS)
  1510                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1512                 for (List<Type> l = types.interfaces(c.type);
  1513                      undef == null && l.nonEmpty();
  1514                      l = l.tail) {
  1515                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1518             return undef;
  1521     /** Check for cyclic references. Issue an error if the
  1522      *  symbol of the type referred to has a LOCKED flag set.
  1524      *  @param pos      Position to be used for error reporting.
  1525      *  @param t        The type referred to.
  1526      */
  1527     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1528         checkNonCyclicInternal(pos, t);
  1532     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1533         checkNonCyclic1(pos, t, new HashSet<TypeVar>());
  1536     private void checkNonCyclic1(DiagnosticPosition pos, Type t, Set<TypeVar> seen) {
  1537         final TypeVar tv;
  1538         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1539             return;
  1540         if (seen.contains(t)) {
  1541             tv = (TypeVar)t;
  1542             tv.bound = new ErrorType();
  1543             log.error(pos, "cyclic.inheritance", t);
  1544         } else if (t.tag == TYPEVAR) {
  1545             tv = (TypeVar)t;
  1546             seen.add(tv);
  1547             for (Type b : types.getBounds(tv))
  1548                 checkNonCyclic1(pos, b, seen);
  1552     /** Check for cyclic references. Issue an error if the
  1553      *  symbol of the type referred to has a LOCKED flag set.
  1555      *  @param pos      Position to be used for error reporting.
  1556      *  @param t        The type referred to.
  1557      *  @returns        True if the check completed on all attributed classes
  1558      */
  1559     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1560         boolean complete = true; // was the check complete?
  1561         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1562         Symbol c = t.tsym;
  1563         if ((c.flags_field & ACYCLIC) != 0) return true;
  1565         if ((c.flags_field & LOCKED) != 0) {
  1566             noteCyclic(pos, (ClassSymbol)c);
  1567         } else if (!c.type.isErroneous()) {
  1568             try {
  1569                 c.flags_field |= LOCKED;
  1570                 if (c.type.tag == CLASS) {
  1571                     ClassType clazz = (ClassType)c.type;
  1572                     if (clazz.interfaces_field != null)
  1573                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1574                             complete &= checkNonCyclicInternal(pos, l.head);
  1575                     if (clazz.supertype_field != null) {
  1576                         Type st = clazz.supertype_field;
  1577                         if (st != null && st.tag == CLASS)
  1578                             complete &= checkNonCyclicInternal(pos, st);
  1580                     if (c.owner.kind == TYP)
  1581                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1583             } finally {
  1584                 c.flags_field &= ~LOCKED;
  1587         if (complete)
  1588             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1589         if (complete) c.flags_field |= ACYCLIC;
  1590         return complete;
  1593     /** Note that we found an inheritance cycle. */
  1594     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1595         log.error(pos, "cyclic.inheritance", c);
  1596         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1597             l.head = new ErrorType((ClassSymbol)l.head.tsym);
  1598         Type st = types.supertype(c.type);
  1599         if (st.tag == CLASS)
  1600             ((ClassType)c.type).supertype_field = new ErrorType((ClassSymbol)st.tsym);
  1601         c.type = new ErrorType(c);
  1602         c.flags_field |= ACYCLIC;
  1605     /** Check that all methods which implement some
  1606      *  method conform to the method they implement.
  1607      *  @param tree         The class definition whose members are checked.
  1608      */
  1609     void checkImplementations(JCClassDecl tree) {
  1610         checkImplementations(tree, tree.sym);
  1612 //where
  1613         /** Check that all methods which implement some
  1614          *  method in `ic' conform to the method they implement.
  1615          */
  1616         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1617             ClassSymbol origin = tree.sym;
  1618             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1619                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1620                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1621                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  1622                         if (e.sym.kind == MTH &&
  1623                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  1624                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  1625                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  1626                             if (implmeth != null && implmeth != absmeth &&
  1627                                 (implmeth.owner.flags() & INTERFACE) ==
  1628                                 (origin.flags() & INTERFACE)) {
  1629                                 // don't check if implmeth is in a class, yet
  1630                                 // origin is an interface. This case arises only
  1631                                 // if implmeth is declared in Object. The reason is
  1632                                 // that interfaces really don't inherit from
  1633                                 // Object it's just that the compiler represents
  1634                                 // things that way.
  1635                                 checkOverride(tree, implmeth, absmeth, origin);
  1643     /** Check that all abstract methods implemented by a class are
  1644      *  mutually compatible.
  1645      *  @param pos          Position to be used for error reporting.
  1646      *  @param c            The class whose interfaces are checked.
  1647      */
  1648     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  1649         List<Type> supertypes = types.interfaces(c);
  1650         Type supertype = types.supertype(c);
  1651         if (supertype.tag == CLASS &&
  1652             (supertype.tsym.flags() & ABSTRACT) != 0)
  1653             supertypes = supertypes.prepend(supertype);
  1654         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  1655             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  1656                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  1657                 return;
  1658             for (List<Type> m = supertypes; m != l; m = m.tail)
  1659                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  1660                     return;
  1662         checkCompatibleConcretes(pos, c);
  1665     /** Check that class c does not implement directly or indirectly
  1666      *  the same parameterized interface with two different argument lists.
  1667      *  @param pos          Position to be used for error reporting.
  1668      *  @param type         The type whose interfaces are checked.
  1669      */
  1670     void checkClassBounds(DiagnosticPosition pos, Type type) {
  1671         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  1673 //where
  1674         /** Enter all interfaces of type `type' into the hash table `seensofar'
  1675          *  with their class symbol as key and their type as value. Make
  1676          *  sure no class is entered with two different types.
  1677          */
  1678         void checkClassBounds(DiagnosticPosition pos,
  1679                               Map<TypeSymbol,Type> seensofar,
  1680                               Type type) {
  1681             if (type.isErroneous()) return;
  1682             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  1683                 Type it = l.head;
  1684                 Type oldit = seensofar.put(it.tsym, it);
  1685                 if (oldit != null) {
  1686                     List<Type> oldparams = oldit.allparams();
  1687                     List<Type> newparams = it.allparams();
  1688                     if (!types.containsTypeEquivalent(oldparams, newparams))
  1689                         log.error(pos, "cant.inherit.diff.arg",
  1690                                   it.tsym, Type.toString(oldparams),
  1691                                   Type.toString(newparams));
  1693                 checkClassBounds(pos, seensofar, it);
  1695             Type st = types.supertype(type);
  1696             if (st != null) checkClassBounds(pos, seensofar, st);
  1699     /** Enter interface into into set.
  1700      *  If it existed already, issue a "repeated interface" error.
  1701      */
  1702     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  1703         if (its.contains(it))
  1704             log.error(pos, "repeated.interface");
  1705         else {
  1706             its.add(it);
  1710 /* *************************************************************************
  1711  * Check annotations
  1712  **************************************************************************/
  1714     /** Annotation types are restricted to primitives, String, an
  1715      *  enum, an annotation, Class, Class<?>, Class<? extends
  1716      *  Anything>, arrays of the preceding.
  1717      */
  1718     void validateAnnotationType(JCTree restype) {
  1719         // restype may be null if an error occurred, so don't bother validating it
  1720         if (restype != null) {
  1721             validateAnnotationType(restype.pos(), restype.type);
  1725     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  1726         if (type.isPrimitive()) return;
  1727         if (types.isSameType(type, syms.stringType)) return;
  1728         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  1729         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  1730         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  1731         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  1732             validateAnnotationType(pos, types.elemtype(type));
  1733             return;
  1735         log.error(pos, "invalid.annotation.member.type");
  1738     /**
  1739      * "It is also a compile-time error if any method declared in an
  1740      * annotation type has a signature that is override-equivalent to
  1741      * that of any public or protected method declared in class Object
  1742      * or in the interface annotation.Annotation."
  1744      * @jls3 9.6 Annotation Types
  1745      */
  1746     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  1747         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  1748             Scope s = sup.tsym.members();
  1749             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  1750                 if (e.sym.kind == MTH &&
  1751                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  1752                     types.overrideEquivalent(m.type, e.sym.type))
  1753                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  1758     /** Check the annotations of a symbol.
  1759      */
  1760     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  1761         if (skipAnnotations) return;
  1762         for (JCAnnotation a : annotations)
  1763             validateAnnotation(a, s);
  1766     /** Check an annotation of a symbol.
  1767      */
  1768     public void validateAnnotation(JCAnnotation a, Symbol s) {
  1769         validateAnnotation(a);
  1771         if (!annotationApplicable(a, s))
  1772             log.error(a.pos(), "annotation.type.not.applicable");
  1774         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1775             if (!isOverrider(s))
  1776                 log.error(a.pos(), "method.does.not.override.superclass");
  1780     /** Is s a method symbol that overrides a method in a superclass? */
  1781     boolean isOverrider(Symbol s) {
  1782         if (s.kind != MTH || s.isStatic())
  1783             return false;
  1784         MethodSymbol m = (MethodSymbol)s;
  1785         TypeSymbol owner = (TypeSymbol)m.owner;
  1786         for (Type sup : types.closure(owner.type)) {
  1787             if (sup == owner.type)
  1788                 continue; // skip "this"
  1789             Scope scope = sup.tsym.members();
  1790             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  1791                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  1792                     return true;
  1795         return false;
  1798     /** Is the annotation applicable to the symbol? */
  1799     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  1800         Attribute.Compound atTarget =
  1801             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1802         if (atTarget == null) return true;
  1803         Attribute atValue = atTarget.member(names.value);
  1804         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1805         Attribute.Array arr = (Attribute.Array) atValue;
  1806         for (Attribute app : arr.values) {
  1807             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1808             Attribute.Enum e = (Attribute.Enum) app;
  1809             if (e.value.name == names.TYPE)
  1810                 { if (s.kind == TYP) return true; }
  1811             else if (e.value.name == names.FIELD)
  1812                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  1813             else if (e.value.name == names.METHOD)
  1814                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  1815             else if (e.value.name == names.PARAMETER)
  1816                 { if (s.kind == VAR &&
  1817                       s.owner.kind == MTH &&
  1818                       (s.flags() & PARAMETER) != 0)
  1819                     return true;
  1821             else if (e.value.name == names.CONSTRUCTOR)
  1822                 { if (s.kind == MTH && s.isConstructor()) return true; }
  1823             else if (e.value.name == names.LOCAL_VARIABLE)
  1824                 { if (s.kind == VAR && s.owner.kind == MTH &&
  1825                       (s.flags() & PARAMETER) == 0)
  1826                     return true;
  1828             else if (e.value.name == names.ANNOTATION_TYPE)
  1829                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  1830                     return true;
  1832             else if (e.value.name == names.PACKAGE)
  1833                 { if (s.kind == PCK) return true; }
  1834             else
  1835                 return true; // recovery
  1837         return false;
  1840     /** Check an annotation value.
  1841      */
  1842     public void validateAnnotation(JCAnnotation a) {
  1843         if (a.type.isErroneous()) return;
  1845         // collect an inventory of the members
  1846         Set<MethodSymbol> members = new HashSet<MethodSymbol>();
  1847         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  1848              e != null;
  1849              e = e.sibling)
  1850             if (e.sym.kind == MTH)
  1851                 members.add((MethodSymbol) e.sym);
  1853         // count them off as they're annotated
  1854         for (JCTree arg : a.args) {
  1855             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  1856             JCAssign assign = (JCAssign) arg;
  1857             Symbol m = TreeInfo.symbol(assign.lhs);
  1858             if (m == null || m.type.isErroneous()) continue;
  1859             if (!members.remove(m))
  1860                 log.error(arg.pos(), "duplicate.annotation.member.value",
  1861                           m.name, a.type);
  1862             if (assign.rhs.getTag() == ANNOTATION)
  1863                 validateAnnotation((JCAnnotation)assign.rhs);
  1866         // all the remaining ones better have default values
  1867         for (MethodSymbol m : members)
  1868             if (m.defaultValue == null && !m.type.isErroneous())
  1869                 log.error(a.pos(), "annotation.missing.default.value",
  1870                           a.type, m.name);
  1872         // special case: java.lang.annotation.Target must not have
  1873         // repeated values in its value member
  1874         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  1875             a.args.tail == null)
  1876             return;
  1878         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  1879         JCAssign assign = (JCAssign) a.args.head;
  1880         Symbol m = TreeInfo.symbol(assign.lhs);
  1881         if (m.name != names.value) return;
  1882         JCTree rhs = assign.rhs;
  1883         if (rhs.getTag() != JCTree.NEWARRAY) return;
  1884         JCNewArray na = (JCNewArray) rhs;
  1885         Set<Symbol> targets = new HashSet<Symbol>();
  1886         for (JCTree elem : na.elems) {
  1887             if (!targets.add(TreeInfo.symbol(elem))) {
  1888                 log.error(elem.pos(), "repeated.annotation.target");
  1893     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  1894         if (allowAnnotations &&
  1895             lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
  1896             (s.flags() & DEPRECATED) != 0 &&
  1897             !syms.deprecatedType.isErroneous() &&
  1898             s.attribute(syms.deprecatedType.tsym) == null) {
  1899             log.warning(pos, "missing.deprecated.annotation");
  1903 /* *************************************************************************
  1904  * Check for recursive annotation elements.
  1905  **************************************************************************/
  1907     /** Check for cycles in the graph of annotation elements.
  1908      */
  1909     void checkNonCyclicElements(JCClassDecl tree) {
  1910         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  1911         assert (tree.sym.flags_field & LOCKED) == 0;
  1912         try {
  1913             tree.sym.flags_field |= LOCKED;
  1914             for (JCTree def : tree.defs) {
  1915                 if (def.getTag() != JCTree.METHODDEF) continue;
  1916                 JCMethodDecl meth = (JCMethodDecl)def;
  1917                 checkAnnotationResType(meth.pos(), meth.restype.type);
  1919         } finally {
  1920             tree.sym.flags_field &= ~LOCKED;
  1921             tree.sym.flags_field |= ACYCLIC_ANN;
  1925     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  1926         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  1927             return;
  1928         if ((tsym.flags_field & LOCKED) != 0) {
  1929             log.error(pos, "cyclic.annotation.element");
  1930             return;
  1932         try {
  1933             tsym.flags_field |= LOCKED;
  1934             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  1935                 Symbol s = e.sym;
  1936                 if (s.kind != Kinds.MTH)
  1937                     continue;
  1938                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  1940         } finally {
  1941             tsym.flags_field &= ~LOCKED;
  1942             tsym.flags_field |= ACYCLIC_ANN;
  1946     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  1947         switch (type.tag) {
  1948         case TypeTags.CLASS:
  1949             if ((type.tsym.flags() & ANNOTATION) != 0)
  1950                 checkNonCyclicElementsInternal(pos, type.tsym);
  1951             break;
  1952         case TypeTags.ARRAY:
  1953             checkAnnotationResType(pos, types.elemtype(type));
  1954             break;
  1955         default:
  1956             break; // int etc
  1960 /* *************************************************************************
  1961  * Check for cycles in the constructor call graph.
  1962  **************************************************************************/
  1964     /** Check for cycles in the graph of constructors calling other
  1965      *  constructors.
  1966      */
  1967     void checkCyclicConstructors(JCClassDecl tree) {
  1968         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  1970         // enter each constructor this-call into the map
  1971         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  1972             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  1973             if (app == null) continue;
  1974             JCMethodDecl meth = (JCMethodDecl) l.head;
  1975             if (TreeInfo.name(app.meth) == names._this) {
  1976                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  1977             } else {
  1978                 meth.sym.flags_field |= ACYCLIC;
  1982         // Check for cycles in the map
  1983         Symbol[] ctors = new Symbol[0];
  1984         ctors = callMap.keySet().toArray(ctors);
  1985         for (Symbol caller : ctors) {
  1986             checkCyclicConstructor(tree, caller, callMap);
  1990     /** Look in the map to see if the given constructor is part of a
  1991      *  call cycle.
  1992      */
  1993     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  1994                                         Map<Symbol,Symbol> callMap) {
  1995         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  1996             if ((ctor.flags_field & LOCKED) != 0) {
  1997                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  1998                           "recursive.ctor.invocation");
  1999             } else {
  2000                 ctor.flags_field |= LOCKED;
  2001                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2002                 ctor.flags_field &= ~LOCKED;
  2004             ctor.flags_field |= ACYCLIC;
  2008 /* *************************************************************************
  2009  * Miscellaneous
  2010  **************************************************************************/
  2012     /**
  2013      * Return the opcode of the operator but emit an error if it is an
  2014      * error.
  2015      * @param pos        position for error reporting.
  2016      * @param operator   an operator
  2017      * @param tag        a tree tag
  2018      * @param left       type of left hand side
  2019      * @param right      type of right hand side
  2020      */
  2021     int checkOperator(DiagnosticPosition pos,
  2022                        OperatorSymbol operator,
  2023                        int tag,
  2024                        Type left,
  2025                        Type right) {
  2026         if (operator.opcode == ByteCodes.error) {
  2027             log.error(pos,
  2028                       "operator.cant.be.applied",
  2029                       treeinfo.operatorName(tag),
  2030                       left + "," + right);
  2032         return operator.opcode;
  2036     /**
  2037      *  Check for division by integer constant zero
  2038      *  @param pos           Position for error reporting.
  2039      *  @param operator      The operator for the expression
  2040      *  @param operand       The right hand operand for the expression
  2041      */
  2042     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2043         if (operand.constValue() != null
  2044             && lint.isEnabled(Lint.LintCategory.DIVZERO)
  2045             && operand.tag <= LONG
  2046             && ((Number) (operand.constValue())).longValue() == 0) {
  2047             int opc = ((OperatorSymbol)operator).opcode;
  2048             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2049                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2050                 log.warning(pos, "div.zero");
  2055     /**
  2056      * Check for empty statements after if
  2057      */
  2058     void checkEmptyIf(JCIf tree) {
  2059         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
  2060             log.warning(tree.thenpart.pos(), "empty.if");
  2063     /** Check that symbol is unique in given scope.
  2064      *  @param pos           Position for error reporting.
  2065      *  @param sym           The symbol.
  2066      *  @param s             The scope.
  2067      */
  2068     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2069         if (sym.type.isErroneous())
  2070             return true;
  2071         if (sym.owner.name == names.any) return false;
  2072         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2073             if (sym != e.sym &&
  2074                 sym.kind == e.sym.kind &&
  2075                 sym.name != names.error &&
  2076                 (sym.kind != MTH || types.overrideEquivalent(sym.type, e.sym.type))) {
  2077                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2078                     varargsDuplicateError(pos, sym, e.sym);
  2079                 else
  2080                     duplicateError(pos, e.sym);
  2081                 return false;
  2084         return true;
  2087     /** Check that single-type import is not already imported or top-level defined,
  2088      *  but make an exception for two single-type imports which denote the same type.
  2089      *  @param pos           Position for error reporting.
  2090      *  @param sym           The symbol.
  2091      *  @param s             The scope
  2092      */
  2093     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2094         return checkUniqueImport(pos, sym, s, false);
  2097     /** Check that static single-type import is not already imported or top-level defined,
  2098      *  but make an exception for two single-type imports which denote the same type.
  2099      *  @param pos           Position for error reporting.
  2100      *  @param sym           The symbol.
  2101      *  @param s             The scope
  2102      *  @param staticImport  Whether or not this was a static import
  2103      */
  2104     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2105         return checkUniqueImport(pos, sym, s, true);
  2108     /** Check that single-type import is not already imported or top-level defined,
  2109      *  but make an exception for two single-type imports which denote the same type.
  2110      *  @param pos           Position for error reporting.
  2111      *  @param sym           The symbol.
  2112      *  @param s             The scope.
  2113      *  @param staticImport  Whether or not this was a static import
  2114      */
  2115     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2116         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2117             // is encountered class entered via a class declaration?
  2118             boolean isClassDecl = e.scope == s;
  2119             if ((isClassDecl || sym != e.sym) &&
  2120                 sym.kind == e.sym.kind &&
  2121                 sym.name != names.error) {
  2122                 if (!e.sym.type.isErroneous()) {
  2123                     String what = e.sym.toString();
  2124                     if (!isClassDecl) {
  2125                         if (staticImport)
  2126                             log.error(pos, "already.defined.static.single.import", what);
  2127                         else
  2128                             log.error(pos, "already.defined.single.import", what);
  2130                     else if (sym != e.sym)
  2131                         log.error(pos, "already.defined.this.unit", what);
  2133                 return false;
  2136         return true;
  2139     /** Check that a qualified name is in canonical form (for import decls).
  2140      */
  2141     public void checkCanonical(JCTree tree) {
  2142         if (!isCanonical(tree))
  2143             log.error(tree.pos(), "import.requires.canonical",
  2144                       TreeInfo.symbol(tree));
  2146         // where
  2147         private boolean isCanonical(JCTree tree) {
  2148             while (tree.getTag() == JCTree.SELECT) {
  2149                 JCFieldAccess s = (JCFieldAccess) tree;
  2150                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2151                     return false;
  2152                 tree = s.selected;
  2154             return true;
  2157     private class ConversionWarner extends Warner {
  2158         final String key;
  2159         final Type found;
  2160         final Type expected;
  2161         public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
  2162             super(pos);
  2163             this.key = key;
  2164             this.found = found;
  2165             this.expected = expected;
  2168         public void warnUnchecked() {
  2169             boolean warned = this.warned;
  2170             super.warnUnchecked();
  2171             if (warned) return; // suppress redundant diagnostics
  2172             Object problem = JCDiagnostic.fragment(key);
  2173             Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
  2177     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2178         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2181     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2182         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial