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

Mon, 04 May 2009 21:04:04 -0700

author
jrose
date
Mon, 04 May 2009 21:04:04 -0700
changeset 267
e2722bd43f3a
parent 252
5caa6c45936a
child 299
22872b24d38c
permissions
-rw-r--r--

6829189: Java programming with JSR 292 needs language support
Summary: Language changes documented in http://wikis.sun.com/display/mlvm/ProjectCoinProposal
Reviewed-by: jjg, darcy, mcimadamore

     1 /*
     2  * Copyright 1999-2009 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 Names 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 JCDiagnostic.Factory diags;
    67     private final boolean skipAnnotations;
    68     private final TreeInfo treeinfo;
    70     // The set of lint options currently in effect. It is initialized
    71     // from the context, and then is set/reset as needed by Attr as it
    72     // visits all the various parts of the trees during attribution.
    73     private Lint lint;
    75     public static Check instance(Context context) {
    76         Check instance = context.get(checkKey);
    77         if (instance == null)
    78             instance = new Check(context);
    79         return instance;
    80     }
    82     protected Check(Context context) {
    83         context.put(checkKey, this);
    85         names = Names.instance(context);
    86         log = Log.instance(context);
    87         syms = Symtab.instance(context);
    88         infer = Infer.instance(context);
    89         this.types = Types.instance(context);
    90         diags = JCDiagnostic.Factory.instance(context);
    91         Options options = Options.instance(context);
    92         target = Target.instance(context);
    93         source = Source.instance(context);
    94         lint = Lint.instance(context);
    95         treeinfo = TreeInfo.instance(context);
    97         Source source = Source.instance(context);
    98         allowGenerics = source.allowGenerics();
    99         allowAnnotations = source.allowAnnotations();
   100         complexInference = options.get("-complexinference") != null;
   101         skipAnnotations = options.get("skipAnnotations") != null;
   103         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   104         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   105         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   107         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   108                 enforceMandatoryWarnings, "deprecated");
   109         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   110                 enforceMandatoryWarnings, "unchecked");
   111     }
   113     /** Switch: generics enabled?
   114      */
   115     boolean allowGenerics;
   117     /** Switch: annotations enabled?
   118      */
   119     boolean allowAnnotations;
   121     /** Switch: -complexinference option set?
   122      */
   123     boolean complexInference;
   125     /** A table mapping flat names of all compiled classes in this run to their
   126      *  symbols; maintained from outside.
   127      */
   128     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   130     /** A handler for messages about deprecated usage.
   131      */
   132     private MandatoryWarningHandler deprecationHandler;
   134     /** A handler for messages about unchecked or unsafe usage.
   135      */
   136     private MandatoryWarningHandler uncheckedHandler;
   139 /* *************************************************************************
   140  * Errors and Warnings
   141  **************************************************************************/
   143     Lint setLint(Lint newLint) {
   144         Lint prev = lint;
   145         lint = newLint;
   146         return prev;
   147     }
   149     /** Warn about deprecated symbol.
   150      *  @param pos        Position to be used for error reporting.
   151      *  @param sym        The deprecated symbol.
   152      */
   153     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   154         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   155             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   156     }
   158     /** Warn about unchecked operation.
   159      *  @param pos        Position to be used for error reporting.
   160      *  @param msg        A string describing the problem.
   161      */
   162     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   163         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   164             uncheckedHandler.report(pos, msg, args);
   165     }
   167     /**
   168      * Report any deferred diagnostics.
   169      */
   170     public void reportDeferredDiagnostics() {
   171         deprecationHandler.reportDeferredDiagnostic();
   172         uncheckedHandler.reportDeferredDiagnostic();
   173     }
   176     /** Report a failure to complete a class.
   177      *  @param pos        Position to be used for error reporting.
   178      *  @param ex         The failure to report.
   179      */
   180     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   181         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   182         if (ex instanceof ClassReader.BadClassFile) throw new Abort();
   183         else return syms.errType;
   184     }
   186     /** Report a type error.
   187      *  @param pos        Position to be used for error reporting.
   188      *  @param problem    A string describing the error.
   189      *  @param found      The type that was found.
   190      *  @param req        The type that was required.
   191      */
   192     Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
   193         log.error(pos, "prob.found.req",
   194                   problem, found, req);
   195         return types.createErrorType(found);
   196     }
   198     Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
   199         log.error(pos, "prob.found.req.1", problem, found, req, explanation);
   200         return types.createErrorType(found);
   201     }
   203     /** Report an error that wrong type tag was found.
   204      *  @param pos        Position to be used for error reporting.
   205      *  @param required   An internationalized string describing the type tag
   206      *                    required.
   207      *  @param found      The type that was found.
   208      */
   209     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   210         // this error used to be raised by the parser,
   211         // but has been delayed to this point:
   212         if (found instanceof Type && ((Type)found).tag == VOID) {
   213             log.error(pos, "illegal.start.of.type");
   214             return syms.errType;
   215         }
   216         log.error(pos, "type.found.req", found, required);
   217         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   218     }
   220     /** Report an error that symbol cannot be referenced before super
   221      *  has been called.
   222      *  @param pos        Position to be used for error reporting.
   223      *  @param sym        The referenced symbol.
   224      */
   225     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   226         log.error(pos, "cant.ref.before.ctor.called", sym);
   227     }
   229     /** Report duplicate declaration error.
   230      */
   231     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   232         if (!sym.type.isErroneous()) {
   233             log.error(pos, "already.defined", sym, sym.location());
   234         }
   235     }
   237     /** Report array/varargs duplicate declaration
   238      */
   239     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   240         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   241             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   242         }
   243     }
   245 /* ************************************************************************
   246  * duplicate declaration checking
   247  *************************************************************************/
   249     /** Check that variable does not hide variable with same name in
   250      *  immediately enclosing local scope.
   251      *  @param pos           Position for error reporting.
   252      *  @param v             The symbol.
   253      *  @param s             The scope.
   254      */
   255     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   256         if (s.next != null) {
   257             for (Scope.Entry e = s.next.lookup(v.name);
   258                  e.scope != null && e.sym.owner == v.owner;
   259                  e = e.next()) {
   260                 if (e.sym.kind == VAR &&
   261                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   262                     v.name != names.error) {
   263                     duplicateError(pos, e.sym);
   264                     return;
   265                 }
   266             }
   267         }
   268     }
   270     /** Check that a class or interface does not hide a class or
   271      *  interface with same name in immediately enclosing local scope.
   272      *  @param pos           Position for error reporting.
   273      *  @param c             The symbol.
   274      *  @param s             The scope.
   275      */
   276     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   277         if (s.next != null) {
   278             for (Scope.Entry e = s.next.lookup(c.name);
   279                  e.scope != null && e.sym.owner == c.owner;
   280                  e = e.next()) {
   281                 if (e.sym.kind == TYP &&
   282                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   283                     c.name != names.error) {
   284                     duplicateError(pos, e.sym);
   285                     return;
   286                 }
   287             }
   288         }
   289     }
   291     /** Check that class does not have the same name as one of
   292      *  its enclosing classes, or as a class defined in its enclosing scope.
   293      *  return true if class is unique in its enclosing scope.
   294      *  @param pos           Position for error reporting.
   295      *  @param name          The class name.
   296      *  @param s             The enclosing scope.
   297      */
   298     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   299         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   300             if (e.sym.kind == TYP && e.sym.name != names.error) {
   301                 duplicateError(pos, e.sym);
   302                 return false;
   303             }
   304         }
   305         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   306             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   307                 duplicateError(pos, sym);
   308                 return true;
   309             }
   310         }
   311         return true;
   312     }
   314 /* *************************************************************************
   315  * Class name generation
   316  **************************************************************************/
   318     /** Return name of local class.
   319      *  This is of the form    <enclClass> $ n <classname>
   320      *  where
   321      *    enclClass is the flat name of the enclosing class,
   322      *    classname is the simple name of the local class
   323      */
   324     Name localClassName(ClassSymbol c) {
   325         for (int i=1; ; i++) {
   326             Name flatname = names.
   327                 fromString("" + c.owner.enclClass().flatname +
   328                            target.syntheticNameChar() + i +
   329                            c.name);
   330             if (compiled.get(flatname) == null) return flatname;
   331         }
   332     }
   334 /* *************************************************************************
   335  * Type Checking
   336  **************************************************************************/
   338     /** Check that a given type is assignable to a given proto-type.
   339      *  If it is, return the type, otherwise return errType.
   340      *  @param pos        Position to be used for error reporting.
   341      *  @param found      The type that was found.
   342      *  @param req        The type that was required.
   343      */
   344     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   345         if (req.tag == ERROR)
   346             return req;
   347         if (found.tag == FORALL)
   348             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   349         if (req.tag == NONE)
   350             return found;
   351         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   352             return found;
   353         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   354             return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
   355         if (found.isSuperBound()) {
   356             log.error(pos, "assignment.from.super-bound", found);
   357             return types.createErrorType(found);
   358         }
   359         if (req.isExtendsBound()) {
   360             log.error(pos, "assignment.to.extends-bound", req);
   361             return types.createErrorType(found);
   362         }
   363         return typeError(pos, diags.fragment("incompatible.types"), found, req);
   364     }
   366     /** Instantiate polymorphic type to some prototype, unless
   367      *  prototype is `anyPoly' in which case polymorphic type
   368      *  is returned unchanged.
   369      */
   370     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) {
   371         if (pt == Infer.anyPoly && complexInference) {
   372             return t;
   373         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   374             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   375             return instantiatePoly(pos, t, newpt, warn);
   376         } else if (pt.tag == ERROR) {
   377             return pt;
   378         } else {
   379             try {
   380                 return infer.instantiateExpr(t, pt, warn);
   381             } catch (Infer.NoInstanceException ex) {
   382                 if (ex.isAmbiguous) {
   383                     JCDiagnostic d = ex.getDiagnostic();
   384                     log.error(pos,
   385                               "undetermined.type" + (d!=null ? ".1" : ""),
   386                               t, d);
   387                     return types.createErrorType(pt);
   388                 } else {
   389                     JCDiagnostic d = ex.getDiagnostic();
   390                     return typeError(pos,
   391                                      diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   392                                      t, pt);
   393                 }
   394             }
   395         }
   396     }
   398     /** Check that a given type can be cast to a given target type.
   399      *  Return the result of the cast.
   400      *  @param pos        Position to be used for error reporting.
   401      *  @param found      The type that is being cast.
   402      *  @param req        The target type of the cast.
   403      */
   404     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   405         if (found.tag == FORALL) {
   406             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   407             return req;
   408         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   409             return req;
   410         } else {
   411             return typeError(pos,
   412                              diags.fragment("inconvertible.types"),
   413                              found, req);
   414         }
   415     }
   416 //where
   417         /** Is type a type variable, or a (possibly multi-dimensional) array of
   418          *  type variables?
   419          */
   420         boolean isTypeVar(Type t) {
   421             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   422         }
   424     /** Check that a type is within some bounds.
   425      *
   426      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   427      *  type argument.
   428      *  @param pos           Position to be used for error reporting.
   429      *  @param a             The type that should be bounded by bs.
   430      *  @param bs            The bound.
   431      */
   432     private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
   433          if (a.isUnbound()) {
   434              return;
   435          } else if (a.tag != WILDCARD) {
   436              a = types.upperBound(a);
   437              for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
   438                  if (!types.isSubtype(a, l.head)) {
   439                      log.error(pos, "not.within.bounds", a);
   440                      return;
   441                  }
   442              }
   443          } else if (a.isExtendsBound()) {
   444              if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
   445                  log.error(pos, "not.within.bounds", a);
   446          } else if (a.isSuperBound()) {
   447              if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
   448                  log.error(pos, "not.within.bounds", a);
   449          }
   450      }
   452     /** Check that a type is within some bounds.
   453      *
   454      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   455      *  type argument.
   456      *  @param pos           Position to be used for error reporting.
   457      *  @param a             The type that should be bounded by bs.
   458      *  @param bs            The bound.
   459      */
   460     private void checkCapture(JCTypeApply tree) {
   461         List<JCExpression> args = tree.getTypeArguments();
   462         for (Type arg : types.capture(tree.type).getTypeArguments()) {
   463             if (arg.tag == TYPEVAR && arg.getUpperBound().isErroneous()) {
   464                 log.error(args.head.pos, "not.within.bounds", args.head.type);
   465                 break;
   466             }
   467             args = args.tail;
   468         }
   469      }
   471     /** Check that type is different from 'void'.
   472      *  @param pos           Position to be used for error reporting.
   473      *  @param t             The type to be checked.
   474      */
   475     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   476         if (t.tag == VOID) {
   477             log.error(pos, "void.not.allowed.here");
   478             return types.createErrorType(t);
   479         } else {
   480             return t;
   481         }
   482     }
   484     /** Check that type is a class or interface type.
   485      *  @param pos           Position to be used for error reporting.
   486      *  @param t             The type to be checked.
   487      */
   488     Type checkClassType(DiagnosticPosition pos, Type t) {
   489         if (t.tag != CLASS && t.tag != ERROR)
   490             return typeTagError(pos,
   491                                 diags.fragment("type.req.class"),
   492                                 (t.tag == TYPEVAR)
   493                                 ? diags.fragment("type.parameter", t)
   494                                 : t);
   495         else
   496             return t;
   497     }
   499     /** Check that type is a class or interface type.
   500      *  @param pos           Position to be used for error reporting.
   501      *  @param t             The type to be checked.
   502      *  @param noBounds    True if type bounds are illegal here.
   503      */
   504     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   505         t = checkClassType(pos, t);
   506         if (noBounds && t.isParameterized()) {
   507             List<Type> args = t.getTypeArguments();
   508             while (args.nonEmpty()) {
   509                 if (args.head.tag == WILDCARD)
   510                     return typeTagError(pos,
   511                                         log.getLocalizedString("type.req.exact"),
   512                                         args.head);
   513                 args = args.tail;
   514             }
   515         }
   516         return t;
   517     }
   519     /** Check that type is a reifiable class, interface or array type.
   520      *  @param pos           Position to be used for error reporting.
   521      *  @param t             The type to be checked.
   522      */
   523     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   524         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   525             return typeTagError(pos,
   526                                 diags.fragment("type.req.class.array"),
   527                                 t);
   528         } else if (!types.isReifiable(t)) {
   529             log.error(pos, "illegal.generic.type.for.instof");
   530             return types.createErrorType(t);
   531         } else {
   532             return t;
   533         }
   534     }
   536     /** Check that type is a reference type, i.e. a class, interface or array type
   537      *  or a type variable.
   538      *  @param pos           Position to be used for error reporting.
   539      *  @param t             The type to be checked.
   540      */
   541     Type checkRefType(DiagnosticPosition pos, Type t) {
   542         switch (t.tag) {
   543         case CLASS:
   544         case ARRAY:
   545         case TYPEVAR:
   546         case WILDCARD:
   547         case ERROR:
   548             return t;
   549         default:
   550             return typeTagError(pos,
   551                                 diags.fragment("type.req.ref"),
   552                                 t);
   553         }
   554     }
   556     /** Check that each type is a reference type, i.e. a class, interface or array type
   557      *  or a type variable.
   558      *  @param trees         Original trees, used for error reporting.
   559      *  @param types         The types to be checked.
   560      */
   561     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   562         List<JCExpression> tl = trees;
   563         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   564             l.head = checkRefType(tl.head.pos(), l.head);
   565             tl = tl.tail;
   566         }
   567         return types;
   568     }
   570     /** Check that type is a null or reference type.
   571      *  @param pos           Position to be used for error reporting.
   572      *  @param t             The type to be checked.
   573      */
   574     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   575         switch (t.tag) {
   576         case CLASS:
   577         case ARRAY:
   578         case TYPEVAR:
   579         case WILDCARD:
   580         case BOT:
   581         case ERROR:
   582             return t;
   583         default:
   584             return typeTagError(pos,
   585                                 diags.fragment("type.req.ref"),
   586                                 t);
   587         }
   588     }
   590     /** Check that flag set does not contain elements of two conflicting sets. s
   591      *  Return true if it doesn't.
   592      *  @param pos           Position to be used for error reporting.
   593      *  @param flags         The set of flags to be checked.
   594      *  @param set1          Conflicting flags set #1.
   595      *  @param set2          Conflicting flags set #2.
   596      */
   597     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   598         if ((flags & set1) != 0 && (flags & set2) != 0) {
   599             log.error(pos,
   600                       "illegal.combination.of.modifiers",
   601                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   602                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   603             return false;
   604         } else
   605             return true;
   606     }
   608     /** Check that given modifiers are legal for given symbol and
   609      *  return modifiers together with any implicit modififiers for that symbol.
   610      *  Warning: we can't use flags() here since this method
   611      *  is called during class enter, when flags() would cause a premature
   612      *  completion.
   613      *  @param pos           Position to be used for error reporting.
   614      *  @param flags         The set of modifiers given in a definition.
   615      *  @param sym           The defined symbol.
   616      */
   617     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   618         long mask;
   619         long implicit = 0;
   620         switch (sym.kind) {
   621         case VAR:
   622             if (sym.owner.kind != TYP)
   623                 mask = LocalVarFlags;
   624             else if ((sym.owner.flags_field & INTERFACE) != 0)
   625                 mask = implicit = InterfaceVarFlags;
   626             else
   627                 mask = VarFlags;
   628             break;
   629         case MTH:
   630             if (sym.name == names.init) {
   631                 if ((sym.owner.flags_field & ENUM) != 0) {
   632                     // enum constructors cannot be declared public or
   633                     // protected and must be implicitly or explicitly
   634                     // private
   635                     implicit = PRIVATE;
   636                     mask = PRIVATE;
   637                 } else
   638                     mask = ConstructorFlags;
   639             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   640                 mask = implicit = InterfaceMethodFlags;
   641             else {
   642                 mask = MethodFlags;
   643             }
   644             // Imply STRICTFP if owner has STRICTFP set.
   645             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   646               implicit |= sym.owner.flags_field & STRICTFP;
   647             break;
   648         case TYP:
   649             if (sym.isLocal()) {
   650                 mask = LocalClassFlags;
   651                 if (sym.name.isEmpty()) { // Anonymous class
   652                     // Anonymous classes in static methods are themselves static;
   653                     // that's why we admit STATIC here.
   654                     mask |= STATIC;
   655                     // JLS: Anonymous classes are final.
   656                     implicit |= FINAL;
   657                 }
   658                 if ((sym.owner.flags_field & STATIC) == 0 &&
   659                     (flags & ENUM) != 0)
   660                     log.error(pos, "enums.must.be.static");
   661             } else if (sym.owner.kind == TYP) {
   662                 mask = MemberClassFlags;
   663                 if (sym.owner.owner.kind == PCK ||
   664                     (sym.owner.flags_field & STATIC) != 0)
   665                     mask |= STATIC;
   666                 else if ((flags & ENUM) != 0)
   667                     log.error(pos, "enums.must.be.static");
   668                 // Nested interfaces and enums are always STATIC (Spec ???)
   669                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   670             } else {
   671                 mask = ClassFlags;
   672             }
   673             // Interfaces are always ABSTRACT
   674             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   676             if ((flags & ENUM) != 0) {
   677                 // enums can't be declared abstract or final
   678                 mask &= ~(ABSTRACT | FINAL);
   679                 implicit |= implicitEnumFinalFlag(tree);
   680             }
   681             // Imply STRICTFP if owner has STRICTFP set.
   682             implicit |= sym.owner.flags_field & STRICTFP;
   683             break;
   684         default:
   685             throw new AssertionError();
   686         }
   687         long illegal = flags & StandardFlags & ~mask;
   688         if (illegal != 0) {
   689             if ((illegal & INTERFACE) != 0) {
   690                 log.error(pos, "intf.not.allowed.here");
   691                 mask |= INTERFACE;
   692             }
   693             else {
   694                 log.error(pos,
   695                           "mod.not.allowed.here", asFlagSet(illegal));
   696             }
   697         }
   698         else if ((sym.kind == TYP ||
   699                   // ISSUE: Disallowing abstract&private is no longer appropriate
   700                   // in the presence of inner classes. Should it be deleted here?
   701                   checkDisjoint(pos, flags,
   702                                 ABSTRACT,
   703                                 PRIVATE | STATIC))
   704                  &&
   705                  checkDisjoint(pos, flags,
   706                                ABSTRACT | INTERFACE,
   707                                FINAL | NATIVE | SYNCHRONIZED)
   708                  &&
   709                  checkDisjoint(pos, flags,
   710                                PUBLIC,
   711                                PRIVATE | PROTECTED)
   712                  &&
   713                  checkDisjoint(pos, flags,
   714                                PRIVATE,
   715                                PUBLIC | PROTECTED)
   716                  &&
   717                  checkDisjoint(pos, flags,
   718                                FINAL,
   719                                VOLATILE)
   720                  &&
   721                  (sym.kind == TYP ||
   722                   checkDisjoint(pos, flags,
   723                                 ABSTRACT | NATIVE,
   724                                 STRICTFP))) {
   725             // skip
   726         }
   727         return flags & (mask | ~StandardFlags) | implicit;
   728     }
   731     /** Determine if this enum should be implicitly final.
   732      *
   733      *  If the enum has no specialized enum contants, it is final.
   734      *
   735      *  If the enum does have specialized enum contants, it is
   736      *  <i>not</i> final.
   737      */
   738     private long implicitEnumFinalFlag(JCTree tree) {
   739         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   740         class SpecialTreeVisitor extends JCTree.Visitor {
   741             boolean specialized;
   742             SpecialTreeVisitor() {
   743                 this.specialized = false;
   744             };
   746             public void visitTree(JCTree tree) { /* no-op */ }
   748             public void visitVarDef(JCVariableDecl tree) {
   749                 if ((tree.mods.flags & ENUM) != 0) {
   750                     if (tree.init instanceof JCNewClass &&
   751                         ((JCNewClass) tree.init).def != null) {
   752                         specialized = true;
   753                     }
   754                 }
   755             }
   756         }
   758         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   759         JCClassDecl cdef = (JCClassDecl) tree;
   760         for (JCTree defs: cdef.defs) {
   761             defs.accept(sts);
   762             if (sts.specialized) return 0;
   763         }
   764         return FINAL;
   765     }
   767 /* *************************************************************************
   768  * Type Validation
   769  **************************************************************************/
   771     /** Validate a type expression. That is,
   772      *  check that all type arguments of a parametric type are within
   773      *  their bounds. This must be done in a second phase after type attributon
   774      *  since a class might have a subclass as type parameter bound. E.g:
   775      *
   776      *  class B<A extends C> { ... }
   777      *  class C extends B<C> { ... }
   778      *
   779      *  and we can't make sure that the bound is already attributed because
   780      *  of possible cycles.
   781      */
   782     private Validator validator = new Validator();
   784     /** Visitor method: Validate a type expression, if it is not null, catching
   785      *  and reporting any completion failures.
   786      */
   787     void validate(JCTree tree, Env<AttrContext> env) {
   788         try {
   789             if (tree != null) {
   790                 validator.env = env;
   791                 tree.accept(validator);
   792                 checkRaw(tree, env);
   793             }
   794         } catch (CompletionFailure ex) {
   795             completionError(tree.pos(), ex);
   796         }
   797     }
   798     //where
   799     void checkRaw(JCTree tree, Env<AttrContext> env) {
   800         if (lint.isEnabled(Lint.LintCategory.RAW) &&
   801             tree.type.tag == CLASS &&
   802             !env.enclClass.name.isEmpty() &&  //anonymous or intersection
   803             tree.type.isRaw()) {
   804             log.warning(tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
   805         }
   806     }
   808     /** Visitor method: Validate a list of type expressions.
   809      */
   810     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
   811         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   812             validate(l.head, env);
   813     }
   815     /** A visitor class for type validation.
   816      */
   817     class Validator extends JCTree.Visitor {
   819         public void visitTypeArray(JCArrayTypeTree tree) {
   820             validate(tree.elemtype, env);
   821         }
   823         public void visitTypeApply(JCTypeApply tree) {
   824             if (tree.type.tag == CLASS) {
   825                 List<Type> formals = tree.type.tsym.type.allparams();
   826                 List<Type> actuals = tree.type.allparams();
   827                 List<JCExpression> args = tree.arguments;
   828                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
   829                 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>();
   831                 // For matching pairs of actual argument types `a' and
   832                 // formal type parameters with declared bound `b' ...
   833                 while (args.nonEmpty() && forms.nonEmpty()) {
   834                     validate(args.head, env);
   836                     // exact type arguments needs to know their
   837                     // bounds (for upper and lower bound
   838                     // calculations).  So we create new TypeVars with
   839                     // bounds substed with actuals.
   840                     tvars_buf.append(types.substBound(((TypeVar)forms.head),
   841                                                       formals,
   842                                                       actuals));
   844                     args = args.tail;
   845                     forms = forms.tail;
   846                 }
   848                 args = tree.arguments;
   849                 List<Type> tvars_cap = types.substBounds(formals,
   850                                           formals,
   851                                           types.capture(tree.type).allparams());
   852                 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   853                     // Let the actual arguments know their bound
   854                     args.head.type.withTypeVar((TypeVar)tvars_cap.head);
   855                     args = args.tail;
   856                     tvars_cap = tvars_cap.tail;
   857                 }
   859                 args = tree.arguments;
   860                 List<TypeVar> tvars = tvars_buf.toList();
   862                 while (args.nonEmpty() && tvars.nonEmpty()) {
   863                     checkExtends(args.head.pos(),
   864                                  args.head.type,
   865                                  tvars.head);
   866                     args = args.tail;
   867                     tvars = tvars.tail;
   868                 }
   870                 checkCapture(tree);
   872                 // Check that this type is either fully parameterized, or
   873                 // not parameterized at all.
   874                 if (tree.type.getEnclosingType().isRaw())
   875                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
   876                 if (tree.clazz.getTag() == JCTree.SELECT)
   877                     visitSelectInternal((JCFieldAccess)tree.clazz);
   878             }
   879         }
   881         public void visitTypeParameter(JCTypeParameter tree) {
   882             validate(tree.bounds, env);
   883             checkClassBounds(tree.pos(), tree.type);
   884         }
   886         @Override
   887         public void visitWildcard(JCWildcard tree) {
   888             if (tree.inner != null)
   889                 validate(tree.inner, env);
   890         }
   892         public void visitSelect(JCFieldAccess tree) {
   893             if (tree.type.tag == CLASS) {
   894                 visitSelectInternal(tree);
   896                 // Check that this type is either fully parameterized, or
   897                 // not parameterized at all.
   898                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
   899                     log.error(tree.pos(), "improperly.formed.type.param.missing");
   900             }
   901         }
   902         public void visitSelectInternal(JCFieldAccess tree) {
   903             if (tree.type.tsym.isStatic() &&
   904                 tree.selected.type.isParameterized()) {
   905                 // The enclosing type is not a class, so we are
   906                 // looking at a static member type.  However, the
   907                 // qualifying expression is parameterized.
   908                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
   909             } else {
   910                 // otherwise validate the rest of the expression
   911                 tree.selected.accept(this);
   912             }
   913         }
   915         /** Default visitor method: do nothing.
   916          */
   917         public void visitTree(JCTree tree) {
   918         }
   920         Env<AttrContext> env;
   921     }
   923 /* *************************************************************************
   924  * Exception checking
   925  **************************************************************************/
   927     /* The following methods treat classes as sets that contain
   928      * the class itself and all their subclasses
   929      */
   931     /** Is given type a subtype of some of the types in given list?
   932      */
   933     boolean subset(Type t, List<Type> ts) {
   934         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   935             if (types.isSubtype(t, l.head)) return true;
   936         return false;
   937     }
   939     /** Is given type a subtype or supertype of
   940      *  some of the types in given list?
   941      */
   942     boolean intersects(Type t, List<Type> ts) {
   943         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   944             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
   945         return false;
   946     }
   948     /** Add type set to given type list, unless it is a subclass of some class
   949      *  in the list.
   950      */
   951     List<Type> incl(Type t, List<Type> ts) {
   952         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
   953     }
   955     /** Remove type set from type set list.
   956      */
   957     List<Type> excl(Type t, List<Type> ts) {
   958         if (ts.isEmpty()) {
   959             return ts;
   960         } else {
   961             List<Type> ts1 = excl(t, ts.tail);
   962             if (types.isSubtype(ts.head, t)) return ts1;
   963             else if (ts1 == ts.tail) return ts;
   964             else return ts1.prepend(ts.head);
   965         }
   966     }
   968     /** Form the union of two type set lists.
   969      */
   970     List<Type> union(List<Type> ts1, List<Type> ts2) {
   971         List<Type> ts = ts1;
   972         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   973             ts = incl(l.head, ts);
   974         return ts;
   975     }
   977     /** Form the difference of two type lists.
   978      */
   979     List<Type> diff(List<Type> ts1, List<Type> ts2) {
   980         List<Type> ts = ts1;
   981         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   982             ts = excl(l.head, ts);
   983         return ts;
   984     }
   986     /** Form the intersection of two type lists.
   987      */
   988     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
   989         List<Type> ts = List.nil();
   990         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
   991             if (subset(l.head, ts2)) ts = incl(l.head, ts);
   992         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
   993             if (subset(l.head, ts1)) ts = incl(l.head, ts);
   994         return ts;
   995     }
   997     /** Is exc an exception symbol that need not be declared?
   998      */
   999     boolean isUnchecked(ClassSymbol exc) {
  1000         return
  1001             exc.kind == ERR ||
  1002             exc.isSubClass(syms.errorType.tsym, types) ||
  1003             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1006     /** Is exc an exception type that need not be declared?
  1007      */
  1008     boolean isUnchecked(Type exc) {
  1009         return
  1010             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1011             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1012             exc.tag == BOT;
  1015     /** Same, but handling completion failures.
  1016      */
  1017     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1018         try {
  1019             return isUnchecked(exc);
  1020         } catch (CompletionFailure ex) {
  1021             completionError(pos, ex);
  1022             return true;
  1026     /** Is exc handled by given exception list?
  1027      */
  1028     boolean isHandled(Type exc, List<Type> handled) {
  1029         return isUnchecked(exc) || subset(exc, handled);
  1032     /** Return all exceptions in thrown list that are not in handled list.
  1033      *  @param thrown     The list of thrown exceptions.
  1034      *  @param handled    The list of handled exceptions.
  1035      */
  1036     List<Type> unHandled(List<Type> thrown, List<Type> handled) {
  1037         List<Type> unhandled = List.nil();
  1038         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1039             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1040         return unhandled;
  1043 /* *************************************************************************
  1044  * Overriding/Implementation checking
  1045  **************************************************************************/
  1047     /** The level of access protection given by a flag set,
  1048      *  where PRIVATE is highest and PUBLIC is lowest.
  1049      */
  1050     static int protection(long flags) {
  1051         switch ((short)(flags & AccessFlags)) {
  1052         case PRIVATE: return 3;
  1053         case PROTECTED: return 1;
  1054         default:
  1055         case PUBLIC: return 0;
  1056         case 0: return 2;
  1060     /** A customized "cannot override" error message.
  1061      *  @param m      The overriding method.
  1062      *  @param other  The overridden method.
  1063      *  @return       An internationalized string.
  1064      */
  1065     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1066         String key;
  1067         if ((other.owner.flags() & INTERFACE) == 0)
  1068             key = "cant.override";
  1069         else if ((m.owner.flags() & INTERFACE) == 0)
  1070             key = "cant.implement";
  1071         else
  1072             key = "clashes.with";
  1073         return diags.fragment(key, m, m.location(), other, other.location());
  1076     /** A customized "override" warning message.
  1077      *  @param m      The overriding method.
  1078      *  @param other  The overridden method.
  1079      *  @return       An internationalized string.
  1080      */
  1081     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1082         String key;
  1083         if ((other.owner.flags() & INTERFACE) == 0)
  1084             key = "unchecked.override";
  1085         else if ((m.owner.flags() & INTERFACE) == 0)
  1086             key = "unchecked.implement";
  1087         else
  1088             key = "unchecked.clash.with";
  1089         return diags.fragment(key, m, m.location(), other, other.location());
  1092     /** A customized "override" warning message.
  1093      *  @param m      The overriding method.
  1094      *  @param other  The overridden method.
  1095      *  @return       An internationalized string.
  1096      */
  1097     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1098         String key;
  1099         if ((other.owner.flags() & INTERFACE) == 0)
  1100             key = "varargs.override";
  1101         else  if ((m.owner.flags() & INTERFACE) == 0)
  1102             key = "varargs.implement";
  1103         else
  1104             key = "varargs.clash.with";
  1105         return diags.fragment(key, m, m.location(), other, other.location());
  1108     /** Check that this method conforms with overridden method 'other'.
  1109      *  where `origin' is the class where checking started.
  1110      *  Complications:
  1111      *  (1) Do not check overriding of synthetic methods
  1112      *      (reason: they might be final).
  1113      *      todo: check whether this is still necessary.
  1114      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1115      *      than the method it implements. Augment the proxy methods with the
  1116      *      undeclared exceptions in this case.
  1117      *  (3) When generics are enabled, admit the case where an interface proxy
  1118      *      has a result type
  1119      *      extended by the result type of the method it implements.
  1120      *      Change the proxies result type to the smaller type in this case.
  1122      *  @param tree         The tree from which positions
  1123      *                      are extracted for errors.
  1124      *  @param m            The overriding method.
  1125      *  @param other        The overridden method.
  1126      *  @param origin       The class of which the overriding method
  1127      *                      is a member.
  1128      */
  1129     void checkOverride(JCTree tree,
  1130                        MethodSymbol m,
  1131                        MethodSymbol other,
  1132                        ClassSymbol origin) {
  1133         // Don't check overriding of synthetic methods or by bridge methods.
  1134         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1135             return;
  1138         // Error if static method overrides instance method (JLS 8.4.6.2).
  1139         if ((m.flags() & STATIC) != 0 &&
  1140                    (other.flags() & STATIC) == 0) {
  1141             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1142                       cannotOverride(m, other));
  1143             return;
  1146         // Error if instance method overrides static or final
  1147         // method (JLS 8.4.6.1).
  1148         if ((other.flags() & FINAL) != 0 ||
  1149                  (m.flags() & STATIC) == 0 &&
  1150                  (other.flags() & STATIC) != 0) {
  1151             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1152                       cannotOverride(m, other),
  1153                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1154             return;
  1157         if ((m.owner.flags() & ANNOTATION) != 0) {
  1158             // handled in validateAnnotationMethod
  1159             return;
  1162         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1163         if ((origin.flags() & INTERFACE) == 0 &&
  1164                  protection(m.flags()) > protection(other.flags())) {
  1165             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1166                       cannotOverride(m, other),
  1167                       other.flags() == 0 ?
  1168                           Flag.PACKAGE :
  1169                           asFlagSet(other.flags() & AccessFlags));
  1170             return;
  1173         Type mt = types.memberType(origin.type, m);
  1174         Type ot = types.memberType(origin.type, other);
  1175         // Error if overriding result type is different
  1176         // (or, in the case of generics mode, not a subtype) of
  1177         // overridden result type. We have to rename any type parameters
  1178         // before comparing types.
  1179         List<Type> mtvars = mt.getTypeArguments();
  1180         List<Type> otvars = ot.getTypeArguments();
  1181         Type mtres = mt.getReturnType();
  1182         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1184         overrideWarner.warned = false;
  1185         boolean resultTypesOK =
  1186             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1187         if (!resultTypesOK) {
  1188             if (!source.allowCovariantReturns() &&
  1189                 m.owner != origin &&
  1190                 m.owner.isSubClass(other.owner, types)) {
  1191                 // allow limited interoperability with covariant returns
  1192             } else {
  1193                 typeError(TreeInfo.diagnosticPositionFor(m, tree),
  1194                           diags.fragment("override.incompatible.ret",
  1195                                          cannotOverride(m, other)),
  1196                           mtres, otres);
  1197                 return;
  1199         } else if (overrideWarner.warned) {
  1200             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1201                           "prob.found.req",
  1202                           diags.fragment("override.unchecked.ret",
  1203                                               uncheckedOverrides(m, other)),
  1204                           mtres, otres);
  1207         // Error if overriding method throws an exception not reported
  1208         // by overridden method.
  1209         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1210         List<Type> unhandled = unHandled(mt.getThrownTypes(), otthrown);
  1211         if (unhandled.nonEmpty()) {
  1212             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1213                       "override.meth.doesnt.throw",
  1214                       cannotOverride(m, other),
  1215                       unhandled.head);
  1216             return;
  1219         // Optional warning if varargs don't agree
  1220         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1221             && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
  1222             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1223                         ((m.flags() & Flags.VARARGS) != 0)
  1224                         ? "override.varargs.missing"
  1225                         : "override.varargs.extra",
  1226                         varargsOverrides(m, other));
  1229         // Warn if instance method overrides bridge method (compiler spec ??)
  1230         if ((other.flags() & BRIDGE) != 0) {
  1231             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1232                         uncheckedOverrides(m, other));
  1235         // Warn if a deprecated method overridden by a non-deprecated one.
  1236         if ((other.flags() & DEPRECATED) != 0
  1237             && (m.flags() & DEPRECATED) == 0
  1238             && m.outermostClass() != other.outermostClass()
  1239             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1240             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1243     // where
  1244         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1245             // If the method, m, is defined in an interface, then ignore the issue if the method
  1246             // is only inherited via a supertype and also implemented in the supertype,
  1247             // because in that case, we will rediscover the issue when examining the method
  1248             // in the supertype.
  1249             // If the method, m, is not defined in an interface, then the only time we need to
  1250             // address the issue is when the method is the supertype implemementation: any other
  1251             // case, we will have dealt with when examining the supertype classes
  1252             ClassSymbol mc = m.enclClass();
  1253             Type st = types.supertype(origin.type);
  1254             if (st.tag != CLASS)
  1255                 return true;
  1256             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1258             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1259                 List<Type> intfs = types.interfaces(origin.type);
  1260                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1262             else
  1263                 return (stimpl != m);
  1267     // used to check if there were any unchecked conversions
  1268     Warner overrideWarner = new Warner();
  1270     /** Check that a class does not inherit two concrete methods
  1271      *  with the same signature.
  1272      *  @param pos          Position to be used for error reporting.
  1273      *  @param site         The class type to be checked.
  1274      */
  1275     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1276         Type sup = types.supertype(site);
  1277         if (sup.tag != CLASS) return;
  1279         for (Type t1 = sup;
  1280              t1.tsym.type.isParameterized();
  1281              t1 = types.supertype(t1)) {
  1282             for (Scope.Entry e1 = t1.tsym.members().elems;
  1283                  e1 != null;
  1284                  e1 = e1.sibling) {
  1285                 Symbol s1 = e1.sym;
  1286                 if (s1.kind != MTH ||
  1287                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1288                     !s1.isInheritedIn(site.tsym, types) ||
  1289                     ((MethodSymbol)s1).implementation(site.tsym,
  1290                                                       types,
  1291                                                       true) != s1)
  1292                     continue;
  1293                 Type st1 = types.memberType(t1, s1);
  1294                 int s1ArgsLength = st1.getParameterTypes().length();
  1295                 if (st1 == s1.type) continue;
  1297                 for (Type t2 = sup;
  1298                      t2.tag == CLASS;
  1299                      t2 = types.supertype(t2)) {
  1300                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1301                          e2.scope != null;
  1302                          e2 = e2.next()) {
  1303                         Symbol s2 = e2.sym;
  1304                         if (s2 == s1 ||
  1305                             s2.kind != MTH ||
  1306                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1307                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1308                             !s2.isInheritedIn(site.tsym, types) ||
  1309                             ((MethodSymbol)s2).implementation(site.tsym,
  1310                                                               types,
  1311                                                               true) != s2)
  1312                             continue;
  1313                         Type st2 = types.memberType(t2, s2);
  1314                         if (types.overrideEquivalent(st1, st2))
  1315                             log.error(pos, "concrete.inheritance.conflict",
  1316                                       s1, t1, s2, t2, sup);
  1323     /** Check that classes (or interfaces) do not each define an abstract
  1324      *  method with same name and arguments but incompatible return types.
  1325      *  @param pos          Position to be used for error reporting.
  1326      *  @param t1           The first argument type.
  1327      *  @param t2           The second argument type.
  1328      */
  1329     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1330                                             Type t1,
  1331                                             Type t2) {
  1332         return checkCompatibleAbstracts(pos, t1, t2,
  1333                                         types.makeCompoundType(t1, t2));
  1336     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1337                                             Type t1,
  1338                                             Type t2,
  1339                                             Type site) {
  1340         Symbol sym = firstIncompatibility(t1, t2, site);
  1341         if (sym != null) {
  1342             log.error(pos, "types.incompatible.diff.ret",
  1343                       t1, t2, sym.name +
  1344                       "(" + types.memberType(t2, sym).getParameterTypes() + ")");
  1345             return false;
  1347         return true;
  1350     /** Return the first method which is defined with same args
  1351      *  but different return types in two given interfaces, or null if none
  1352      *  exists.
  1353      *  @param t1     The first type.
  1354      *  @param t2     The second type.
  1355      *  @param site   The most derived type.
  1356      *  @returns symbol from t2 that conflicts with one in t1.
  1357      */
  1358     private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
  1359         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1360         closure(t1, interfaces1);
  1361         Map<TypeSymbol,Type> interfaces2;
  1362         if (t1 == t2)
  1363             interfaces2 = interfaces1;
  1364         else
  1365             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1367         for (Type t3 : interfaces1.values()) {
  1368             for (Type t4 : interfaces2.values()) {
  1369                 Symbol s = firstDirectIncompatibility(t3, t4, site);
  1370                 if (s != null) return s;
  1373         return null;
  1376     /** Compute all the supertypes of t, indexed by type symbol. */
  1377     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1378         if (t.tag != CLASS) return;
  1379         if (typeMap.put(t.tsym, t) == null) {
  1380             closure(types.supertype(t), typeMap);
  1381             for (Type i : types.interfaces(t))
  1382                 closure(i, typeMap);
  1386     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1387     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1388         if (t.tag != CLASS) return;
  1389         if (typesSkip.get(t.tsym) != null) return;
  1390         if (typeMap.put(t.tsym, t) == null) {
  1391             closure(types.supertype(t), typesSkip, typeMap);
  1392             for (Type i : types.interfaces(t))
  1393                 closure(i, typesSkip, typeMap);
  1397     /** Return the first method in t2 that conflicts with a method from t1. */
  1398     private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
  1399         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1400             Symbol s1 = e1.sym;
  1401             Type st1 = null;
  1402             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1403             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1404             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1405             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1406                 Symbol s2 = e2.sym;
  1407                 if (s1 == s2) continue;
  1408                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1409                 if (st1 == null) st1 = types.memberType(t1, s1);
  1410                 Type st2 = types.memberType(t2, s2);
  1411                 if (types.overrideEquivalent(st1, st2)) {
  1412                     List<Type> tvars1 = st1.getTypeArguments();
  1413                     List<Type> tvars2 = st2.getTypeArguments();
  1414                     Type rt1 = st1.getReturnType();
  1415                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1416                     boolean compat =
  1417                         types.isSameType(rt1, rt2) ||
  1418                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1419                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1420                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1421                          checkCommonOverriderIn(s1,s2,site);
  1422                     if (!compat) return s2;
  1426         return null;
  1428     //WHERE
  1429     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1430         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1431         Type st1 = types.memberType(site, s1);
  1432         Type st2 = types.memberType(site, s2);
  1433         closure(site, supertypes);
  1434         for (Type t : supertypes.values()) {
  1435             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1436                 Symbol s3 = e.sym;
  1437                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1438                 Type st3 = types.memberType(site,s3);
  1439                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1440                     if (s3.owner == site.tsym) {
  1441                         return true;
  1443                     List<Type> tvars1 = st1.getTypeArguments();
  1444                     List<Type> tvars2 = st2.getTypeArguments();
  1445                     List<Type> tvars3 = st3.getTypeArguments();
  1446                     Type rt1 = st1.getReturnType();
  1447                     Type rt2 = st2.getReturnType();
  1448                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1449                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1450                     boolean compat =
  1451                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1452                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1453                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1454                     if (compat)
  1455                         return true;
  1459         return false;
  1462     /** Check that a given method conforms with any method it overrides.
  1463      *  @param tree         The tree from which positions are extracted
  1464      *                      for errors.
  1465      *  @param m            The overriding method.
  1466      */
  1467     void checkOverride(JCTree tree, MethodSymbol m) {
  1468         ClassSymbol origin = (ClassSymbol)m.owner;
  1469         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1470             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1471                 log.error(tree.pos(), "enum.no.finalize");
  1472                 return;
  1474         for (Type t = types.supertype(origin.type); t.tag == CLASS;
  1475              t = types.supertype(t)) {
  1476             TypeSymbol c = t.tsym;
  1477             Scope.Entry e = c.members().lookup(m.name);
  1478             while (e.scope != null) {
  1479                 if (m.overrides(e.sym, origin, types, false))
  1480                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1481                 else if (e.sym.kind == MTH &&
  1482                         e.sym.isInheritedIn(origin, types) &&
  1483                         (e.sym.flags() & SYNTHETIC) == 0 &&
  1484                         !m.isConstructor()) {
  1485                     Type er1 = m.erasure(types);
  1486                     Type er2 = e.sym.erasure(types);
  1487                     if (types.isSameTypes(er1.getParameterTypes(),
  1488                             er2.getParameterTypes())) {
  1489                             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1490                                     "name.clash.same.erasure.no.override",
  1491                                     m, m.location(),
  1492                                     e.sym, e.sym.location());
  1495                 e = e.next();
  1500     /** Check that all abstract members of given class have definitions.
  1501      *  @param pos          Position to be used for error reporting.
  1502      *  @param c            The class.
  1503      */
  1504     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1505         try {
  1506             MethodSymbol undef = firstUndef(c, c);
  1507             if (undef != null) {
  1508                 if ((c.flags() & ENUM) != 0 &&
  1509                     types.supertype(c.type).tsym == syms.enumSym &&
  1510                     (c.flags() & FINAL) == 0) {
  1511                     // add the ABSTRACT flag to an enum
  1512                     c.flags_field |= ABSTRACT;
  1513                 } else {
  1514                     MethodSymbol undef1 =
  1515                         new MethodSymbol(undef.flags(), undef.name,
  1516                                          types.memberType(c.type, undef), undef.owner);
  1517                     log.error(pos, "does.not.override.abstract",
  1518                               c, undef1, undef1.location());
  1521         } catch (CompletionFailure ex) {
  1522             completionError(pos, ex);
  1525 //where
  1526         /** Return first abstract member of class `c' that is not defined
  1527          *  in `impl', null if there is none.
  1528          */
  1529         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1530             MethodSymbol undef = null;
  1531             // Do not bother to search in classes that are not abstract,
  1532             // since they cannot have abstract members.
  1533             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1534                 Scope s = c.members();
  1535                 for (Scope.Entry e = s.elems;
  1536                      undef == null && e != null;
  1537                      e = e.sibling) {
  1538                     if (e.sym.kind == MTH &&
  1539                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1540                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1541                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1542                         if (implmeth == null || implmeth == absmeth)
  1543                             undef = absmeth;
  1546                 if (undef == null) {
  1547                     Type st = types.supertype(c.type);
  1548                     if (st.tag == CLASS)
  1549                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1551                 for (List<Type> l = types.interfaces(c.type);
  1552                      undef == null && l.nonEmpty();
  1553                      l = l.tail) {
  1554                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1557             return undef;
  1560     /** Check for cyclic references. Issue an error if the
  1561      *  symbol of the type referred to has a LOCKED flag set.
  1563      *  @param pos      Position to be used for error reporting.
  1564      *  @param t        The type referred to.
  1565      */
  1566     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1567         checkNonCyclicInternal(pos, t);
  1571     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1572         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1575     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1576         final TypeVar tv;
  1577         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1578             return;
  1579         if (seen.contains(t)) {
  1580             tv = (TypeVar)t;
  1581             tv.bound = types.createErrorType(t);
  1582             log.error(pos, "cyclic.inheritance", t);
  1583         } else if (t.tag == TYPEVAR) {
  1584             tv = (TypeVar)t;
  1585             seen = seen.prepend(tv);
  1586             for (Type b : types.getBounds(tv))
  1587                 checkNonCyclic1(pos, b, seen);
  1591     /** Check for cyclic references. Issue an error if the
  1592      *  symbol of the type referred to has a LOCKED flag set.
  1594      *  @param pos      Position to be used for error reporting.
  1595      *  @param t        The type referred to.
  1596      *  @returns        True if the check completed on all attributed classes
  1597      */
  1598     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1599         boolean complete = true; // was the check complete?
  1600         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1601         Symbol c = t.tsym;
  1602         if ((c.flags_field & ACYCLIC) != 0) return true;
  1604         if ((c.flags_field & LOCKED) != 0) {
  1605             noteCyclic(pos, (ClassSymbol)c);
  1606         } else if (!c.type.isErroneous()) {
  1607             try {
  1608                 c.flags_field |= LOCKED;
  1609                 if (c.type.tag == CLASS) {
  1610                     ClassType clazz = (ClassType)c.type;
  1611                     if (clazz.interfaces_field != null)
  1612                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1613                             complete &= checkNonCyclicInternal(pos, l.head);
  1614                     if (clazz.supertype_field != null) {
  1615                         Type st = clazz.supertype_field;
  1616                         if (st != null && st.tag == CLASS)
  1617                             complete &= checkNonCyclicInternal(pos, st);
  1619                     if (c.owner.kind == TYP)
  1620                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1622             } finally {
  1623                 c.flags_field &= ~LOCKED;
  1626         if (complete)
  1627             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1628         if (complete) c.flags_field |= ACYCLIC;
  1629         return complete;
  1632     /** Note that we found an inheritance cycle. */
  1633     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1634         log.error(pos, "cyclic.inheritance", c);
  1635         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1636             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  1637         Type st = types.supertype(c.type);
  1638         if (st.tag == CLASS)
  1639             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  1640         c.type = types.createErrorType(c, c.type);
  1641         c.flags_field |= ACYCLIC;
  1644     /** Check that all methods which implement some
  1645      *  method conform to the method they implement.
  1646      *  @param tree         The class definition whose members are checked.
  1647      */
  1648     void checkImplementations(JCClassDecl tree) {
  1649         checkImplementations(tree, tree.sym);
  1651 //where
  1652         /** Check that all methods which implement some
  1653          *  method in `ic' conform to the method they implement.
  1654          */
  1655         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1656             ClassSymbol origin = tree.sym;
  1657             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1658                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1659                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1660                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  1661                         if (e.sym.kind == MTH &&
  1662                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  1663                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  1664                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  1665                             if (implmeth != null && implmeth != absmeth &&
  1666                                 (implmeth.owner.flags() & INTERFACE) ==
  1667                                 (origin.flags() & INTERFACE)) {
  1668                                 // don't check if implmeth is in a class, yet
  1669                                 // origin is an interface. This case arises only
  1670                                 // if implmeth is declared in Object. The reason is
  1671                                 // that interfaces really don't inherit from
  1672                                 // Object it's just that the compiler represents
  1673                                 // things that way.
  1674                                 checkOverride(tree, implmeth, absmeth, origin);
  1682     /** Check that all abstract methods implemented by a class are
  1683      *  mutually compatible.
  1684      *  @param pos          Position to be used for error reporting.
  1685      *  @param c            The class whose interfaces are checked.
  1686      */
  1687     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  1688         List<Type> supertypes = types.interfaces(c);
  1689         Type supertype = types.supertype(c);
  1690         if (supertype.tag == CLASS &&
  1691             (supertype.tsym.flags() & ABSTRACT) != 0)
  1692             supertypes = supertypes.prepend(supertype);
  1693         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  1694             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  1695                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  1696                 return;
  1697             for (List<Type> m = supertypes; m != l; m = m.tail)
  1698                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  1699                     return;
  1701         checkCompatibleConcretes(pos, c);
  1704     /** Check that class c does not implement directly or indirectly
  1705      *  the same parameterized interface with two different argument lists.
  1706      *  @param pos          Position to be used for error reporting.
  1707      *  @param type         The type whose interfaces are checked.
  1708      */
  1709     void checkClassBounds(DiagnosticPosition pos, Type type) {
  1710         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  1712 //where
  1713         /** Enter all interfaces of type `type' into the hash table `seensofar'
  1714          *  with their class symbol as key and their type as value. Make
  1715          *  sure no class is entered with two different types.
  1716          */
  1717         void checkClassBounds(DiagnosticPosition pos,
  1718                               Map<TypeSymbol,Type> seensofar,
  1719                               Type type) {
  1720             if (type.isErroneous()) return;
  1721             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  1722                 Type it = l.head;
  1723                 Type oldit = seensofar.put(it.tsym, it);
  1724                 if (oldit != null) {
  1725                     List<Type> oldparams = oldit.allparams();
  1726                     List<Type> newparams = it.allparams();
  1727                     if (!types.containsTypeEquivalent(oldparams, newparams))
  1728                         log.error(pos, "cant.inherit.diff.arg",
  1729                                   it.tsym, Type.toString(oldparams),
  1730                                   Type.toString(newparams));
  1732                 checkClassBounds(pos, seensofar, it);
  1734             Type st = types.supertype(type);
  1735             if (st != null) checkClassBounds(pos, seensofar, st);
  1738     /** Enter interface into into set.
  1739      *  If it existed already, issue a "repeated interface" error.
  1740      */
  1741     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  1742         if (its.contains(it))
  1743             log.error(pos, "repeated.interface");
  1744         else {
  1745             its.add(it);
  1749 /* *************************************************************************
  1750  * Check annotations
  1751  **************************************************************************/
  1753     /** Annotation types are restricted to primitives, String, an
  1754      *  enum, an annotation, Class, Class<?>, Class<? extends
  1755      *  Anything>, arrays of the preceding.
  1756      */
  1757     void validateAnnotationType(JCTree restype) {
  1758         // restype may be null if an error occurred, so don't bother validating it
  1759         if (restype != null) {
  1760             validateAnnotationType(restype.pos(), restype.type);
  1764     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  1765         if (type.isPrimitive()) return;
  1766         if (types.isSameType(type, syms.stringType)) return;
  1767         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  1768         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  1769         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  1770         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  1771             validateAnnotationType(pos, types.elemtype(type));
  1772             return;
  1774         log.error(pos, "invalid.annotation.member.type");
  1777     /**
  1778      * "It is also a compile-time error if any method declared in an
  1779      * annotation type has a signature that is override-equivalent to
  1780      * that of any public or protected method declared in class Object
  1781      * or in the interface annotation.Annotation."
  1783      * @jls3 9.6 Annotation Types
  1784      */
  1785     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  1786         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  1787             Scope s = sup.tsym.members();
  1788             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  1789                 if (e.sym.kind == MTH &&
  1790                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  1791                     types.overrideEquivalent(m.type, e.sym.type))
  1792                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  1797     /** Check the annotations of a symbol.
  1798      */
  1799     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  1800         if (skipAnnotations) return;
  1801         for (JCAnnotation a : annotations)
  1802             validateAnnotation(a, s);
  1805     /** Check an annotation of a symbol.
  1806      */
  1807     public void validateAnnotation(JCAnnotation a, Symbol s) {
  1808         validateAnnotation(a);
  1810         if (!annotationApplicable(a, s))
  1811             log.error(a.pos(), "annotation.type.not.applicable");
  1813         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1814             if (!isOverrider(s))
  1815                 log.error(a.pos(), "method.does.not.override.superclass");
  1819     /** Is s a method symbol that overrides a method in a superclass? */
  1820     boolean isOverrider(Symbol s) {
  1821         if (s.kind != MTH || s.isStatic())
  1822             return false;
  1823         MethodSymbol m = (MethodSymbol)s;
  1824         TypeSymbol owner = (TypeSymbol)m.owner;
  1825         for (Type sup : types.closure(owner.type)) {
  1826             if (sup == owner.type)
  1827                 continue; // skip "this"
  1828             Scope scope = sup.tsym.members();
  1829             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  1830                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  1831                     return true;
  1834         return false;
  1837     /** Is the annotation applicable to the symbol? */
  1838     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  1839         Attribute.Compound atTarget =
  1840             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1841         if (atTarget == null) return true;
  1842         Attribute atValue = atTarget.member(names.value);
  1843         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1844         Attribute.Array arr = (Attribute.Array) atValue;
  1845         for (Attribute app : arr.values) {
  1846             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1847             Attribute.Enum e = (Attribute.Enum) app;
  1848             if (e.value.name == names.TYPE)
  1849                 { if (s.kind == TYP) return true; }
  1850             else if (e.value.name == names.FIELD)
  1851                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  1852             else if (e.value.name == names.METHOD)
  1853                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  1854             else if (e.value.name == names.PARAMETER)
  1855                 { if (s.kind == VAR &&
  1856                       s.owner.kind == MTH &&
  1857                       (s.flags() & PARAMETER) != 0)
  1858                     return true;
  1860             else if (e.value.name == names.CONSTRUCTOR)
  1861                 { if (s.kind == MTH && s.isConstructor()) return true; }
  1862             else if (e.value.name == names.LOCAL_VARIABLE)
  1863                 { if (s.kind == VAR && s.owner.kind == MTH &&
  1864                       (s.flags() & PARAMETER) == 0)
  1865                     return true;
  1867             else if (e.value.name == names.ANNOTATION_TYPE)
  1868                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  1869                     return true;
  1871             else if (e.value.name == names.PACKAGE)
  1872                 { if (s.kind == PCK) return true; }
  1873             else
  1874                 return true; // recovery
  1876         return false;
  1879     /** Check an annotation value.
  1880      */
  1881     public void validateAnnotation(JCAnnotation a) {
  1882         if (a.type.isErroneous()) return;
  1884         // collect an inventory of the members
  1885         Set<MethodSymbol> members = new HashSet<MethodSymbol>();
  1886         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  1887              e != null;
  1888              e = e.sibling)
  1889             if (e.sym.kind == MTH)
  1890                 members.add((MethodSymbol) e.sym);
  1892         // count them off as they're annotated
  1893         for (JCTree arg : a.args) {
  1894             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  1895             JCAssign assign = (JCAssign) arg;
  1896             Symbol m = TreeInfo.symbol(assign.lhs);
  1897             if (m == null || m.type.isErroneous()) continue;
  1898             if (!members.remove(m))
  1899                 log.error(arg.pos(), "duplicate.annotation.member.value",
  1900                           m.name, a.type);
  1901             if (assign.rhs.getTag() == ANNOTATION)
  1902                 validateAnnotation((JCAnnotation)assign.rhs);
  1905         // all the remaining ones better have default values
  1906         for (MethodSymbol m : members)
  1907             if (m.defaultValue == null && !m.type.isErroneous())
  1908                 log.error(a.pos(), "annotation.missing.default.value",
  1909                           a.type, m.name);
  1911         // special case: java.lang.annotation.Target must not have
  1912         // repeated values in its value member
  1913         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  1914             a.args.tail == null)
  1915             return;
  1917         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  1918         JCAssign assign = (JCAssign) a.args.head;
  1919         Symbol m = TreeInfo.symbol(assign.lhs);
  1920         if (m.name != names.value) return;
  1921         JCTree rhs = assign.rhs;
  1922         if (rhs.getTag() != JCTree.NEWARRAY) return;
  1923         JCNewArray na = (JCNewArray) rhs;
  1924         Set<Symbol> targets = new HashSet<Symbol>();
  1925         for (JCTree elem : na.elems) {
  1926             if (!targets.add(TreeInfo.symbol(elem))) {
  1927                 log.error(elem.pos(), "repeated.annotation.target");
  1932     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  1933         if (allowAnnotations &&
  1934             lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
  1935             (s.flags() & DEPRECATED) != 0 &&
  1936             !syms.deprecatedType.isErroneous() &&
  1937             s.attribute(syms.deprecatedType.tsym) == null) {
  1938             log.warning(pos, "missing.deprecated.annotation");
  1942 /* *************************************************************************
  1943  * Check for recursive annotation elements.
  1944  **************************************************************************/
  1946     /** Check for cycles in the graph of annotation elements.
  1947      */
  1948     void checkNonCyclicElements(JCClassDecl tree) {
  1949         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  1950         assert (tree.sym.flags_field & LOCKED) == 0;
  1951         try {
  1952             tree.sym.flags_field |= LOCKED;
  1953             for (JCTree def : tree.defs) {
  1954                 if (def.getTag() != JCTree.METHODDEF) continue;
  1955                 JCMethodDecl meth = (JCMethodDecl)def;
  1956                 checkAnnotationResType(meth.pos(), meth.restype.type);
  1958         } finally {
  1959             tree.sym.flags_field &= ~LOCKED;
  1960             tree.sym.flags_field |= ACYCLIC_ANN;
  1964     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  1965         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  1966             return;
  1967         if ((tsym.flags_field & LOCKED) != 0) {
  1968             log.error(pos, "cyclic.annotation.element");
  1969             return;
  1971         try {
  1972             tsym.flags_field |= LOCKED;
  1973             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  1974                 Symbol s = e.sym;
  1975                 if (s.kind != Kinds.MTH)
  1976                     continue;
  1977                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  1979         } finally {
  1980             tsym.flags_field &= ~LOCKED;
  1981             tsym.flags_field |= ACYCLIC_ANN;
  1985     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  1986         switch (type.tag) {
  1987         case TypeTags.CLASS:
  1988             if ((type.tsym.flags() & ANNOTATION) != 0)
  1989                 checkNonCyclicElementsInternal(pos, type.tsym);
  1990             break;
  1991         case TypeTags.ARRAY:
  1992             checkAnnotationResType(pos, types.elemtype(type));
  1993             break;
  1994         default:
  1995             break; // int etc
  1999 /* *************************************************************************
  2000  * Check for cycles in the constructor call graph.
  2001  **************************************************************************/
  2003     /** Check for cycles in the graph of constructors calling other
  2004      *  constructors.
  2005      */
  2006     void checkCyclicConstructors(JCClassDecl tree) {
  2007         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2009         // enter each constructor this-call into the map
  2010         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2011             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2012             if (app == null) continue;
  2013             JCMethodDecl meth = (JCMethodDecl) l.head;
  2014             if (TreeInfo.name(app.meth) == names._this) {
  2015                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2016             } else {
  2017                 meth.sym.flags_field |= ACYCLIC;
  2021         // Check for cycles in the map
  2022         Symbol[] ctors = new Symbol[0];
  2023         ctors = callMap.keySet().toArray(ctors);
  2024         for (Symbol caller : ctors) {
  2025             checkCyclicConstructor(tree, caller, callMap);
  2029     /** Look in the map to see if the given constructor is part of a
  2030      *  call cycle.
  2031      */
  2032     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2033                                         Map<Symbol,Symbol> callMap) {
  2034         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2035             if ((ctor.flags_field & LOCKED) != 0) {
  2036                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2037                           "recursive.ctor.invocation");
  2038             } else {
  2039                 ctor.flags_field |= LOCKED;
  2040                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2041                 ctor.flags_field &= ~LOCKED;
  2043             ctor.flags_field |= ACYCLIC;
  2047 /* *************************************************************************
  2048  * Miscellaneous
  2049  **************************************************************************/
  2051     /**
  2052      * Return the opcode of the operator but emit an error if it is an
  2053      * error.
  2054      * @param pos        position for error reporting.
  2055      * @param operator   an operator
  2056      * @param tag        a tree tag
  2057      * @param left       type of left hand side
  2058      * @param right      type of right hand side
  2059      */
  2060     int checkOperator(DiagnosticPosition pos,
  2061                        OperatorSymbol operator,
  2062                        int tag,
  2063                        Type left,
  2064                        Type right) {
  2065         if (operator.opcode == ByteCodes.error) {
  2066             log.error(pos,
  2067                       "operator.cant.be.applied",
  2068                       treeinfo.operatorName(tag),
  2069                       List.of(left, right));
  2071         return operator.opcode;
  2075     /**
  2076      *  Check for division by integer constant zero
  2077      *  @param pos           Position for error reporting.
  2078      *  @param operator      The operator for the expression
  2079      *  @param operand       The right hand operand for the expression
  2080      */
  2081     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2082         if (operand.constValue() != null
  2083             && lint.isEnabled(Lint.LintCategory.DIVZERO)
  2084             && operand.tag <= LONG
  2085             && ((Number) (operand.constValue())).longValue() == 0) {
  2086             int opc = ((OperatorSymbol)operator).opcode;
  2087             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2088                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2089                 log.warning(pos, "div.zero");
  2094     /**
  2095      * Check for empty statements after if
  2096      */
  2097     void checkEmptyIf(JCIf tree) {
  2098         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
  2099             log.warning(tree.thenpart.pos(), "empty.if");
  2102     /** Check that symbol is unique in given scope.
  2103      *  @param pos           Position for error reporting.
  2104      *  @param sym           The symbol.
  2105      *  @param s             The scope.
  2106      */
  2107     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2108         if (sym.type.isErroneous())
  2109             return true;
  2110         if (sym.owner.name == names.any) return false;
  2111         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2112             if (sym != e.sym &&
  2113                 sym.kind == e.sym.kind &&
  2114                 sym.name != names.error &&
  2115                 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2116                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2117                     varargsDuplicateError(pos, sym, e.sym);
  2118                 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
  2119                     duplicateErasureError(pos, sym, e.sym);
  2120                 else
  2121                     duplicateError(pos, e.sym);
  2122                 return false;
  2125         return true;
  2127     //where
  2128     /** Report duplicate declaration error.
  2129      */
  2130     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2131         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2132             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2136     /** Check that single-type import is not already imported or top-level defined,
  2137      *  but make an exception for two single-type imports which denote the same type.
  2138      *  @param pos           Position for error reporting.
  2139      *  @param sym           The symbol.
  2140      *  @param s             The scope
  2141      */
  2142     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2143         return checkUniqueImport(pos, sym, s, false);
  2146     /** Check that static single-type import is not already imported or top-level defined,
  2147      *  but make an exception for two single-type imports which denote the same type.
  2148      *  @param pos           Position for error reporting.
  2149      *  @param sym           The symbol.
  2150      *  @param s             The scope
  2151      *  @param staticImport  Whether or not this was a static import
  2152      */
  2153     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2154         return checkUniqueImport(pos, sym, s, true);
  2157     /** Check that single-type import is not already imported or top-level defined,
  2158      *  but make an exception for two single-type imports which denote the same type.
  2159      *  @param pos           Position for error reporting.
  2160      *  @param sym           The symbol.
  2161      *  @param s             The scope.
  2162      *  @param staticImport  Whether or not this was a static import
  2163      */
  2164     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2165         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2166             // is encountered class entered via a class declaration?
  2167             boolean isClassDecl = e.scope == s;
  2168             if ((isClassDecl || sym != e.sym) &&
  2169                 sym.kind == e.sym.kind &&
  2170                 sym.name != names.error) {
  2171                 if (!e.sym.type.isErroneous()) {
  2172                     String what = e.sym.toString();
  2173                     if (!isClassDecl) {
  2174                         if (staticImport)
  2175                             log.error(pos, "already.defined.static.single.import", what);
  2176                         else
  2177                             log.error(pos, "already.defined.single.import", what);
  2179                     else if (sym != e.sym)
  2180                         log.error(pos, "already.defined.this.unit", what);
  2182                 return false;
  2185         return true;
  2188     /** Check that a qualified name is in canonical form (for import decls).
  2189      */
  2190     public void checkCanonical(JCTree tree) {
  2191         if (!isCanonical(tree))
  2192             log.error(tree.pos(), "import.requires.canonical",
  2193                       TreeInfo.symbol(tree));
  2195         // where
  2196         private boolean isCanonical(JCTree tree) {
  2197             while (tree.getTag() == JCTree.SELECT) {
  2198                 JCFieldAccess s = (JCFieldAccess) tree;
  2199                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2200                     return false;
  2201                 tree = s.selected;
  2203             return true;
  2206     private class ConversionWarner extends Warner {
  2207         final String key;
  2208         final Type found;
  2209         final Type expected;
  2210         public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
  2211             super(pos);
  2212             this.key = key;
  2213             this.found = found;
  2214             this.expected = expected;
  2217         public void warnUnchecked() {
  2218             boolean warned = this.warned;
  2219             super.warnUnchecked();
  2220             if (warned) return; // suppress redundant diagnostics
  2221             Object problem = diags.fragment(key);
  2222             Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
  2226     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2227         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2230     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2231         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial