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

Sat, 01 May 2010 15:05:39 -0700

author
jrose
date
Sat, 01 May 2010 15:05:39 -0700
changeset 571
f0e3ec1f9d9f
parent 537
9d9d08922405
child 547
04cf82179fa7
permissions
-rw-r--r--

6939134: JSR 292 adjustments to method handle invocation
Summary: split MethodHandle.invoke into invokeExact and invokeGeneric
Reviewed-by: twisti

     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 (found.tag == FORALL)
   379             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   380         if (req.tag == NONE)
   381             return found;
   382         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   383             return found;
   384         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   385             return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
   386         if (found.isSuperBound()) {
   387             log.error(pos, "assignment.from.super-bound", found);
   388             return types.createErrorType(found);
   389         }
   390         if (req.isExtendsBound()) {
   391             log.error(pos, "assignment.to.extends-bound", req);
   392             return types.createErrorType(found);
   393         }
   394         return typeError(pos, diags.fragment("incompatible.types"), found, req);
   395     }
   397     /** Instantiate polymorphic type to some prototype, unless
   398      *  prototype is `anyPoly' in which case polymorphic type
   399      *  is returned unchanged.
   400      */
   401     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
   402         if (pt == Infer.anyPoly && complexInference) {
   403             return t;
   404         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   405             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   406             return instantiatePoly(pos, t, newpt, warn);
   407         } else if (pt.tag == ERROR) {
   408             return pt;
   409         } else {
   410             try {
   411                 return infer.instantiateExpr(t, pt, warn);
   412             } catch (Infer.NoInstanceException ex) {
   413                 if (ex.isAmbiguous) {
   414                     JCDiagnostic d = ex.getDiagnostic();
   415                     log.error(pos,
   416                               "undetermined.type" + (d!=null ? ".1" : ""),
   417                               t, d);
   418                     return types.createErrorType(pt);
   419                 } else {
   420                     JCDiagnostic d = ex.getDiagnostic();
   421                     return typeError(pos,
   422                                      diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   423                                      t, pt);
   424                 }
   425             } catch (Infer.InvalidInstanceException ex) {
   426                 JCDiagnostic d = ex.getDiagnostic();
   427                 log.error(pos, "invalid.inferred.types", t.tvars, d);
   428                 return types.createErrorType(pt);
   429             }
   430         }
   431     }
   433     /** Check that a given type can be cast to a given target type.
   434      *  Return the result of the cast.
   435      *  @param pos        Position to be used for error reporting.
   436      *  @param found      The type that is being cast.
   437      *  @param req        The target type of the cast.
   438      */
   439     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   440         if (found.tag == FORALL) {
   441             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   442             return req;
   443         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   444             return req;
   445         } else {
   446             return typeError(pos,
   447                              diags.fragment("inconvertible.types"),
   448                              found, req);
   449         }
   450     }
   451 //where
   452         /** Is type a type variable, or a (possibly multi-dimensional) array of
   453          *  type variables?
   454          */
   455         boolean isTypeVar(Type t) {
   456             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   457         }
   459     /** Check that a type is within some bounds.
   460      *
   461      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   462      *  type argument.
   463      *  @param pos           Position to be used for error reporting.
   464      *  @param a             The type that should be bounded by bs.
   465      *  @param bs            The bound.
   466      */
   467     private void checkExtends(DiagnosticPosition pos, Type a, TypeVar bs) {
   468          if (a.isUnbound()) {
   469              return;
   470          } else if (a.tag != WILDCARD) {
   471              a = types.upperBound(a);
   472              for (List<Type> l = types.getBounds(bs); l.nonEmpty(); l = l.tail) {
   473                  if (!types.isSubtype(a, l.head)) {
   474                      log.error(pos, "not.within.bounds", a);
   475                      return;
   476                  }
   477              }
   478          } else if (a.isExtendsBound()) {
   479              if (!types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings))
   480                  log.error(pos, "not.within.bounds", a);
   481          } else if (a.isSuperBound()) {
   482              if (types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound()))
   483                  log.error(pos, "not.within.bounds", a);
   484          }
   485      }
   487     /** Check that a type is within some bounds.
   488      *
   489      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   490      *  type argument.
   491      *  @param pos           Position to be used for error reporting.
   492      *  @param a             The type that should be bounded by bs.
   493      *  @param bs            The bound.
   494      */
   495     private void checkCapture(JCTypeApply tree) {
   496         List<JCExpression> args = tree.getTypeArguments();
   497         for (Type arg : types.capture(tree.type).getTypeArguments()) {
   498             if (arg.tag == TYPEVAR && arg.getUpperBound().isErroneous()) {
   499                 log.error(args.head.pos, "not.within.bounds", args.head.type);
   500                 break;
   501             }
   502             args = args.tail;
   503         }
   504      }
   506     /** Check that type is different from 'void'.
   507      *  @param pos           Position to be used for error reporting.
   508      *  @param t             The type to be checked.
   509      */
   510     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   511         if (t.tag == VOID) {
   512             log.error(pos, "void.not.allowed.here");
   513             return types.createErrorType(t);
   514         } else {
   515             return t;
   516         }
   517     }
   519     /** Check that type is a class or interface type.
   520      *  @param pos           Position to be used for error reporting.
   521      *  @param t             The type to be checked.
   522      */
   523     Type checkClassType(DiagnosticPosition pos, Type t) {
   524         if (t.tag != CLASS && t.tag != ERROR)
   525             return typeTagError(pos,
   526                                 diags.fragment("type.req.class"),
   527                                 (t.tag == TYPEVAR)
   528                                 ? diags.fragment("type.parameter", t)
   529                                 : t);
   530         else
   531             return t;
   532     }
   534     /** Check that type is a class or interface type.
   535      *  @param pos           Position to be used for error reporting.
   536      *  @param t             The type to be checked.
   537      *  @param noBounds    True if type bounds are illegal here.
   538      */
   539     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   540         t = checkClassType(pos, t);
   541         if (noBounds && t.isParameterized()) {
   542             List<Type> args = t.getTypeArguments();
   543             while (args.nonEmpty()) {
   544                 if (args.head.tag == WILDCARD)
   545                     return typeTagError(pos,
   546                                         Log.getLocalizedString("type.req.exact"),
   547                                         args.head);
   548                 args = args.tail;
   549             }
   550         }
   551         return t;
   552     }
   554     /** Check that type is a reifiable class, interface or array type.
   555      *  @param pos           Position to be used for error reporting.
   556      *  @param t             The type to be checked.
   557      */
   558     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   559         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   560             return typeTagError(pos,
   561                                 diags.fragment("type.req.class.array"),
   562                                 t);
   563         } else if (!types.isReifiable(t)) {
   564             log.error(pos, "illegal.generic.type.for.instof");
   565             return types.createErrorType(t);
   566         } else {
   567             return t;
   568         }
   569     }
   571     /** Check that type is a reference type, i.e. a class, interface or array type
   572      *  or a type variable.
   573      *  @param pos           Position to be used for error reporting.
   574      *  @param t             The type to be checked.
   575      */
   576     Type checkRefType(DiagnosticPosition pos, Type t) {
   577         switch (t.tag) {
   578         case CLASS:
   579         case ARRAY:
   580         case TYPEVAR:
   581         case WILDCARD:
   582         case ERROR:
   583             return t;
   584         default:
   585             return typeTagError(pos,
   586                                 diags.fragment("type.req.ref"),
   587                                 t);
   588         }
   589     }
   591     /** Check that each type is a reference type, i.e. a class, interface or array type
   592      *  or a type variable.
   593      *  @param trees         Original trees, used for error reporting.
   594      *  @param types         The types to be checked.
   595      */
   596     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   597         List<JCExpression> tl = trees;
   598         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   599             l.head = checkRefType(tl.head.pos(), l.head);
   600             tl = tl.tail;
   601         }
   602         return types;
   603     }
   605     /** Check that type is a null or reference type.
   606      *  @param pos           Position to be used for error reporting.
   607      *  @param t             The type to be checked.
   608      */
   609     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   610         switch (t.tag) {
   611         case CLASS:
   612         case ARRAY:
   613         case TYPEVAR:
   614         case WILDCARD:
   615         case BOT:
   616         case ERROR:
   617             return t;
   618         default:
   619             return typeTagError(pos,
   620                                 diags.fragment("type.req.ref"),
   621                                 t);
   622         }
   623     }
   625     /** Check that flag set does not contain elements of two conflicting sets. s
   626      *  Return true if it doesn't.
   627      *  @param pos           Position to be used for error reporting.
   628      *  @param flags         The set of flags to be checked.
   629      *  @param set1          Conflicting flags set #1.
   630      *  @param set2          Conflicting flags set #2.
   631      */
   632     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   633         if ((flags & set1) != 0 && (flags & set2) != 0) {
   634             log.error(pos,
   635                       "illegal.combination.of.modifiers",
   636                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   637                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   638             return false;
   639         } else
   640             return true;
   641     }
   643     /** Check that the type inferred using the diamond operator does not contain
   644      *  non-denotable types such as captured types or intersection types.
   645      *  @param t the type inferred using the diamond operator
   646      */
   647     List<Type> checkDiamond(ClassType t) {
   648         DiamondTypeChecker dtc = new DiamondTypeChecker();
   649         ListBuffer<Type> buf = ListBuffer.lb();
   650         for (Type arg : t.getTypeArguments()) {
   651             if (!dtc.visit(arg, null)) {
   652                 buf.append(arg);
   653             }
   654         }
   655         return buf.toList();
   656     }
   658     static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
   659         public Boolean visitType(Type t, Void s) {
   660             return true;
   661         }
   662         @Override
   663         public Boolean visitClassType(ClassType t, Void s) {
   664             if (t.isCompound()) {
   665                 return false;
   666             }
   667             for (Type targ : t.getTypeArguments()) {
   668                 if (!visit(targ, s)) {
   669                     return false;
   670                 }
   671             }
   672             return true;
   673         }
   674         @Override
   675         public Boolean visitCapturedType(CapturedType t, Void s) {
   676             return false;
   677         }
   678     }
   680     /** Check that given modifiers are legal for given symbol and
   681      *  return modifiers together with any implicit modififiers for that symbol.
   682      *  Warning: we can't use flags() here since this method
   683      *  is called during class enter, when flags() would cause a premature
   684      *  completion.
   685      *  @param pos           Position to be used for error reporting.
   686      *  @param flags         The set of modifiers given in a definition.
   687      *  @param sym           The defined symbol.
   688      */
   689     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   690         long mask;
   691         long implicit = 0;
   692         switch (sym.kind) {
   693         case VAR:
   694             if (sym.owner.kind != TYP)
   695                 mask = LocalVarFlags;
   696             else if ((sym.owner.flags_field & INTERFACE) != 0)
   697                 mask = implicit = InterfaceVarFlags;
   698             else
   699                 mask = VarFlags;
   700             break;
   701         case MTH:
   702             if (sym.name == names.init) {
   703                 if ((sym.owner.flags_field & ENUM) != 0) {
   704                     // enum constructors cannot be declared public or
   705                     // protected and must be implicitly or explicitly
   706                     // private
   707                     implicit = PRIVATE;
   708                     mask = PRIVATE;
   709                 } else
   710                     mask = ConstructorFlags;
   711             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   712                 mask = implicit = InterfaceMethodFlags;
   713             else {
   714                 mask = MethodFlags;
   715             }
   716             // Imply STRICTFP if owner has STRICTFP set.
   717             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   718               implicit |= sym.owner.flags_field & STRICTFP;
   719             break;
   720         case TYP:
   721             if (sym.isLocal()) {
   722                 mask = LocalClassFlags;
   723                 if (sym.name.isEmpty()) { // Anonymous class
   724                     // Anonymous classes in static methods are themselves static;
   725                     // that's why we admit STATIC here.
   726                     mask |= STATIC;
   727                     // JLS: Anonymous classes are final.
   728                     implicit |= FINAL;
   729                 }
   730                 if ((sym.owner.flags_field & STATIC) == 0 &&
   731                     (flags & ENUM) != 0)
   732                     log.error(pos, "enums.must.be.static");
   733             } else if (sym.owner.kind == TYP) {
   734                 mask = MemberClassFlags;
   735                 if (sym.owner.owner.kind == PCK ||
   736                     (sym.owner.flags_field & STATIC) != 0)
   737                     mask |= STATIC;
   738                 else if ((flags & ENUM) != 0)
   739                     log.error(pos, "enums.must.be.static");
   740                 // Nested interfaces and enums are always STATIC (Spec ???)
   741                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   742             } else {
   743                 mask = ClassFlags;
   744             }
   745             // Interfaces are always ABSTRACT
   746             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   748             if ((flags & ENUM) != 0) {
   749                 // enums can't be declared abstract or final
   750                 mask &= ~(ABSTRACT | FINAL);
   751                 implicit |= implicitEnumFinalFlag(tree);
   752             }
   753             // Imply STRICTFP if owner has STRICTFP set.
   754             implicit |= sym.owner.flags_field & STRICTFP;
   755             break;
   756         default:
   757             throw new AssertionError();
   758         }
   759         long illegal = flags & StandardFlags & ~mask;
   760         if (illegal != 0) {
   761             if ((illegal & INTERFACE) != 0) {
   762                 log.error(pos, "intf.not.allowed.here");
   763                 mask |= INTERFACE;
   764             }
   765             else {
   766                 log.error(pos,
   767                           "mod.not.allowed.here", asFlagSet(illegal));
   768             }
   769         }
   770         else if ((sym.kind == TYP ||
   771                   // ISSUE: Disallowing abstract&private is no longer appropriate
   772                   // in the presence of inner classes. Should it be deleted here?
   773                   checkDisjoint(pos, flags,
   774                                 ABSTRACT,
   775                                 PRIVATE | STATIC))
   776                  &&
   777                  checkDisjoint(pos, flags,
   778                                ABSTRACT | INTERFACE,
   779                                FINAL | NATIVE | SYNCHRONIZED)
   780                  &&
   781                  checkDisjoint(pos, flags,
   782                                PUBLIC,
   783                                PRIVATE | PROTECTED)
   784                  &&
   785                  checkDisjoint(pos, flags,
   786                                PRIVATE,
   787                                PUBLIC | PROTECTED)
   788                  &&
   789                  checkDisjoint(pos, flags,
   790                                FINAL,
   791                                VOLATILE)
   792                  &&
   793                  (sym.kind == TYP ||
   794                   checkDisjoint(pos, flags,
   795                                 ABSTRACT | NATIVE,
   796                                 STRICTFP))) {
   797             // skip
   798         }
   799         return flags & (mask | ~StandardFlags) | implicit;
   800     }
   803     /** Determine if this enum should be implicitly final.
   804      *
   805      *  If the enum has no specialized enum contants, it is final.
   806      *
   807      *  If the enum does have specialized enum contants, it is
   808      *  <i>not</i> final.
   809      */
   810     private long implicitEnumFinalFlag(JCTree tree) {
   811         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   812         class SpecialTreeVisitor extends JCTree.Visitor {
   813             boolean specialized;
   814             SpecialTreeVisitor() {
   815                 this.specialized = false;
   816             };
   818             @Override
   819             public void visitTree(JCTree tree) { /* no-op */ }
   821             @Override
   822             public void visitVarDef(JCVariableDecl tree) {
   823                 if ((tree.mods.flags & ENUM) != 0) {
   824                     if (tree.init instanceof JCNewClass &&
   825                         ((JCNewClass) tree.init).def != null) {
   826                         specialized = true;
   827                     }
   828                 }
   829             }
   830         }
   832         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   833         JCClassDecl cdef = (JCClassDecl) tree;
   834         for (JCTree defs: cdef.defs) {
   835             defs.accept(sts);
   836             if (sts.specialized) return 0;
   837         }
   838         return FINAL;
   839     }
   841 /* *************************************************************************
   842  * Type Validation
   843  **************************************************************************/
   845     /** Validate a type expression. That is,
   846      *  check that all type arguments of a parametric type are within
   847      *  their bounds. This must be done in a second phase after type attributon
   848      *  since a class might have a subclass as type parameter bound. E.g:
   849      *
   850      *  class B<A extends C> { ... }
   851      *  class C extends B<C> { ... }
   852      *
   853      *  and we can't make sure that the bound is already attributed because
   854      *  of possible cycles.
   855      */
   856     private Validator validator = new Validator();
   858     /** Visitor method: Validate a type expression, if it is not null, catching
   859      *  and reporting any completion failures.
   860      */
   861     void validate(JCTree tree, Env<AttrContext> env) {
   862         try {
   863             if (tree != null) {
   864                 validator.env = env;
   865                 tree.accept(validator);
   866                 checkRaw(tree, env);
   867             }
   868         } catch (CompletionFailure ex) {
   869             completionError(tree.pos(), ex);
   870         }
   871     }
   872     //where
   873     void checkRaw(JCTree tree, Env<AttrContext> env) {
   874         if (lint.isEnabled(Lint.LintCategory.RAW) &&
   875             tree.type.tag == CLASS &&
   876             !env.enclClass.name.isEmpty() &&  //anonymous or intersection
   877             tree.type.isRaw()) {
   878             log.warning(tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
   879         }
   880     }
   882     /** Visitor method: Validate a list of type expressions.
   883      */
   884     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
   885         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   886             validate(l.head, env);
   887     }
   889     /** A visitor class for type validation.
   890      */
   891     class Validator extends JCTree.Visitor {
   893         @Override
   894         public void visitTypeArray(JCArrayTypeTree tree) {
   895             validate(tree.elemtype, env);
   896         }
   898         @Override
   899         public void visitTypeApply(JCTypeApply tree) {
   900             if (tree.type.tag == CLASS) {
   901                 List<Type> formals = tree.type.tsym.type.allparams();
   902                 List<Type> actuals = tree.type.allparams();
   903                 List<JCExpression> args = tree.arguments;
   904                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
   905                 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>();
   907                 // For matching pairs of actual argument types `a' and
   908                 // formal type parameters with declared bound `b' ...
   909                 while (args.nonEmpty() && forms.nonEmpty()) {
   910                     validate(args.head, env);
   912                     // exact type arguments needs to know their
   913                     // bounds (for upper and lower bound
   914                     // calculations).  So we create new TypeVars with
   915                     // bounds substed with actuals.
   916                     tvars_buf.append(types.substBound(((TypeVar)forms.head),
   917                                                       formals,
   918                                                       actuals));
   920                     args = args.tail;
   921                     forms = forms.tail;
   922                 }
   924                 args = tree.arguments;
   925                 List<Type> tvars_cap = types.substBounds(formals,
   926                                           formals,
   927                                           types.capture(tree.type).allparams());
   928                 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   929                     // Let the actual arguments know their bound
   930                     args.head.type.withTypeVar((TypeVar)tvars_cap.head);
   931                     args = args.tail;
   932                     tvars_cap = tvars_cap.tail;
   933                 }
   935                 args = tree.arguments;
   936                 List<TypeVar> tvars = tvars_buf.toList();
   938                 while (args.nonEmpty() && tvars.nonEmpty()) {
   939                     checkExtends(args.head.pos(),
   940                                  args.head.type,
   941                                  tvars.head);
   942                     args = args.tail;
   943                     tvars = tvars.tail;
   944                 }
   946                 checkCapture(tree);
   948                 // Check that this type is either fully parameterized, or
   949                 // not parameterized at all.
   950                 if (tree.type.getEnclosingType().isRaw())
   951                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
   952                 if (tree.clazz.getTag() == JCTree.SELECT)
   953                     visitSelectInternal((JCFieldAccess)tree.clazz);
   954             }
   955         }
   957         @Override
   958         public void visitTypeParameter(JCTypeParameter tree) {
   959             validate(tree.bounds, env);
   960             checkClassBounds(tree.pos(), tree.type);
   961         }
   963         @Override
   964         public void visitWildcard(JCWildcard tree) {
   965             if (tree.inner != null)
   966                 validate(tree.inner, env);
   967         }
   969         @Override
   970         public void visitSelect(JCFieldAccess tree) {
   971             if (tree.type.tag == CLASS) {
   972                 visitSelectInternal(tree);
   974                 // Check that this type is either fully parameterized, or
   975                 // not parameterized at all.
   976                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
   977                     log.error(tree.pos(), "improperly.formed.type.param.missing");
   978             }
   979         }
   980         public void visitSelectInternal(JCFieldAccess tree) {
   981             if (tree.type.tsym.isStatic() &&
   982                 tree.selected.type.isParameterized()) {
   983                 // The enclosing type is not a class, so we are
   984                 // looking at a static member type.  However, the
   985                 // qualifying expression is parameterized.
   986                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
   987             } else {
   988                 // otherwise validate the rest of the expression
   989                 tree.selected.accept(this);
   990             }
   991         }
   993         @Override
   994         public void visitAnnotatedType(JCAnnotatedType tree) {
   995             tree.underlyingType.accept(this);
   996         }
   998         /** Default visitor method: do nothing.
   999          */
  1000         @Override
  1001         public void visitTree(JCTree tree) {
  1004         Env<AttrContext> env;
  1007 /* *************************************************************************
  1008  * Exception checking
  1009  **************************************************************************/
  1011     /* The following methods treat classes as sets that contain
  1012      * the class itself and all their subclasses
  1013      */
  1015     /** Is given type a subtype of some of the types in given list?
  1016      */
  1017     boolean subset(Type t, List<Type> ts) {
  1018         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1019             if (types.isSubtype(t, l.head)) return true;
  1020         return false;
  1023     /** Is given type a subtype or supertype of
  1024      *  some of the types in given list?
  1025      */
  1026     boolean intersects(Type t, List<Type> ts) {
  1027         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1028             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1029         return false;
  1032     /** Add type set to given type list, unless it is a subclass of some class
  1033      *  in the list.
  1034      */
  1035     List<Type> incl(Type t, List<Type> ts) {
  1036         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1039     /** Remove type set from type set list.
  1040      */
  1041     List<Type> excl(Type t, List<Type> ts) {
  1042         if (ts.isEmpty()) {
  1043             return ts;
  1044         } else {
  1045             List<Type> ts1 = excl(t, ts.tail);
  1046             if (types.isSubtype(ts.head, t)) return ts1;
  1047             else if (ts1 == ts.tail) return ts;
  1048             else return ts1.prepend(ts.head);
  1052     /** Form the union of two type set lists.
  1053      */
  1054     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1055         List<Type> ts = ts1;
  1056         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1057             ts = incl(l.head, ts);
  1058         return ts;
  1061     /** Form the difference of two type lists.
  1062      */
  1063     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1064         List<Type> ts = ts1;
  1065         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1066             ts = excl(l.head, ts);
  1067         return ts;
  1070     /** Form the intersection of two type lists.
  1071      */
  1072     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1073         List<Type> ts = List.nil();
  1074         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1075             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1076         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1077             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1078         return ts;
  1081     /** Is exc an exception symbol that need not be declared?
  1082      */
  1083     boolean isUnchecked(ClassSymbol exc) {
  1084         return
  1085             exc.kind == ERR ||
  1086             exc.isSubClass(syms.errorType.tsym, types) ||
  1087             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1090     /** Is exc an exception type that need not be declared?
  1091      */
  1092     boolean isUnchecked(Type exc) {
  1093         return
  1094             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1095             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1096             exc.tag == BOT;
  1099     /** Same, but handling completion failures.
  1100      */
  1101     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1102         try {
  1103             return isUnchecked(exc);
  1104         } catch (CompletionFailure ex) {
  1105             completionError(pos, ex);
  1106             return true;
  1110     /** Is exc handled by given exception list?
  1111      */
  1112     boolean isHandled(Type exc, List<Type> handled) {
  1113         return isUnchecked(exc) || subset(exc, handled);
  1116     /** Return all exceptions in thrown list that are not in handled list.
  1117      *  @param thrown     The list of thrown exceptions.
  1118      *  @param handled    The list of handled exceptions.
  1119      */
  1120     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1121         List<Type> unhandled = List.nil();
  1122         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1123             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1124         return unhandled;
  1127 /* *************************************************************************
  1128  * Overriding/Implementation checking
  1129  **************************************************************************/
  1131     /** The level of access protection given by a flag set,
  1132      *  where PRIVATE is highest and PUBLIC is lowest.
  1133      */
  1134     static int protection(long flags) {
  1135         switch ((short)(flags & AccessFlags)) {
  1136         case PRIVATE: return 3;
  1137         case PROTECTED: return 1;
  1138         default:
  1139         case PUBLIC: return 0;
  1140         case 0: return 2;
  1144     /** A customized "cannot override" error message.
  1145      *  @param m      The overriding method.
  1146      *  @param other  The overridden method.
  1147      *  @return       An internationalized string.
  1148      */
  1149     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1150         String key;
  1151         if ((other.owner.flags() & INTERFACE) == 0)
  1152             key = "cant.override";
  1153         else if ((m.owner.flags() & INTERFACE) == 0)
  1154             key = "cant.implement";
  1155         else
  1156             key = "clashes.with";
  1157         return diags.fragment(key, m, m.location(), other, other.location());
  1160     /** A customized "override" warning message.
  1161      *  @param m      The overriding method.
  1162      *  @param other  The overridden method.
  1163      *  @return       An internationalized string.
  1164      */
  1165     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1166         String key;
  1167         if ((other.owner.flags() & INTERFACE) == 0)
  1168             key = "unchecked.override";
  1169         else if ((m.owner.flags() & INTERFACE) == 0)
  1170             key = "unchecked.implement";
  1171         else
  1172             key = "unchecked.clash.with";
  1173         return diags.fragment(key, m, m.location(), other, other.location());
  1176     /** A customized "override" warning message.
  1177      *  @param m      The overriding method.
  1178      *  @param other  The overridden method.
  1179      *  @return       An internationalized string.
  1180      */
  1181     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1182         String key;
  1183         if ((other.owner.flags() & INTERFACE) == 0)
  1184             key = "varargs.override";
  1185         else  if ((m.owner.flags() & INTERFACE) == 0)
  1186             key = "varargs.implement";
  1187         else
  1188             key = "varargs.clash.with";
  1189         return diags.fragment(key, m, m.location(), other, other.location());
  1192     /** Check that this method conforms with overridden method 'other'.
  1193      *  where `origin' is the class where checking started.
  1194      *  Complications:
  1195      *  (1) Do not check overriding of synthetic methods
  1196      *      (reason: they might be final).
  1197      *      todo: check whether this is still necessary.
  1198      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1199      *      than the method it implements. Augment the proxy methods with the
  1200      *      undeclared exceptions in this case.
  1201      *  (3) When generics are enabled, admit the case where an interface proxy
  1202      *      has a result type
  1203      *      extended by the result type of the method it implements.
  1204      *      Change the proxies result type to the smaller type in this case.
  1206      *  @param tree         The tree from which positions
  1207      *                      are extracted for errors.
  1208      *  @param m            The overriding method.
  1209      *  @param other        The overridden method.
  1210      *  @param origin       The class of which the overriding method
  1211      *                      is a member.
  1212      */
  1213     void checkOverride(JCTree tree,
  1214                        MethodSymbol m,
  1215                        MethodSymbol other,
  1216                        ClassSymbol origin) {
  1217         // Don't check overriding of synthetic methods or by bridge methods.
  1218         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1219             return;
  1222         // Error if static method overrides instance method (JLS 8.4.6.2).
  1223         if ((m.flags() & STATIC) != 0 &&
  1224                    (other.flags() & STATIC) == 0) {
  1225             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1226                       cannotOverride(m, other));
  1227             return;
  1230         // Error if instance method overrides static or final
  1231         // method (JLS 8.4.6.1).
  1232         if ((other.flags() & FINAL) != 0 ||
  1233                  (m.flags() & STATIC) == 0 &&
  1234                  (other.flags() & STATIC) != 0) {
  1235             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1236                       cannotOverride(m, other),
  1237                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1238             return;
  1241         if ((m.owner.flags() & ANNOTATION) != 0) {
  1242             // handled in validateAnnotationMethod
  1243             return;
  1246         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1247         if ((origin.flags() & INTERFACE) == 0 &&
  1248                  protection(m.flags()) > protection(other.flags())) {
  1249             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1250                       cannotOverride(m, other),
  1251                       other.flags() == 0 ?
  1252                           Flag.PACKAGE :
  1253                           asFlagSet(other.flags() & AccessFlags));
  1254             return;
  1257         Type mt = types.memberType(origin.type, m);
  1258         Type ot = types.memberType(origin.type, other);
  1259         // Error if overriding result type is different
  1260         // (or, in the case of generics mode, not a subtype) of
  1261         // overridden result type. We have to rename any type parameters
  1262         // before comparing types.
  1263         List<Type> mtvars = mt.getTypeArguments();
  1264         List<Type> otvars = ot.getTypeArguments();
  1265         Type mtres = mt.getReturnType();
  1266         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1268         overrideWarner.warned = false;
  1269         boolean resultTypesOK =
  1270             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1271         if (!resultTypesOK) {
  1272             if (!allowCovariantReturns &&
  1273                 m.owner != origin &&
  1274                 m.owner.isSubClass(other.owner, types)) {
  1275                 // allow limited interoperability with covariant returns
  1276             } else {
  1277                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1278                           "override.incompatible.ret",
  1279                           cannotOverride(m, other),
  1280                           mtres, otres);
  1281                 return;
  1283         } else if (overrideWarner.warned) {
  1284             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1285                     "override.unchecked.ret",
  1286                     uncheckedOverrides(m, other),
  1287                     mtres, otres);
  1290         // Error if overriding method throws an exception not reported
  1291         // by overridden method.
  1292         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1293         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1294         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1295         if (unhandledErased.nonEmpty()) {
  1296             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1297                       "override.meth.doesnt.throw",
  1298                       cannotOverride(m, other),
  1299                       unhandledUnerased.head);
  1300             return;
  1302         else if (unhandledUnerased.nonEmpty()) {
  1303             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1304                           "override.unchecked.thrown",
  1305                          cannotOverride(m, other),
  1306                          unhandledUnerased.head);
  1307             return;
  1310         // Optional warning if varargs don't agree
  1311         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1312             && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
  1313             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1314                         ((m.flags() & Flags.VARARGS) != 0)
  1315                         ? "override.varargs.missing"
  1316                         : "override.varargs.extra",
  1317                         varargsOverrides(m, other));
  1320         // Warn if instance method overrides bridge method (compiler spec ??)
  1321         if ((other.flags() & BRIDGE) != 0) {
  1322             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1323                         uncheckedOverrides(m, other));
  1326         // Warn if a deprecated method overridden by a non-deprecated one.
  1327         if ((other.flags() & DEPRECATED) != 0
  1328             && (m.flags() & DEPRECATED) == 0
  1329             && m.outermostClass() != other.outermostClass()
  1330             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1331             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1334     // where
  1335         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1336             // If the method, m, is defined in an interface, then ignore the issue if the method
  1337             // is only inherited via a supertype and also implemented in the supertype,
  1338             // because in that case, we will rediscover the issue when examining the method
  1339             // in the supertype.
  1340             // If the method, m, is not defined in an interface, then the only time we need to
  1341             // address the issue is when the method is the supertype implemementation: any other
  1342             // case, we will have dealt with when examining the supertype classes
  1343             ClassSymbol mc = m.enclClass();
  1344             Type st = types.supertype(origin.type);
  1345             if (st.tag != CLASS)
  1346                 return true;
  1347             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1349             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1350                 List<Type> intfs = types.interfaces(origin.type);
  1351                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1353             else
  1354                 return (stimpl != m);
  1358     // used to check if there were any unchecked conversions
  1359     Warner overrideWarner = new Warner();
  1361     /** Check that a class does not inherit two concrete methods
  1362      *  with the same signature.
  1363      *  @param pos          Position to be used for error reporting.
  1364      *  @param site         The class type to be checked.
  1365      */
  1366     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1367         Type sup = types.supertype(site);
  1368         if (sup.tag != CLASS) return;
  1370         for (Type t1 = sup;
  1371              t1.tsym.type.isParameterized();
  1372              t1 = types.supertype(t1)) {
  1373             for (Scope.Entry e1 = t1.tsym.members().elems;
  1374                  e1 != null;
  1375                  e1 = e1.sibling) {
  1376                 Symbol s1 = e1.sym;
  1377                 if (s1.kind != MTH ||
  1378                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1379                     !s1.isInheritedIn(site.tsym, types) ||
  1380                     ((MethodSymbol)s1).implementation(site.tsym,
  1381                                                       types,
  1382                                                       true) != s1)
  1383                     continue;
  1384                 Type st1 = types.memberType(t1, s1);
  1385                 int s1ArgsLength = st1.getParameterTypes().length();
  1386                 if (st1 == s1.type) continue;
  1388                 for (Type t2 = sup;
  1389                      t2.tag == CLASS;
  1390                      t2 = types.supertype(t2)) {
  1391                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1392                          e2.scope != null;
  1393                          e2 = e2.next()) {
  1394                         Symbol s2 = e2.sym;
  1395                         if (s2 == s1 ||
  1396                             s2.kind != MTH ||
  1397                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1398                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1399                             !s2.isInheritedIn(site.tsym, types) ||
  1400                             ((MethodSymbol)s2).implementation(site.tsym,
  1401                                                               types,
  1402                                                               true) != s2)
  1403                             continue;
  1404                         Type st2 = types.memberType(t2, s2);
  1405                         if (types.overrideEquivalent(st1, st2))
  1406                             log.error(pos, "concrete.inheritance.conflict",
  1407                                       s1, t1, s2, t2, sup);
  1414     /** Check that classes (or interfaces) do not each define an abstract
  1415      *  method with same name and arguments but incompatible return types.
  1416      *  @param pos          Position to be used for error reporting.
  1417      *  @param t1           The first argument type.
  1418      *  @param t2           The second argument type.
  1419      */
  1420     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1421                                             Type t1,
  1422                                             Type t2) {
  1423         return checkCompatibleAbstracts(pos, t1, t2,
  1424                                         types.makeCompoundType(t1, t2));
  1427     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1428                                             Type t1,
  1429                                             Type t2,
  1430                                             Type site) {
  1431         Symbol sym = firstIncompatibility(t1, t2, site);
  1432         if (sym != null) {
  1433             log.error(pos, "types.incompatible.diff.ret",
  1434                       t1, t2, sym.name +
  1435                       "(" + types.memberType(t2, sym).getParameterTypes() + ")");
  1436             return false;
  1438         return true;
  1441     /** Return the first method which is defined with same args
  1442      *  but different return types in two given interfaces, or null if none
  1443      *  exists.
  1444      *  @param t1     The first type.
  1445      *  @param t2     The second type.
  1446      *  @param site   The most derived type.
  1447      *  @returns symbol from t2 that conflicts with one in t1.
  1448      */
  1449     private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
  1450         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1451         closure(t1, interfaces1);
  1452         Map<TypeSymbol,Type> interfaces2;
  1453         if (t1 == t2)
  1454             interfaces2 = interfaces1;
  1455         else
  1456             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1458         for (Type t3 : interfaces1.values()) {
  1459             for (Type t4 : interfaces2.values()) {
  1460                 Symbol s = firstDirectIncompatibility(t3, t4, site);
  1461                 if (s != null) return s;
  1464         return null;
  1467     /** Compute all the supertypes of t, indexed by type symbol. */
  1468     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1469         if (t.tag != CLASS) return;
  1470         if (typeMap.put(t.tsym, t) == null) {
  1471             closure(types.supertype(t), typeMap);
  1472             for (Type i : types.interfaces(t))
  1473                 closure(i, typeMap);
  1477     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1478     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1479         if (t.tag != CLASS) return;
  1480         if (typesSkip.get(t.tsym) != null) return;
  1481         if (typeMap.put(t.tsym, t) == null) {
  1482             closure(types.supertype(t), typesSkip, typeMap);
  1483             for (Type i : types.interfaces(t))
  1484                 closure(i, typesSkip, typeMap);
  1488     /** Return the first method in t2 that conflicts with a method from t1. */
  1489     private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
  1490         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1491             Symbol s1 = e1.sym;
  1492             Type st1 = null;
  1493             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1494             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1495             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1496             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1497                 Symbol s2 = e2.sym;
  1498                 if (s1 == s2) continue;
  1499                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1500                 if (st1 == null) st1 = types.memberType(t1, s1);
  1501                 Type st2 = types.memberType(t2, s2);
  1502                 if (types.overrideEquivalent(st1, st2)) {
  1503                     List<Type> tvars1 = st1.getTypeArguments();
  1504                     List<Type> tvars2 = st2.getTypeArguments();
  1505                     Type rt1 = st1.getReturnType();
  1506                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1507                     boolean compat =
  1508                         types.isSameType(rt1, rt2) ||
  1509                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1510                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1511                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1512                          checkCommonOverriderIn(s1,s2,site);
  1513                     if (!compat) return s2;
  1517         return null;
  1519     //WHERE
  1520     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1521         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1522         Type st1 = types.memberType(site, s1);
  1523         Type st2 = types.memberType(site, s2);
  1524         closure(site, supertypes);
  1525         for (Type t : supertypes.values()) {
  1526             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1527                 Symbol s3 = e.sym;
  1528                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1529                 Type st3 = types.memberType(site,s3);
  1530                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1531                     if (s3.owner == site.tsym) {
  1532                         return true;
  1534                     List<Type> tvars1 = st1.getTypeArguments();
  1535                     List<Type> tvars2 = st2.getTypeArguments();
  1536                     List<Type> tvars3 = st3.getTypeArguments();
  1537                     Type rt1 = st1.getReturnType();
  1538                     Type rt2 = st2.getReturnType();
  1539                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1540                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1541                     boolean compat =
  1542                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1543                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1544                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1545                     if (compat)
  1546                         return true;
  1550         return false;
  1553     /** Check that a given method conforms with any method it overrides.
  1554      *  @param tree         The tree from which positions are extracted
  1555      *                      for errors.
  1556      *  @param m            The overriding method.
  1557      */
  1558     void checkOverride(JCTree tree, MethodSymbol m) {
  1559         ClassSymbol origin = (ClassSymbol)m.owner;
  1560         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1561             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1562                 log.error(tree.pos(), "enum.no.finalize");
  1563                 return;
  1565         for (Type t = types.supertype(origin.type); t.tag == CLASS;
  1566              t = types.supertype(t)) {
  1567             TypeSymbol c = t.tsym;
  1568             Scope.Entry e = c.members().lookup(m.name);
  1569             while (e.scope != null) {
  1570                 if (m.overrides(e.sym, origin, types, false))
  1571                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1572                 else if (e.sym.kind == MTH &&
  1573                         e.sym.isInheritedIn(origin, types) &&
  1574                         (e.sym.flags() & SYNTHETIC) == 0 &&
  1575                         !m.isConstructor()) {
  1576                     Type er1 = m.erasure(types);
  1577                     Type er2 = e.sym.erasure(types);
  1578                     if (types.isSameTypes(er1.getParameterTypes(),
  1579                             er2.getParameterTypes())) {
  1580                             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1581                                     "name.clash.same.erasure.no.override",
  1582                                     m, m.location(),
  1583                                     e.sym, e.sym.location());
  1586                 e = e.next();
  1591     /** Check that all abstract members of given class have definitions.
  1592      *  @param pos          Position to be used for error reporting.
  1593      *  @param c            The class.
  1594      */
  1595     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1596         try {
  1597             MethodSymbol undef = firstUndef(c, c);
  1598             if (undef != null) {
  1599                 if ((c.flags() & ENUM) != 0 &&
  1600                     types.supertype(c.type).tsym == syms.enumSym &&
  1601                     (c.flags() & FINAL) == 0) {
  1602                     // add the ABSTRACT flag to an enum
  1603                     c.flags_field |= ABSTRACT;
  1604                 } else {
  1605                     MethodSymbol undef1 =
  1606                         new MethodSymbol(undef.flags(), undef.name,
  1607                                          types.memberType(c.type, undef), undef.owner);
  1608                     log.error(pos, "does.not.override.abstract",
  1609                               c, undef1, undef1.location());
  1612         } catch (CompletionFailure ex) {
  1613             completionError(pos, ex);
  1616 //where
  1617         /** Return first abstract member of class `c' that is not defined
  1618          *  in `impl', null if there is none.
  1619          */
  1620         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1621             MethodSymbol undef = null;
  1622             // Do not bother to search in classes that are not abstract,
  1623             // since they cannot have abstract members.
  1624             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1625                 Scope s = c.members();
  1626                 for (Scope.Entry e = s.elems;
  1627                      undef == null && e != null;
  1628                      e = e.sibling) {
  1629                     if (e.sym.kind == MTH &&
  1630                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1631                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1632                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1633                         if (implmeth == null || implmeth == absmeth)
  1634                             undef = absmeth;
  1637                 if (undef == null) {
  1638                     Type st = types.supertype(c.type);
  1639                     if (st.tag == CLASS)
  1640                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1642                 for (List<Type> l = types.interfaces(c.type);
  1643                      undef == null && l.nonEmpty();
  1644                      l = l.tail) {
  1645                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1648             return undef;
  1651     /** Check for cyclic references. Issue an error if the
  1652      *  symbol of the type referred to has a LOCKED flag set.
  1654      *  @param pos      Position to be used for error reporting.
  1655      *  @param t        The type referred to.
  1656      */
  1657     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1658         checkNonCyclicInternal(pos, t);
  1662     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1663         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1666     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1667         final TypeVar tv;
  1668         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1669             return;
  1670         if (seen.contains(t)) {
  1671             tv = (TypeVar)t;
  1672             tv.bound = types.createErrorType(t);
  1673             log.error(pos, "cyclic.inheritance", t);
  1674         } else if (t.tag == TYPEVAR) {
  1675             tv = (TypeVar)t;
  1676             seen = seen.prepend(tv);
  1677             for (Type b : types.getBounds(tv))
  1678                 checkNonCyclic1(pos, b, seen);
  1682     /** Check for cyclic references. Issue an error if the
  1683      *  symbol of the type referred to has a LOCKED flag set.
  1685      *  @param pos      Position to be used for error reporting.
  1686      *  @param t        The type referred to.
  1687      *  @returns        True if the check completed on all attributed classes
  1688      */
  1689     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1690         boolean complete = true; // was the check complete?
  1691         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1692         Symbol c = t.tsym;
  1693         if ((c.flags_field & ACYCLIC) != 0) return true;
  1695         if ((c.flags_field & LOCKED) != 0) {
  1696             noteCyclic(pos, (ClassSymbol)c);
  1697         } else if (!c.type.isErroneous()) {
  1698             try {
  1699                 c.flags_field |= LOCKED;
  1700                 if (c.type.tag == CLASS) {
  1701                     ClassType clazz = (ClassType)c.type;
  1702                     if (clazz.interfaces_field != null)
  1703                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1704                             complete &= checkNonCyclicInternal(pos, l.head);
  1705                     if (clazz.supertype_field != null) {
  1706                         Type st = clazz.supertype_field;
  1707                         if (st != null && st.tag == CLASS)
  1708                             complete &= checkNonCyclicInternal(pos, st);
  1710                     if (c.owner.kind == TYP)
  1711                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1713             } finally {
  1714                 c.flags_field &= ~LOCKED;
  1717         if (complete)
  1718             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1719         if (complete) c.flags_field |= ACYCLIC;
  1720         return complete;
  1723     /** Note that we found an inheritance cycle. */
  1724     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1725         log.error(pos, "cyclic.inheritance", c);
  1726         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1727             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  1728         Type st = types.supertype(c.type);
  1729         if (st.tag == CLASS)
  1730             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  1731         c.type = types.createErrorType(c, c.type);
  1732         c.flags_field |= ACYCLIC;
  1735     /** Check that all methods which implement some
  1736      *  method conform to the method they implement.
  1737      *  @param tree         The class definition whose members are checked.
  1738      */
  1739     void checkImplementations(JCClassDecl tree) {
  1740         checkImplementations(tree, tree.sym);
  1742 //where
  1743         /** Check that all methods which implement some
  1744          *  method in `ic' conform to the method they implement.
  1745          */
  1746         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1747             ClassSymbol origin = tree.sym;
  1748             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1749                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1750                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1751                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  1752                         if (e.sym.kind == MTH &&
  1753                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  1754                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  1755                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  1756                             if (implmeth != null && implmeth != absmeth &&
  1757                                 (implmeth.owner.flags() & INTERFACE) ==
  1758                                 (origin.flags() & INTERFACE)) {
  1759                                 // don't check if implmeth is in a class, yet
  1760                                 // origin is an interface. This case arises only
  1761                                 // if implmeth is declared in Object. The reason is
  1762                                 // that interfaces really don't inherit from
  1763                                 // Object it's just that the compiler represents
  1764                                 // things that way.
  1765                                 checkOverride(tree, implmeth, absmeth, origin);
  1773     /** Check that all abstract methods implemented by a class are
  1774      *  mutually compatible.
  1775      *  @param pos          Position to be used for error reporting.
  1776      *  @param c            The class whose interfaces are checked.
  1777      */
  1778     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  1779         List<Type> supertypes = types.interfaces(c);
  1780         Type supertype = types.supertype(c);
  1781         if (supertype.tag == CLASS &&
  1782             (supertype.tsym.flags() & ABSTRACT) != 0)
  1783             supertypes = supertypes.prepend(supertype);
  1784         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  1785             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  1786                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  1787                 return;
  1788             for (List<Type> m = supertypes; m != l; m = m.tail)
  1789                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  1790                     return;
  1792         checkCompatibleConcretes(pos, c);
  1795     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  1796         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  1797             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  1798                 // VM allows methods and variables with differing types
  1799                 if (sym.kind == e.sym.kind &&
  1800                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  1801                     sym != e.sym &&
  1802                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  1803                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  1804                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  1805                     return;
  1811     /** Report a conflict between a user symbol and a synthetic symbol.
  1812      */
  1813     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  1814         if (!sym.type.isErroneous()) {
  1815             if (warnOnSyntheticConflicts) {
  1816                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  1818             else {
  1819                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  1824     /** Check that class c does not implement directly or indirectly
  1825      *  the same parameterized interface with two different argument lists.
  1826      *  @param pos          Position to be used for error reporting.
  1827      *  @param type         The type whose interfaces are checked.
  1828      */
  1829     void checkClassBounds(DiagnosticPosition pos, Type type) {
  1830         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  1832 //where
  1833         /** Enter all interfaces of type `type' into the hash table `seensofar'
  1834          *  with their class symbol as key and their type as value. Make
  1835          *  sure no class is entered with two different types.
  1836          */
  1837         void checkClassBounds(DiagnosticPosition pos,
  1838                               Map<TypeSymbol,Type> seensofar,
  1839                               Type type) {
  1840             if (type.isErroneous()) return;
  1841             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  1842                 Type it = l.head;
  1843                 Type oldit = seensofar.put(it.tsym, it);
  1844                 if (oldit != null) {
  1845                     List<Type> oldparams = oldit.allparams();
  1846                     List<Type> newparams = it.allparams();
  1847                     if (!types.containsTypeEquivalent(oldparams, newparams))
  1848                         log.error(pos, "cant.inherit.diff.arg",
  1849                                   it.tsym, Type.toString(oldparams),
  1850                                   Type.toString(newparams));
  1852                 checkClassBounds(pos, seensofar, it);
  1854             Type st = types.supertype(type);
  1855             if (st != null) checkClassBounds(pos, seensofar, st);
  1858     /** Enter interface into into set.
  1859      *  If it existed already, issue a "repeated interface" error.
  1860      */
  1861     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  1862         if (its.contains(it))
  1863             log.error(pos, "repeated.interface");
  1864         else {
  1865             its.add(it);
  1869 /* *************************************************************************
  1870  * Check annotations
  1871  **************************************************************************/
  1873     /** Annotation types are restricted to primitives, String, an
  1874      *  enum, an annotation, Class, Class<?>, Class<? extends
  1875      *  Anything>, arrays of the preceding.
  1876      */
  1877     void validateAnnotationType(JCTree restype) {
  1878         // restype may be null if an error occurred, so don't bother validating it
  1879         if (restype != null) {
  1880             validateAnnotationType(restype.pos(), restype.type);
  1884     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  1885         if (type.isPrimitive()) return;
  1886         if (types.isSameType(type, syms.stringType)) return;
  1887         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  1888         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  1889         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  1890         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  1891             validateAnnotationType(pos, types.elemtype(type));
  1892             return;
  1894         log.error(pos, "invalid.annotation.member.type");
  1897     /**
  1898      * "It is also a compile-time error if any method declared in an
  1899      * annotation type has a signature that is override-equivalent to
  1900      * that of any public or protected method declared in class Object
  1901      * or in the interface annotation.Annotation."
  1903      * @jls3 9.6 Annotation Types
  1904      */
  1905     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  1906         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  1907             Scope s = sup.tsym.members();
  1908             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  1909                 if (e.sym.kind == MTH &&
  1910                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  1911                     types.overrideEquivalent(m.type, e.sym.type))
  1912                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  1917     /** Check the annotations of a symbol.
  1918      */
  1919     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  1920         if (skipAnnotations) return;
  1921         for (JCAnnotation a : annotations)
  1922             validateAnnotation(a, s);
  1925     /** Check the type annotations
  1926      */
  1927     public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
  1928         if (skipAnnotations) return;
  1929         for (JCTypeAnnotation a : annotations)
  1930             validateTypeAnnotation(a, isTypeParameter);
  1933     /** Check an annotation of a symbol.
  1934      */
  1935     public void validateAnnotation(JCAnnotation a, Symbol s) {
  1936         validateAnnotation(a);
  1938         if (!annotationApplicable(a, s))
  1939             log.error(a.pos(), "annotation.type.not.applicable");
  1941         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1942             if (!isOverrider(s))
  1943                 log.error(a.pos(), "method.does.not.override.superclass");
  1947     public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
  1948         if (a.type == null)
  1949             throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
  1950         validateAnnotation(a);
  1952         if (!isTypeAnnotation(a, isTypeParameter))
  1953             log.error(a.pos(), "annotation.type.not.applicable");
  1956     /** Is s a method symbol that overrides a method in a superclass? */
  1957     boolean isOverrider(Symbol s) {
  1958         if (s.kind != MTH || s.isStatic())
  1959             return false;
  1960         MethodSymbol m = (MethodSymbol)s;
  1961         TypeSymbol owner = (TypeSymbol)m.owner;
  1962         for (Type sup : types.closure(owner.type)) {
  1963             if (sup == owner.type)
  1964                 continue; // skip "this"
  1965             Scope scope = sup.tsym.members();
  1966             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  1967                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  1968                     return true;
  1971         return false;
  1974     /** Is the annotation applicable to type annotations */
  1975     boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
  1976         Attribute.Compound atTarget =
  1977             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1978         if (atTarget == null) return true;
  1979         Attribute atValue = atTarget.member(names.value);
  1980         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1981         Attribute.Array arr = (Attribute.Array) atValue;
  1982         for (Attribute app : arr.values) {
  1983             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1984             Attribute.Enum e = (Attribute.Enum) app;
  1985             if (!isTypeParameter && e.value.name == names.TYPE_USE)
  1986                 return true;
  1987             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  1988                 return true;
  1990         return false;
  1993     /** Is the annotation applicable to the symbol? */
  1994     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  1995         Attribute.Compound atTarget =
  1996             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1997         if (atTarget == null) return true;
  1998         Attribute atValue = atTarget.member(names.value);
  1999         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2000         Attribute.Array arr = (Attribute.Array) atValue;
  2001         for (Attribute app : arr.values) {
  2002             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2003             Attribute.Enum e = (Attribute.Enum) app;
  2004             if (e.value.name == names.TYPE)
  2005                 { if (s.kind == TYP) return true; }
  2006             else if (e.value.name == names.FIELD)
  2007                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2008             else if (e.value.name == names.METHOD)
  2009                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2010             else if (e.value.name == names.PARAMETER)
  2011                 { if (s.kind == VAR &&
  2012                       s.owner.kind == MTH &&
  2013                       (s.flags() & PARAMETER) != 0)
  2014                     return true;
  2016             else if (e.value.name == names.CONSTRUCTOR)
  2017                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2018             else if (e.value.name == names.LOCAL_VARIABLE)
  2019                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2020                       (s.flags() & PARAMETER) == 0)
  2021                     return true;
  2023             else if (e.value.name == names.ANNOTATION_TYPE)
  2024                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2025                     return true;
  2027             else if (e.value.name == names.PACKAGE)
  2028                 { if (s.kind == PCK) return true; }
  2029             else if (e.value.name == names.TYPE_USE)
  2030                 { if (s.kind == TYP ||
  2031                       s.kind == VAR ||
  2032                       (s.kind == MTH && !s.isConstructor() &&
  2033                        s.type.getReturnType().tag != VOID))
  2034                     return true;
  2036             else
  2037                 return true; // recovery
  2039         return false;
  2042     /** Check an annotation value.
  2043      */
  2044     public void validateAnnotation(JCAnnotation a) {
  2045         if (a.type.isErroneous()) return;
  2047         // collect an inventory of the members
  2048         Set<MethodSymbol> members = new HashSet<MethodSymbol>();
  2049         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2050              e != null;
  2051              e = e.sibling)
  2052             if (e.sym.kind == MTH)
  2053                 members.add((MethodSymbol) e.sym);
  2055         // count them off as they're annotated
  2056         for (JCTree arg : a.args) {
  2057             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  2058             JCAssign assign = (JCAssign) arg;
  2059             Symbol m = TreeInfo.symbol(assign.lhs);
  2060             if (m == null || m.type.isErroneous()) continue;
  2061             if (!members.remove(m))
  2062                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2063                           m.name, a.type);
  2064             if (assign.rhs.getTag() == ANNOTATION)
  2065                 validateAnnotation((JCAnnotation)assign.rhs);
  2068         // all the remaining ones better have default values
  2069         for (MethodSymbol m : members)
  2070             if (m.defaultValue == null && !m.type.isErroneous())
  2071                 log.error(a.pos(), "annotation.missing.default.value",
  2072                           a.type, m.name);
  2074         // special case: java.lang.annotation.Target must not have
  2075         // repeated values in its value member
  2076         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2077             a.args.tail == null)
  2078             return;
  2080         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  2081         JCAssign assign = (JCAssign) a.args.head;
  2082         Symbol m = TreeInfo.symbol(assign.lhs);
  2083         if (m.name != names.value) return;
  2084         JCTree rhs = assign.rhs;
  2085         if (rhs.getTag() != JCTree.NEWARRAY) return;
  2086         JCNewArray na = (JCNewArray) rhs;
  2087         Set<Symbol> targets = new HashSet<Symbol>();
  2088         for (JCTree elem : na.elems) {
  2089             if (!targets.add(TreeInfo.symbol(elem))) {
  2090                 log.error(elem.pos(), "repeated.annotation.target");
  2095     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2096         if (allowAnnotations &&
  2097             lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
  2098             (s.flags() & DEPRECATED) != 0 &&
  2099             !syms.deprecatedType.isErroneous() &&
  2100             s.attribute(syms.deprecatedType.tsym) == null) {
  2101             log.warning(pos, "missing.deprecated.annotation");
  2105 /* *************************************************************************
  2106  * Check for recursive annotation elements.
  2107  **************************************************************************/
  2109     /** Check for cycles in the graph of annotation elements.
  2110      */
  2111     void checkNonCyclicElements(JCClassDecl tree) {
  2112         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2113         assert (tree.sym.flags_field & LOCKED) == 0;
  2114         try {
  2115             tree.sym.flags_field |= LOCKED;
  2116             for (JCTree def : tree.defs) {
  2117                 if (def.getTag() != JCTree.METHODDEF) continue;
  2118                 JCMethodDecl meth = (JCMethodDecl)def;
  2119                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2121         } finally {
  2122             tree.sym.flags_field &= ~LOCKED;
  2123             tree.sym.flags_field |= ACYCLIC_ANN;
  2127     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2128         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2129             return;
  2130         if ((tsym.flags_field & LOCKED) != 0) {
  2131             log.error(pos, "cyclic.annotation.element");
  2132             return;
  2134         try {
  2135             tsym.flags_field |= LOCKED;
  2136             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2137                 Symbol s = e.sym;
  2138                 if (s.kind != Kinds.MTH)
  2139                     continue;
  2140                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2142         } finally {
  2143             tsym.flags_field &= ~LOCKED;
  2144             tsym.flags_field |= ACYCLIC_ANN;
  2148     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2149         switch (type.tag) {
  2150         case TypeTags.CLASS:
  2151             if ((type.tsym.flags() & ANNOTATION) != 0)
  2152                 checkNonCyclicElementsInternal(pos, type.tsym);
  2153             break;
  2154         case TypeTags.ARRAY:
  2155             checkAnnotationResType(pos, types.elemtype(type));
  2156             break;
  2157         default:
  2158             break; // int etc
  2162 /* *************************************************************************
  2163  * Check for cycles in the constructor call graph.
  2164  **************************************************************************/
  2166     /** Check for cycles in the graph of constructors calling other
  2167      *  constructors.
  2168      */
  2169     void checkCyclicConstructors(JCClassDecl tree) {
  2170         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2172         // enter each constructor this-call into the map
  2173         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2174             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2175             if (app == null) continue;
  2176             JCMethodDecl meth = (JCMethodDecl) l.head;
  2177             if (TreeInfo.name(app.meth) == names._this) {
  2178                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2179             } else {
  2180                 meth.sym.flags_field |= ACYCLIC;
  2184         // Check for cycles in the map
  2185         Symbol[] ctors = new Symbol[0];
  2186         ctors = callMap.keySet().toArray(ctors);
  2187         for (Symbol caller : ctors) {
  2188             checkCyclicConstructor(tree, caller, callMap);
  2192     /** Look in the map to see if the given constructor is part of a
  2193      *  call cycle.
  2194      */
  2195     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2196                                         Map<Symbol,Symbol> callMap) {
  2197         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2198             if ((ctor.flags_field & LOCKED) != 0) {
  2199                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2200                           "recursive.ctor.invocation");
  2201             } else {
  2202                 ctor.flags_field |= LOCKED;
  2203                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2204                 ctor.flags_field &= ~LOCKED;
  2206             ctor.flags_field |= ACYCLIC;
  2210 /* *************************************************************************
  2211  * Miscellaneous
  2212  **************************************************************************/
  2214     /**
  2215      * Return the opcode of the operator but emit an error if it is an
  2216      * error.
  2217      * @param pos        position for error reporting.
  2218      * @param operator   an operator
  2219      * @param tag        a tree tag
  2220      * @param left       type of left hand side
  2221      * @param right      type of right hand side
  2222      */
  2223     int checkOperator(DiagnosticPosition pos,
  2224                        OperatorSymbol operator,
  2225                        int tag,
  2226                        Type left,
  2227                        Type right) {
  2228         if (operator.opcode == ByteCodes.error) {
  2229             log.error(pos,
  2230                       "operator.cant.be.applied",
  2231                       treeinfo.operatorName(tag),
  2232                       List.of(left, right));
  2234         return operator.opcode;
  2238     /**
  2239      *  Check for division by integer constant zero
  2240      *  @param pos           Position for error reporting.
  2241      *  @param operator      The operator for the expression
  2242      *  @param operand       The right hand operand for the expression
  2243      */
  2244     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2245         if (operand.constValue() != null
  2246             && lint.isEnabled(Lint.LintCategory.DIVZERO)
  2247             && operand.tag <= LONG
  2248             && ((Number) (operand.constValue())).longValue() == 0) {
  2249             int opc = ((OperatorSymbol)operator).opcode;
  2250             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2251                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2252                 log.warning(pos, "div.zero");
  2257     /**
  2258      * Check for empty statements after if
  2259      */
  2260     void checkEmptyIf(JCIf tree) {
  2261         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
  2262             log.warning(tree.thenpart.pos(), "empty.if");
  2265     /** Check that symbol is unique in given scope.
  2266      *  @param pos           Position for error reporting.
  2267      *  @param sym           The symbol.
  2268      *  @param s             The scope.
  2269      */
  2270     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2271         if (sym.type.isErroneous())
  2272             return true;
  2273         if (sym.owner.name == names.any) return false;
  2274         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2275             if (sym != e.sym &&
  2276                 sym.kind == e.sym.kind &&
  2277                 sym.name != names.error &&
  2278                 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2279                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2280                     varargsDuplicateError(pos, sym, e.sym);
  2281                 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
  2282                     duplicateErasureError(pos, sym, e.sym);
  2283                 else
  2284                     duplicateError(pos, e.sym);
  2285                 return false;
  2288         return true;
  2290     //where
  2291     /** Report duplicate declaration error.
  2292      */
  2293     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2294         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2295             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2299     /** Check that single-type import is not already imported or top-level defined,
  2300      *  but make an exception for two single-type imports which denote the same type.
  2301      *  @param pos           Position for error reporting.
  2302      *  @param sym           The symbol.
  2303      *  @param s             The scope
  2304      */
  2305     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2306         return checkUniqueImport(pos, sym, s, false);
  2309     /** Check that static single-type import is not already imported or top-level defined,
  2310      *  but make an exception for two single-type imports which denote the same type.
  2311      *  @param pos           Position for error reporting.
  2312      *  @param sym           The symbol.
  2313      *  @param s             The scope
  2314      *  @param staticImport  Whether or not this was a static import
  2315      */
  2316     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2317         return checkUniqueImport(pos, sym, s, true);
  2320     /** Check that single-type import is not already imported or top-level defined,
  2321      *  but make an exception for two single-type imports which denote the same type.
  2322      *  @param pos           Position for error reporting.
  2323      *  @param sym           The symbol.
  2324      *  @param s             The scope.
  2325      *  @param staticImport  Whether or not this was a static import
  2326      */
  2327     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2328         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2329             // is encountered class entered via a class declaration?
  2330             boolean isClassDecl = e.scope == s;
  2331             if ((isClassDecl || sym != e.sym) &&
  2332                 sym.kind == e.sym.kind &&
  2333                 sym.name != names.error) {
  2334                 if (!e.sym.type.isErroneous()) {
  2335                     String what = e.sym.toString();
  2336                     if (!isClassDecl) {
  2337                         if (staticImport)
  2338                             log.error(pos, "already.defined.static.single.import", what);
  2339                         else
  2340                             log.error(pos, "already.defined.single.import", what);
  2342                     else if (sym != e.sym)
  2343                         log.error(pos, "already.defined.this.unit", what);
  2345                 return false;
  2348         return true;
  2351     /** Check that a qualified name is in canonical form (for import decls).
  2352      */
  2353     public void checkCanonical(JCTree tree) {
  2354         if (!isCanonical(tree))
  2355             log.error(tree.pos(), "import.requires.canonical",
  2356                       TreeInfo.symbol(tree));
  2358         // where
  2359         private boolean isCanonical(JCTree tree) {
  2360             while (tree.getTag() == JCTree.SELECT) {
  2361                 JCFieldAccess s = (JCFieldAccess) tree;
  2362                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2363                     return false;
  2364                 tree = s.selected;
  2366             return true;
  2369     private class ConversionWarner extends Warner {
  2370         final String key;
  2371         final Type found;
  2372         final Type expected;
  2373         public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
  2374             super(pos);
  2375             this.key = key;
  2376             this.found = found;
  2377             this.expected = expected;
  2380         @Override
  2381         public void warnUnchecked() {
  2382             boolean warned = this.warned;
  2383             super.warnUnchecked();
  2384             if (warned) return; // suppress redundant diagnostics
  2385             Object problem = diags.fragment(key);
  2386             Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
  2390     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2391         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2394     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2395         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial