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

Thu, 25 Feb 2010 09:42:35 -0800

author
jjg
date
Thu, 25 Feb 2010 09:42:35 -0800
changeset 505
87eb6edd4f21
parent 479
da0e3e2dd3ef
child 536
396b117c1743
permissions
-rw-r--r--

4880220: Add a warning when accessing a static method via an reference
Reviewed-by: darcy

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

mercurial