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

Tue, 11 Aug 2009 01:13:14 +0100

author
mcimadamore
date
Tue, 11 Aug 2009 01:13:14 +0100
changeset 359
8227961c64d3
parent 308
03944ee4fac4
child 362
c4c424badb83
permissions
-rw-r--r--

6521805: Regression: JDK5/JDK6 javac allows write access to outer class reference
Summary: javac should warn/complain about identifiers with the same name as synthetic symbol
Reviewed-by: jjg

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

mercurial