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

Wed, 14 Apr 2010 12:23:29 +0100

author
mcimadamore
date
Wed, 14 Apr 2010 12:23:29 +0100
changeset 536
396b117c1743
parent 505
87eb6edd4f21
child 537
9d9d08922405
permissions
-rw-r--r--

6939618: Revert 'simple' diamond implementation
Summary: backout changeset for 6840638
Reviewed-by: jjg

     1 /*
     2  * Copyright 1999-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    31 import com.sun.tools.javac.code.*;
    32 import com.sun.tools.javac.jvm.*;
    33 import com.sun.tools.javac.tree.*;
    34 import com.sun.tools.javac.util.*;
    35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    36 import com.sun.tools.javac.util.List;
    38 import com.sun.tools.javac.tree.JCTree.*;
    39 import com.sun.tools.javac.code.Lint;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    44 import static com.sun.tools.javac.code.Flags.*;
    45 import static com.sun.tools.javac.code.Kinds.*;
    46 import static com.sun.tools.javac.code.TypeTags.*;
    48 /** Type checking helper class for the attribution phase.
    49  *
    50  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    51  *  you write code that depends on this, you do so at your own risk.
    52  *  This code and its internal interfaces are subject to change or
    53  *  deletion without notice.</b>
    54  */
    55 public class Check {
    56     protected static final Context.Key<Check> checkKey =
    57         new Context.Key<Check>();
    59     private final Names names;
    60     private final Log log;
    61     private final Symtab syms;
    62     private final Infer infer;
    63     private final 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 given modifiers are legal for given symbol and
   644      *  return modifiers together with any implicit modififiers for that symbol.
   645      *  Warning: we can't use flags() here since this method
   646      *  is called during class enter, when flags() would cause a premature
   647      *  completion.
   648      *  @param pos           Position to be used for error reporting.
   649      *  @param flags         The set of modifiers given in a definition.
   650      *  @param sym           The defined symbol.
   651      */
   652     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   653         long mask;
   654         long implicit = 0;
   655         switch (sym.kind) {
   656         case VAR:
   657             if (sym.owner.kind != TYP)
   658                 mask = LocalVarFlags;
   659             else if ((sym.owner.flags_field & INTERFACE) != 0)
   660                 mask = implicit = InterfaceVarFlags;
   661             else
   662                 mask = VarFlags;
   663             break;
   664         case MTH:
   665             if (sym.name == names.init) {
   666                 if ((sym.owner.flags_field & ENUM) != 0) {
   667                     // enum constructors cannot be declared public or
   668                     // protected and must be implicitly or explicitly
   669                     // private
   670                     implicit = PRIVATE;
   671                     mask = PRIVATE;
   672                 } else
   673                     mask = ConstructorFlags;
   674             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   675                 mask = implicit = InterfaceMethodFlags;
   676             else {
   677                 mask = MethodFlags;
   678             }
   679             // Imply STRICTFP if owner has STRICTFP set.
   680             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   681               implicit |= sym.owner.flags_field & STRICTFP;
   682             break;
   683         case TYP:
   684             if (sym.isLocal()) {
   685                 mask = LocalClassFlags;
   686                 if (sym.name.isEmpty()) { // Anonymous class
   687                     // Anonymous classes in static methods are themselves static;
   688                     // that's why we admit STATIC here.
   689                     mask |= STATIC;
   690                     // JLS: Anonymous classes are final.
   691                     implicit |= FINAL;
   692                 }
   693                 if ((sym.owner.flags_field & STATIC) == 0 &&
   694                     (flags & ENUM) != 0)
   695                     log.error(pos, "enums.must.be.static");
   696             } else if (sym.owner.kind == TYP) {
   697                 mask = MemberClassFlags;
   698                 if (sym.owner.owner.kind == PCK ||
   699                     (sym.owner.flags_field & STATIC) != 0)
   700                     mask |= STATIC;
   701                 else if ((flags & ENUM) != 0)
   702                     log.error(pos, "enums.must.be.static");
   703                 // Nested interfaces and enums are always STATIC (Spec ???)
   704                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   705             } else {
   706                 mask = ClassFlags;
   707             }
   708             // Interfaces are always ABSTRACT
   709             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   711             if ((flags & ENUM) != 0) {
   712                 // enums can't be declared abstract or final
   713                 mask &= ~(ABSTRACT | FINAL);
   714                 implicit |= implicitEnumFinalFlag(tree);
   715             }
   716             // Imply STRICTFP if owner has STRICTFP set.
   717             implicit |= sym.owner.flags_field & STRICTFP;
   718             break;
   719         default:
   720             throw new AssertionError();
   721         }
   722         long illegal = flags & StandardFlags & ~mask;
   723         if (illegal != 0) {
   724             if ((illegal & INTERFACE) != 0) {
   725                 log.error(pos, "intf.not.allowed.here");
   726                 mask |= INTERFACE;
   727             }
   728             else {
   729                 log.error(pos,
   730                           "mod.not.allowed.here", asFlagSet(illegal));
   731             }
   732         }
   733         else if ((sym.kind == TYP ||
   734                   // ISSUE: Disallowing abstract&private is no longer appropriate
   735                   // in the presence of inner classes. Should it be deleted here?
   736                   checkDisjoint(pos, flags,
   737                                 ABSTRACT,
   738                                 PRIVATE | STATIC))
   739                  &&
   740                  checkDisjoint(pos, flags,
   741                                ABSTRACT | INTERFACE,
   742                                FINAL | NATIVE | SYNCHRONIZED)
   743                  &&
   744                  checkDisjoint(pos, flags,
   745                                PUBLIC,
   746                                PRIVATE | PROTECTED)
   747                  &&
   748                  checkDisjoint(pos, flags,
   749                                PRIVATE,
   750                                PUBLIC | PROTECTED)
   751                  &&
   752                  checkDisjoint(pos, flags,
   753                                FINAL,
   754                                VOLATILE)
   755                  &&
   756                  (sym.kind == TYP ||
   757                   checkDisjoint(pos, flags,
   758                                 ABSTRACT | NATIVE,
   759                                 STRICTFP))) {
   760             // skip
   761         }
   762         return flags & (mask | ~StandardFlags) | implicit;
   763     }
   766     /** Determine if this enum should be implicitly final.
   767      *
   768      *  If the enum has no specialized enum contants, it is final.
   769      *
   770      *  If the enum does have specialized enum contants, it is
   771      *  <i>not</i> final.
   772      */
   773     private long implicitEnumFinalFlag(JCTree tree) {
   774         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   775         class SpecialTreeVisitor extends JCTree.Visitor {
   776             boolean specialized;
   777             SpecialTreeVisitor() {
   778                 this.specialized = false;
   779             };
   781             @Override
   782             public void visitTree(JCTree tree) { /* no-op */ }
   784             @Override
   785             public void visitVarDef(JCVariableDecl tree) {
   786                 if ((tree.mods.flags & ENUM) != 0) {
   787                     if (tree.init instanceof JCNewClass &&
   788                         ((JCNewClass) tree.init).def != null) {
   789                         specialized = true;
   790                     }
   791                 }
   792             }
   793         }
   795         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   796         JCClassDecl cdef = (JCClassDecl) tree;
   797         for (JCTree defs: cdef.defs) {
   798             defs.accept(sts);
   799             if (sts.specialized) return 0;
   800         }
   801         return FINAL;
   802     }
   804 /* *************************************************************************
   805  * Type Validation
   806  **************************************************************************/
   808     /** Validate a type expression. That is,
   809      *  check that all type arguments of a parametric type are within
   810      *  their bounds. This must be done in a second phase after type attributon
   811      *  since a class might have a subclass as type parameter bound. E.g:
   812      *
   813      *  class B<A extends C> { ... }
   814      *  class C extends B<C> { ... }
   815      *
   816      *  and we can't make sure that the bound is already attributed because
   817      *  of possible cycles.
   818      */
   819     private Validator validator = new Validator();
   821     /** Visitor method: Validate a type expression, if it is not null, catching
   822      *  and reporting any completion failures.
   823      */
   824     void validate(JCTree tree, Env<AttrContext> env) {
   825         try {
   826             if (tree != null) {
   827                 validator.env = env;
   828                 tree.accept(validator);
   829                 checkRaw(tree, env);
   830             }
   831         } catch (CompletionFailure ex) {
   832             completionError(tree.pos(), ex);
   833         }
   834     }
   835     //where
   836     void checkRaw(JCTree tree, Env<AttrContext> env) {
   837         if (lint.isEnabled(Lint.LintCategory.RAW) &&
   838             tree.type.tag == CLASS &&
   839             !env.enclClass.name.isEmpty() &&  //anonymous or intersection
   840             tree.type.isRaw()) {
   841             log.warning(tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
   842         }
   843     }
   845     /** Visitor method: Validate a list of type expressions.
   846      */
   847     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
   848         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   849             validate(l.head, env);
   850     }
   852     /** A visitor class for type validation.
   853      */
   854     class Validator extends JCTree.Visitor {
   856         @Override
   857         public void visitTypeArray(JCArrayTypeTree tree) {
   858             validate(tree.elemtype, env);
   859         }
   861         @Override
   862         public void visitTypeApply(JCTypeApply tree) {
   863             if (tree.type.tag == CLASS) {
   864                 List<Type> formals = tree.type.tsym.type.allparams();
   865                 List<Type> actuals = tree.type.allparams();
   866                 List<JCExpression> args = tree.arguments;
   867                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
   868                 ListBuffer<TypeVar> tvars_buf = new ListBuffer<TypeVar>();
   870                 // For matching pairs of actual argument types `a' and
   871                 // formal type parameters with declared bound `b' ...
   872                 while (args.nonEmpty() && forms.nonEmpty()) {
   873                     validate(args.head, env);
   875                     // exact type arguments needs to know their
   876                     // bounds (for upper and lower bound
   877                     // calculations).  So we create new TypeVars with
   878                     // bounds substed with actuals.
   879                     tvars_buf.append(types.substBound(((TypeVar)forms.head),
   880                                                       formals,
   881                                                       actuals));
   883                     args = args.tail;
   884                     forms = forms.tail;
   885                 }
   887                 args = tree.arguments;
   888                 List<Type> tvars_cap = types.substBounds(formals,
   889                                           formals,
   890                                           types.capture(tree.type).allparams());
   891                 while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   892                     // Let the actual arguments know their bound
   893                     args.head.type.withTypeVar((TypeVar)tvars_cap.head);
   894                     args = args.tail;
   895                     tvars_cap = tvars_cap.tail;
   896                 }
   898                 args = tree.arguments;
   899                 List<TypeVar> tvars = tvars_buf.toList();
   901                 while (args.nonEmpty() && tvars.nonEmpty()) {
   902                     checkExtends(args.head.pos(),
   903                                  args.head.type,
   904                                  tvars.head);
   905                     args = args.tail;
   906                     tvars = tvars.tail;
   907                 }
   909                 checkCapture(tree);
   911                 // Check that this type is either fully parameterized, or
   912                 // not parameterized at all.
   913                 if (tree.type.getEnclosingType().isRaw())
   914                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
   915                 if (tree.clazz.getTag() == JCTree.SELECT)
   916                     visitSelectInternal((JCFieldAccess)tree.clazz);
   917             }
   918         }
   920         @Override
   921         public void visitTypeParameter(JCTypeParameter tree) {
   922             validate(tree.bounds, env);
   923             checkClassBounds(tree.pos(), tree.type);
   924         }
   926         @Override
   927         public void visitWildcard(JCWildcard tree) {
   928             if (tree.inner != null)
   929                 validate(tree.inner, env);
   930         }
   932         @Override
   933         public void visitSelect(JCFieldAccess tree) {
   934             if (tree.type.tag == CLASS) {
   935                 visitSelectInternal(tree);
   937                 // Check that this type is either fully parameterized, or
   938                 // not parameterized at all.
   939                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
   940                     log.error(tree.pos(), "improperly.formed.type.param.missing");
   941             }
   942         }
   943         public void visitSelectInternal(JCFieldAccess tree) {
   944             if (tree.type.tsym.isStatic() &&
   945                 tree.selected.type.isParameterized()) {
   946                 // The enclosing type is not a class, so we are
   947                 // looking at a static member type.  However, the
   948                 // qualifying expression is parameterized.
   949                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
   950             } else {
   951                 // otherwise validate the rest of the expression
   952                 tree.selected.accept(this);
   953             }
   954         }
   956         @Override
   957         public void visitAnnotatedType(JCAnnotatedType tree) {
   958             tree.underlyingType.accept(this);
   959         }
   961         /** Default visitor method: do nothing.
   962          */
   963         @Override
   964         public void visitTree(JCTree tree) {
   965         }
   967         Env<AttrContext> env;
   968     }
   970 /* *************************************************************************
   971  * Exception checking
   972  **************************************************************************/
   974     /* The following methods treat classes as sets that contain
   975      * the class itself and all their subclasses
   976      */
   978     /** Is given type a subtype of some of the types in given list?
   979      */
   980     boolean subset(Type t, List<Type> ts) {
   981         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   982             if (types.isSubtype(t, l.head)) return true;
   983         return false;
   984     }
   986     /** Is given type a subtype or supertype of
   987      *  some of the types in given list?
   988      */
   989     boolean intersects(Type t, List<Type> ts) {
   990         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   991             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
   992         return false;
   993     }
   995     /** Add type set to given type list, unless it is a subclass of some class
   996      *  in the list.
   997      */
   998     List<Type> incl(Type t, List<Type> ts) {
   999         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1002     /** Remove type set from type set list.
  1003      */
  1004     List<Type> excl(Type t, List<Type> ts) {
  1005         if (ts.isEmpty()) {
  1006             return ts;
  1007         } else {
  1008             List<Type> ts1 = excl(t, ts.tail);
  1009             if (types.isSubtype(ts.head, t)) return ts1;
  1010             else if (ts1 == ts.tail) return ts;
  1011             else return ts1.prepend(ts.head);
  1015     /** Form the union of two type set lists.
  1016      */
  1017     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1018         List<Type> ts = ts1;
  1019         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1020             ts = incl(l.head, ts);
  1021         return ts;
  1024     /** Form the difference of two type lists.
  1025      */
  1026     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1027         List<Type> ts = ts1;
  1028         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1029             ts = excl(l.head, ts);
  1030         return ts;
  1033     /** Form the intersection of two type lists.
  1034      */
  1035     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1036         List<Type> ts = List.nil();
  1037         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1038             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1039         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1040             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1041         return ts;
  1044     /** Is exc an exception symbol that need not be declared?
  1045      */
  1046     boolean isUnchecked(ClassSymbol exc) {
  1047         return
  1048             exc.kind == ERR ||
  1049             exc.isSubClass(syms.errorType.tsym, types) ||
  1050             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1053     /** Is exc an exception type that need not be declared?
  1054      */
  1055     boolean isUnchecked(Type exc) {
  1056         return
  1057             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1058             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1059             exc.tag == BOT;
  1062     /** Same, but handling completion failures.
  1063      */
  1064     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1065         try {
  1066             return isUnchecked(exc);
  1067         } catch (CompletionFailure ex) {
  1068             completionError(pos, ex);
  1069             return true;
  1073     /** Is exc handled by given exception list?
  1074      */
  1075     boolean isHandled(Type exc, List<Type> handled) {
  1076         return isUnchecked(exc) || subset(exc, handled);
  1079     /** Return all exceptions in thrown list that are not in handled list.
  1080      *  @param thrown     The list of thrown exceptions.
  1081      *  @param handled    The list of handled exceptions.
  1082      */
  1083     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1084         List<Type> unhandled = List.nil();
  1085         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1086             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1087         return unhandled;
  1090 /* *************************************************************************
  1091  * Overriding/Implementation checking
  1092  **************************************************************************/
  1094     /** The level of access protection given by a flag set,
  1095      *  where PRIVATE is highest and PUBLIC is lowest.
  1096      */
  1097     static int protection(long flags) {
  1098         switch ((short)(flags & AccessFlags)) {
  1099         case PRIVATE: return 3;
  1100         case PROTECTED: return 1;
  1101         default:
  1102         case PUBLIC: return 0;
  1103         case 0: return 2;
  1107     /** A customized "cannot override" error message.
  1108      *  @param m      The overriding method.
  1109      *  @param other  The overridden method.
  1110      *  @return       An internationalized string.
  1111      */
  1112     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1113         String key;
  1114         if ((other.owner.flags() & INTERFACE) == 0)
  1115             key = "cant.override";
  1116         else if ((m.owner.flags() & INTERFACE) == 0)
  1117             key = "cant.implement";
  1118         else
  1119             key = "clashes.with";
  1120         return diags.fragment(key, m, m.location(), other, other.location());
  1123     /** A customized "override" warning message.
  1124      *  @param m      The overriding method.
  1125      *  @param other  The overridden method.
  1126      *  @return       An internationalized string.
  1127      */
  1128     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1129         String key;
  1130         if ((other.owner.flags() & INTERFACE) == 0)
  1131             key = "unchecked.override";
  1132         else if ((m.owner.flags() & INTERFACE) == 0)
  1133             key = "unchecked.implement";
  1134         else
  1135             key = "unchecked.clash.with";
  1136         return diags.fragment(key, m, m.location(), other, other.location());
  1139     /** A customized "override" warning message.
  1140      *  @param m      The overriding method.
  1141      *  @param other  The overridden method.
  1142      *  @return       An internationalized string.
  1143      */
  1144     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1145         String key;
  1146         if ((other.owner.flags() & INTERFACE) == 0)
  1147             key = "varargs.override";
  1148         else  if ((m.owner.flags() & INTERFACE) == 0)
  1149             key = "varargs.implement";
  1150         else
  1151             key = "varargs.clash.with";
  1152         return diags.fragment(key, m, m.location(), other, other.location());
  1155     /** Check that this method conforms with overridden method 'other'.
  1156      *  where `origin' is the class where checking started.
  1157      *  Complications:
  1158      *  (1) Do not check overriding of synthetic methods
  1159      *      (reason: they might be final).
  1160      *      todo: check whether this is still necessary.
  1161      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1162      *      than the method it implements. Augment the proxy methods with the
  1163      *      undeclared exceptions in this case.
  1164      *  (3) When generics are enabled, admit the case where an interface proxy
  1165      *      has a result type
  1166      *      extended by the result type of the method it implements.
  1167      *      Change the proxies result type to the smaller type in this case.
  1169      *  @param tree         The tree from which positions
  1170      *                      are extracted for errors.
  1171      *  @param m            The overriding method.
  1172      *  @param other        The overridden method.
  1173      *  @param origin       The class of which the overriding method
  1174      *                      is a member.
  1175      */
  1176     void checkOverride(JCTree tree,
  1177                        MethodSymbol m,
  1178                        MethodSymbol other,
  1179                        ClassSymbol origin) {
  1180         // Don't check overriding of synthetic methods or by bridge methods.
  1181         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1182             return;
  1185         // Error if static method overrides instance method (JLS 8.4.6.2).
  1186         if ((m.flags() & STATIC) != 0 &&
  1187                    (other.flags() & STATIC) == 0) {
  1188             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1189                       cannotOverride(m, other));
  1190             return;
  1193         // Error if instance method overrides static or final
  1194         // method (JLS 8.4.6.1).
  1195         if ((other.flags() & FINAL) != 0 ||
  1196                  (m.flags() & STATIC) == 0 &&
  1197                  (other.flags() & STATIC) != 0) {
  1198             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1199                       cannotOverride(m, other),
  1200                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1201             return;
  1204         if ((m.owner.flags() & ANNOTATION) != 0) {
  1205             // handled in validateAnnotationMethod
  1206             return;
  1209         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1210         if ((origin.flags() & INTERFACE) == 0 &&
  1211                  protection(m.flags()) > protection(other.flags())) {
  1212             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1213                       cannotOverride(m, other),
  1214                       other.flags() == 0 ?
  1215                           Flag.PACKAGE :
  1216                           asFlagSet(other.flags() & AccessFlags));
  1217             return;
  1220         Type mt = types.memberType(origin.type, m);
  1221         Type ot = types.memberType(origin.type, other);
  1222         // Error if overriding result type is different
  1223         // (or, in the case of generics mode, not a subtype) of
  1224         // overridden result type. We have to rename any type parameters
  1225         // before comparing types.
  1226         List<Type> mtvars = mt.getTypeArguments();
  1227         List<Type> otvars = ot.getTypeArguments();
  1228         Type mtres = mt.getReturnType();
  1229         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1231         overrideWarner.warned = false;
  1232         boolean resultTypesOK =
  1233             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1234         if (!resultTypesOK) {
  1235             if (!allowCovariantReturns &&
  1236                 m.owner != origin &&
  1237                 m.owner.isSubClass(other.owner, types)) {
  1238                 // allow limited interoperability with covariant returns
  1239             } else {
  1240                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1241                           "override.incompatible.ret",
  1242                           cannotOverride(m, other),
  1243                           mtres, otres);
  1244                 return;
  1246         } else if (overrideWarner.warned) {
  1247             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1248                     "override.unchecked.ret",
  1249                     uncheckedOverrides(m, other),
  1250                     mtres, otres);
  1253         // Error if overriding method throws an exception not reported
  1254         // by overridden method.
  1255         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1256         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1257         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1258         if (unhandledErased.nonEmpty()) {
  1259             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1260                       "override.meth.doesnt.throw",
  1261                       cannotOverride(m, other),
  1262                       unhandledUnerased.head);
  1263             return;
  1265         else if (unhandledUnerased.nonEmpty()) {
  1266             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1267                           "override.unchecked.thrown",
  1268                          cannotOverride(m, other),
  1269                          unhandledUnerased.head);
  1270             return;
  1273         // Optional warning if varargs don't agree
  1274         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1275             && lint.isEnabled(Lint.LintCategory.OVERRIDES)) {
  1276             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1277                         ((m.flags() & Flags.VARARGS) != 0)
  1278                         ? "override.varargs.missing"
  1279                         : "override.varargs.extra",
  1280                         varargsOverrides(m, other));
  1283         // Warn if instance method overrides bridge method (compiler spec ??)
  1284         if ((other.flags() & BRIDGE) != 0) {
  1285             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1286                         uncheckedOverrides(m, other));
  1289         // Warn if a deprecated method overridden by a non-deprecated one.
  1290         if ((other.flags() & DEPRECATED) != 0
  1291             && (m.flags() & DEPRECATED) == 0
  1292             && m.outermostClass() != other.outermostClass()
  1293             && !isDeprecatedOverrideIgnorable(other, origin)) {
  1294             warnDeprecated(TreeInfo.diagnosticPositionFor(m, tree), other);
  1297     // where
  1298         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1299             // If the method, m, is defined in an interface, then ignore the issue if the method
  1300             // is only inherited via a supertype and also implemented in the supertype,
  1301             // because in that case, we will rediscover the issue when examining the method
  1302             // in the supertype.
  1303             // If the method, m, is not defined in an interface, then the only time we need to
  1304             // address the issue is when the method is the supertype implemementation: any other
  1305             // case, we will have dealt with when examining the supertype classes
  1306             ClassSymbol mc = m.enclClass();
  1307             Type st = types.supertype(origin.type);
  1308             if (st.tag != CLASS)
  1309                 return true;
  1310             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1312             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1313                 List<Type> intfs = types.interfaces(origin.type);
  1314                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1316             else
  1317                 return (stimpl != m);
  1321     // used to check if there were any unchecked conversions
  1322     Warner overrideWarner = new Warner();
  1324     /** Check that a class does not inherit two concrete methods
  1325      *  with the same signature.
  1326      *  @param pos          Position to be used for error reporting.
  1327      *  @param site         The class type to be checked.
  1328      */
  1329     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1330         Type sup = types.supertype(site);
  1331         if (sup.tag != CLASS) return;
  1333         for (Type t1 = sup;
  1334              t1.tsym.type.isParameterized();
  1335              t1 = types.supertype(t1)) {
  1336             for (Scope.Entry e1 = t1.tsym.members().elems;
  1337                  e1 != null;
  1338                  e1 = e1.sibling) {
  1339                 Symbol s1 = e1.sym;
  1340                 if (s1.kind != MTH ||
  1341                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1342                     !s1.isInheritedIn(site.tsym, types) ||
  1343                     ((MethodSymbol)s1).implementation(site.tsym,
  1344                                                       types,
  1345                                                       true) != s1)
  1346                     continue;
  1347                 Type st1 = types.memberType(t1, s1);
  1348                 int s1ArgsLength = st1.getParameterTypes().length();
  1349                 if (st1 == s1.type) continue;
  1351                 for (Type t2 = sup;
  1352                      t2.tag == CLASS;
  1353                      t2 = types.supertype(t2)) {
  1354                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1355                          e2.scope != null;
  1356                          e2 = e2.next()) {
  1357                         Symbol s2 = e2.sym;
  1358                         if (s2 == s1 ||
  1359                             s2.kind != MTH ||
  1360                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1361                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1362                             !s2.isInheritedIn(site.tsym, types) ||
  1363                             ((MethodSymbol)s2).implementation(site.tsym,
  1364                                                               types,
  1365                                                               true) != s2)
  1366                             continue;
  1367                         Type st2 = types.memberType(t2, s2);
  1368                         if (types.overrideEquivalent(st1, st2))
  1369                             log.error(pos, "concrete.inheritance.conflict",
  1370                                       s1, t1, s2, t2, sup);
  1377     /** Check that classes (or interfaces) do not each define an abstract
  1378      *  method with same name and arguments but incompatible return types.
  1379      *  @param pos          Position to be used for error reporting.
  1380      *  @param t1           The first argument type.
  1381      *  @param t2           The second argument type.
  1382      */
  1383     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1384                                             Type t1,
  1385                                             Type t2) {
  1386         return checkCompatibleAbstracts(pos, t1, t2,
  1387                                         types.makeCompoundType(t1, t2));
  1390     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1391                                             Type t1,
  1392                                             Type t2,
  1393                                             Type site) {
  1394         Symbol sym = firstIncompatibility(t1, t2, site);
  1395         if (sym != null) {
  1396             log.error(pos, "types.incompatible.diff.ret",
  1397                       t1, t2, sym.name +
  1398                       "(" + types.memberType(t2, sym).getParameterTypes() + ")");
  1399             return false;
  1401         return true;
  1404     /** Return the first method which is defined with same args
  1405      *  but different return types in two given interfaces, or null if none
  1406      *  exists.
  1407      *  @param t1     The first type.
  1408      *  @param t2     The second type.
  1409      *  @param site   The most derived type.
  1410      *  @returns symbol from t2 that conflicts with one in t1.
  1411      */
  1412     private Symbol firstIncompatibility(Type t1, Type t2, Type site) {
  1413         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1414         closure(t1, interfaces1);
  1415         Map<TypeSymbol,Type> interfaces2;
  1416         if (t1 == t2)
  1417             interfaces2 = interfaces1;
  1418         else
  1419             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1421         for (Type t3 : interfaces1.values()) {
  1422             for (Type t4 : interfaces2.values()) {
  1423                 Symbol s = firstDirectIncompatibility(t3, t4, site);
  1424                 if (s != null) return s;
  1427         return null;
  1430     /** Compute all the supertypes of t, indexed by type symbol. */
  1431     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1432         if (t.tag != CLASS) return;
  1433         if (typeMap.put(t.tsym, t) == null) {
  1434             closure(types.supertype(t), typeMap);
  1435             for (Type i : types.interfaces(t))
  1436                 closure(i, typeMap);
  1440     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1441     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1442         if (t.tag != CLASS) return;
  1443         if (typesSkip.get(t.tsym) != null) return;
  1444         if (typeMap.put(t.tsym, t) == null) {
  1445             closure(types.supertype(t), typesSkip, typeMap);
  1446             for (Type i : types.interfaces(t))
  1447                 closure(i, typesSkip, typeMap);
  1451     /** Return the first method in t2 that conflicts with a method from t1. */
  1452     private Symbol firstDirectIncompatibility(Type t1, Type t2, Type site) {
  1453         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1454             Symbol s1 = e1.sym;
  1455             Type st1 = null;
  1456             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1457             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1458             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1459             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1460                 Symbol s2 = e2.sym;
  1461                 if (s1 == s2) continue;
  1462                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1463                 if (st1 == null) st1 = types.memberType(t1, s1);
  1464                 Type st2 = types.memberType(t2, s2);
  1465                 if (types.overrideEquivalent(st1, st2)) {
  1466                     List<Type> tvars1 = st1.getTypeArguments();
  1467                     List<Type> tvars2 = st2.getTypeArguments();
  1468                     Type rt1 = st1.getReturnType();
  1469                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1470                     boolean compat =
  1471                         types.isSameType(rt1, rt2) ||
  1472                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1473                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1474                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1475                          checkCommonOverriderIn(s1,s2,site);
  1476                     if (!compat) return s2;
  1480         return null;
  1482     //WHERE
  1483     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1484         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1485         Type st1 = types.memberType(site, s1);
  1486         Type st2 = types.memberType(site, s2);
  1487         closure(site, supertypes);
  1488         for (Type t : supertypes.values()) {
  1489             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1490                 Symbol s3 = e.sym;
  1491                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1492                 Type st3 = types.memberType(site,s3);
  1493                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1494                     if (s3.owner == site.tsym) {
  1495                         return true;
  1497                     List<Type> tvars1 = st1.getTypeArguments();
  1498                     List<Type> tvars2 = st2.getTypeArguments();
  1499                     List<Type> tvars3 = st3.getTypeArguments();
  1500                     Type rt1 = st1.getReturnType();
  1501                     Type rt2 = st2.getReturnType();
  1502                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1503                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1504                     boolean compat =
  1505                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1506                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1507                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1508                     if (compat)
  1509                         return true;
  1513         return false;
  1516     /** Check that a given method conforms with any method it overrides.
  1517      *  @param tree         The tree from which positions are extracted
  1518      *                      for errors.
  1519      *  @param m            The overriding method.
  1520      */
  1521     void checkOverride(JCTree tree, MethodSymbol m) {
  1522         ClassSymbol origin = (ClassSymbol)m.owner;
  1523         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1524             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1525                 log.error(tree.pos(), "enum.no.finalize");
  1526                 return;
  1528         for (Type t = types.supertype(origin.type); t.tag == CLASS;
  1529              t = types.supertype(t)) {
  1530             TypeSymbol c = t.tsym;
  1531             Scope.Entry e = c.members().lookup(m.name);
  1532             while (e.scope != null) {
  1533                 if (m.overrides(e.sym, origin, types, false))
  1534                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1535                 else if (e.sym.kind == MTH &&
  1536                         e.sym.isInheritedIn(origin, types) &&
  1537                         (e.sym.flags() & SYNTHETIC) == 0 &&
  1538                         !m.isConstructor()) {
  1539                     Type er1 = m.erasure(types);
  1540                     Type er2 = e.sym.erasure(types);
  1541                     if (types.isSameTypes(er1.getParameterTypes(),
  1542                             er2.getParameterTypes())) {
  1543                             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1544                                     "name.clash.same.erasure.no.override",
  1545                                     m, m.location(),
  1546                                     e.sym, e.sym.location());
  1549                 e = e.next();
  1554     /** Check that all abstract members of given class have definitions.
  1555      *  @param pos          Position to be used for error reporting.
  1556      *  @param c            The class.
  1557      */
  1558     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1559         try {
  1560             MethodSymbol undef = firstUndef(c, c);
  1561             if (undef != null) {
  1562                 if ((c.flags() & ENUM) != 0 &&
  1563                     types.supertype(c.type).tsym == syms.enumSym &&
  1564                     (c.flags() & FINAL) == 0) {
  1565                     // add the ABSTRACT flag to an enum
  1566                     c.flags_field |= ABSTRACT;
  1567                 } else {
  1568                     MethodSymbol undef1 =
  1569                         new MethodSymbol(undef.flags(), undef.name,
  1570                                          types.memberType(c.type, undef), undef.owner);
  1571                     log.error(pos, "does.not.override.abstract",
  1572                               c, undef1, undef1.location());
  1575         } catch (CompletionFailure ex) {
  1576             completionError(pos, ex);
  1579 //where
  1580         /** Return first abstract member of class `c' that is not defined
  1581          *  in `impl', null if there is none.
  1582          */
  1583         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1584             MethodSymbol undef = null;
  1585             // Do not bother to search in classes that are not abstract,
  1586             // since they cannot have abstract members.
  1587             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1588                 Scope s = c.members();
  1589                 for (Scope.Entry e = s.elems;
  1590                      undef == null && e != null;
  1591                      e = e.sibling) {
  1592                     if (e.sym.kind == MTH &&
  1593                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1594                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1595                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1596                         if (implmeth == null || implmeth == absmeth)
  1597                             undef = absmeth;
  1600                 if (undef == null) {
  1601                     Type st = types.supertype(c.type);
  1602                     if (st.tag == CLASS)
  1603                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1605                 for (List<Type> l = types.interfaces(c.type);
  1606                      undef == null && l.nonEmpty();
  1607                      l = l.tail) {
  1608                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1611             return undef;
  1614     /** Check for cyclic references. Issue an error if the
  1615      *  symbol of the type referred to has a LOCKED flag set.
  1617      *  @param pos      Position to be used for error reporting.
  1618      *  @param t        The type referred to.
  1619      */
  1620     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1621         checkNonCyclicInternal(pos, t);
  1625     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1626         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1629     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1630         final TypeVar tv;
  1631         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1632             return;
  1633         if (seen.contains(t)) {
  1634             tv = (TypeVar)t;
  1635             tv.bound = types.createErrorType(t);
  1636             log.error(pos, "cyclic.inheritance", t);
  1637         } else if (t.tag == TYPEVAR) {
  1638             tv = (TypeVar)t;
  1639             seen = seen.prepend(tv);
  1640             for (Type b : types.getBounds(tv))
  1641                 checkNonCyclic1(pos, b, seen);
  1645     /** Check for cyclic references. Issue an error if the
  1646      *  symbol of the type referred to has a LOCKED flag set.
  1648      *  @param pos      Position to be used for error reporting.
  1649      *  @param t        The type referred to.
  1650      *  @returns        True if the check completed on all attributed classes
  1651      */
  1652     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1653         boolean complete = true; // was the check complete?
  1654         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1655         Symbol c = t.tsym;
  1656         if ((c.flags_field & ACYCLIC) != 0) return true;
  1658         if ((c.flags_field & LOCKED) != 0) {
  1659             noteCyclic(pos, (ClassSymbol)c);
  1660         } else if (!c.type.isErroneous()) {
  1661             try {
  1662                 c.flags_field |= LOCKED;
  1663                 if (c.type.tag == CLASS) {
  1664                     ClassType clazz = (ClassType)c.type;
  1665                     if (clazz.interfaces_field != null)
  1666                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1667                             complete &= checkNonCyclicInternal(pos, l.head);
  1668                     if (clazz.supertype_field != null) {
  1669                         Type st = clazz.supertype_field;
  1670                         if (st != null && st.tag == CLASS)
  1671                             complete &= checkNonCyclicInternal(pos, st);
  1673                     if (c.owner.kind == TYP)
  1674                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1676             } finally {
  1677                 c.flags_field &= ~LOCKED;
  1680         if (complete)
  1681             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1682         if (complete) c.flags_field |= ACYCLIC;
  1683         return complete;
  1686     /** Note that we found an inheritance cycle. */
  1687     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1688         log.error(pos, "cyclic.inheritance", c);
  1689         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1690             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  1691         Type st = types.supertype(c.type);
  1692         if (st.tag == CLASS)
  1693             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  1694         c.type = types.createErrorType(c, c.type);
  1695         c.flags_field |= ACYCLIC;
  1698     /** Check that all methods which implement some
  1699      *  method conform to the method they implement.
  1700      *  @param tree         The class definition whose members are checked.
  1701      */
  1702     void checkImplementations(JCClassDecl tree) {
  1703         checkImplementations(tree, tree.sym);
  1705 //where
  1706         /** Check that all methods which implement some
  1707          *  method in `ic' conform to the method they implement.
  1708          */
  1709         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  1710             ClassSymbol origin = tree.sym;
  1711             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  1712                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  1713                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  1714                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  1715                         if (e.sym.kind == MTH &&
  1716                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  1717                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  1718                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  1719                             if (implmeth != null && implmeth != absmeth &&
  1720                                 (implmeth.owner.flags() & INTERFACE) ==
  1721                                 (origin.flags() & INTERFACE)) {
  1722                                 // don't check if implmeth is in a class, yet
  1723                                 // origin is an interface. This case arises only
  1724                                 // if implmeth is declared in Object. The reason is
  1725                                 // that interfaces really don't inherit from
  1726                                 // Object it's just that the compiler represents
  1727                                 // things that way.
  1728                                 checkOverride(tree, implmeth, absmeth, origin);
  1736     /** Check that all abstract methods implemented by a class are
  1737      *  mutually compatible.
  1738      *  @param pos          Position to be used for error reporting.
  1739      *  @param c            The class whose interfaces are checked.
  1740      */
  1741     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  1742         List<Type> supertypes = types.interfaces(c);
  1743         Type supertype = types.supertype(c);
  1744         if (supertype.tag == CLASS &&
  1745             (supertype.tsym.flags() & ABSTRACT) != 0)
  1746             supertypes = supertypes.prepend(supertype);
  1747         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  1748             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  1749                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  1750                 return;
  1751             for (List<Type> m = supertypes; m != l; m = m.tail)
  1752                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  1753                     return;
  1755         checkCompatibleConcretes(pos, c);
  1758     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  1759         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  1760             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  1761                 // VM allows methods and variables with differing types
  1762                 if (sym.kind == e.sym.kind &&
  1763                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  1764                     sym != e.sym &&
  1765                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  1766                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  1767                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  1768                     return;
  1774     /** Report a conflict between a user symbol and a synthetic symbol.
  1775      */
  1776     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  1777         if (!sym.type.isErroneous()) {
  1778             if (warnOnSyntheticConflicts) {
  1779                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  1781             else {
  1782                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  1787     /** Check that class c does not implement directly or indirectly
  1788      *  the same parameterized interface with two different argument lists.
  1789      *  @param pos          Position to be used for error reporting.
  1790      *  @param type         The type whose interfaces are checked.
  1791      */
  1792     void checkClassBounds(DiagnosticPosition pos, Type type) {
  1793         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  1795 //where
  1796         /** Enter all interfaces of type `type' into the hash table `seensofar'
  1797          *  with their class symbol as key and their type as value. Make
  1798          *  sure no class is entered with two different types.
  1799          */
  1800         void checkClassBounds(DiagnosticPosition pos,
  1801                               Map<TypeSymbol,Type> seensofar,
  1802                               Type type) {
  1803             if (type.isErroneous()) return;
  1804             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  1805                 Type it = l.head;
  1806                 Type oldit = seensofar.put(it.tsym, it);
  1807                 if (oldit != null) {
  1808                     List<Type> oldparams = oldit.allparams();
  1809                     List<Type> newparams = it.allparams();
  1810                     if (!types.containsTypeEquivalent(oldparams, newparams))
  1811                         log.error(pos, "cant.inherit.diff.arg",
  1812                                   it.tsym, Type.toString(oldparams),
  1813                                   Type.toString(newparams));
  1815                 checkClassBounds(pos, seensofar, it);
  1817             Type st = types.supertype(type);
  1818             if (st != null) checkClassBounds(pos, seensofar, st);
  1821     /** Enter interface into into set.
  1822      *  If it existed already, issue a "repeated interface" error.
  1823      */
  1824     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  1825         if (its.contains(it))
  1826             log.error(pos, "repeated.interface");
  1827         else {
  1828             its.add(it);
  1832 /* *************************************************************************
  1833  * Check annotations
  1834  **************************************************************************/
  1836     /** Annotation types are restricted to primitives, String, an
  1837      *  enum, an annotation, Class, Class<?>, Class<? extends
  1838      *  Anything>, arrays of the preceding.
  1839      */
  1840     void validateAnnotationType(JCTree restype) {
  1841         // restype may be null if an error occurred, so don't bother validating it
  1842         if (restype != null) {
  1843             validateAnnotationType(restype.pos(), restype.type);
  1847     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  1848         if (type.isPrimitive()) return;
  1849         if (types.isSameType(type, syms.stringType)) return;
  1850         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  1851         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  1852         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  1853         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  1854             validateAnnotationType(pos, types.elemtype(type));
  1855             return;
  1857         log.error(pos, "invalid.annotation.member.type");
  1860     /**
  1861      * "It is also a compile-time error if any method declared in an
  1862      * annotation type has a signature that is override-equivalent to
  1863      * that of any public or protected method declared in class Object
  1864      * or in the interface annotation.Annotation."
  1866      * @jls3 9.6 Annotation Types
  1867      */
  1868     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  1869         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  1870             Scope s = sup.tsym.members();
  1871             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  1872                 if (e.sym.kind == MTH &&
  1873                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  1874                     types.overrideEquivalent(m.type, e.sym.type))
  1875                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  1880     /** Check the annotations of a symbol.
  1881      */
  1882     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  1883         if (skipAnnotations) return;
  1884         for (JCAnnotation a : annotations)
  1885             validateAnnotation(a, s);
  1888     /** Check the type annotations
  1889      */
  1890     public void validateTypeAnnotations(List<JCTypeAnnotation> annotations, boolean isTypeParameter) {
  1891         if (skipAnnotations) return;
  1892         for (JCTypeAnnotation a : annotations)
  1893             validateTypeAnnotation(a, isTypeParameter);
  1896     /** Check an annotation of a symbol.
  1897      */
  1898     public void validateAnnotation(JCAnnotation a, Symbol s) {
  1899         validateAnnotation(a);
  1901         if (!annotationApplicable(a, s))
  1902             log.error(a.pos(), "annotation.type.not.applicable");
  1904         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  1905             if (!isOverrider(s))
  1906                 log.error(a.pos(), "method.does.not.override.superclass");
  1910     public void validateTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
  1911         if (a.type == null)
  1912             throw new AssertionError("annotation tree hasn't been attributed yet: " + a);
  1913         validateAnnotation(a);
  1915         if (!isTypeAnnotation(a, isTypeParameter))
  1916             log.error(a.pos(), "annotation.type.not.applicable");
  1919     /** Is s a method symbol that overrides a method in a superclass? */
  1920     boolean isOverrider(Symbol s) {
  1921         if (s.kind != MTH || s.isStatic())
  1922             return false;
  1923         MethodSymbol m = (MethodSymbol)s;
  1924         TypeSymbol owner = (TypeSymbol)m.owner;
  1925         for (Type sup : types.closure(owner.type)) {
  1926             if (sup == owner.type)
  1927                 continue; // skip "this"
  1928             Scope scope = sup.tsym.members();
  1929             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  1930                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  1931                     return true;
  1934         return false;
  1937     /** Is the annotation applicable to type annotations */
  1938     boolean isTypeAnnotation(JCTypeAnnotation a, boolean isTypeParameter) {
  1939         Attribute.Compound atTarget =
  1940             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1941         if (atTarget == null) return true;
  1942         Attribute atValue = atTarget.member(names.value);
  1943         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1944         Attribute.Array arr = (Attribute.Array) atValue;
  1945         for (Attribute app : arr.values) {
  1946             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1947             Attribute.Enum e = (Attribute.Enum) app;
  1948             if (!isTypeParameter && e.value.name == names.TYPE_USE)
  1949                 return true;
  1950             else if (isTypeParameter && e.value.name == names.TYPE_PARAMETER)
  1951                 return true;
  1953         return false;
  1956     /** Is the annotation applicable to the symbol? */
  1957     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  1958         Attribute.Compound atTarget =
  1959             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  1960         if (atTarget == null) return true;
  1961         Attribute atValue = atTarget.member(names.value);
  1962         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  1963         Attribute.Array arr = (Attribute.Array) atValue;
  1964         for (Attribute app : arr.values) {
  1965             if (!(app instanceof Attribute.Enum)) return true; // recovery
  1966             Attribute.Enum e = (Attribute.Enum) app;
  1967             if (e.value.name == names.TYPE)
  1968                 { if (s.kind == TYP) return true; }
  1969             else if (e.value.name == names.FIELD)
  1970                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  1971             else if (e.value.name == names.METHOD)
  1972                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  1973             else if (e.value.name == names.PARAMETER)
  1974                 { if (s.kind == VAR &&
  1975                       s.owner.kind == MTH &&
  1976                       (s.flags() & PARAMETER) != 0)
  1977                     return true;
  1979             else if (e.value.name == names.CONSTRUCTOR)
  1980                 { if (s.kind == MTH && s.isConstructor()) return true; }
  1981             else if (e.value.name == names.LOCAL_VARIABLE)
  1982                 { if (s.kind == VAR && s.owner.kind == MTH &&
  1983                       (s.flags() & PARAMETER) == 0)
  1984                     return true;
  1986             else if (e.value.name == names.ANNOTATION_TYPE)
  1987                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  1988                     return true;
  1990             else if (e.value.name == names.PACKAGE)
  1991                 { if (s.kind == PCK) return true; }
  1992             else if (e.value.name == names.TYPE_USE)
  1993                 { if (s.kind == TYP ||
  1994                       s.kind == VAR ||
  1995                       (s.kind == MTH && !s.isConstructor() &&
  1996                        s.type.getReturnType().tag != VOID))
  1997                     return true;
  1999             else
  2000                 return true; // recovery
  2002         return false;
  2005     /** Check an annotation value.
  2006      */
  2007     public void validateAnnotation(JCAnnotation a) {
  2008         if (a.type.isErroneous()) return;
  2010         // collect an inventory of the members
  2011         Set<MethodSymbol> members = new HashSet<MethodSymbol>();
  2012         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2013              e != null;
  2014              e = e.sibling)
  2015             if (e.sym.kind == MTH)
  2016                 members.add((MethodSymbol) e.sym);
  2018         // count them off as they're annotated
  2019         for (JCTree arg : a.args) {
  2020             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  2021             JCAssign assign = (JCAssign) arg;
  2022             Symbol m = TreeInfo.symbol(assign.lhs);
  2023             if (m == null || m.type.isErroneous()) continue;
  2024             if (!members.remove(m))
  2025                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2026                           m.name, a.type);
  2027             if (assign.rhs.getTag() == ANNOTATION)
  2028                 validateAnnotation((JCAnnotation)assign.rhs);
  2031         // all the remaining ones better have default values
  2032         for (MethodSymbol m : members)
  2033             if (m.defaultValue == null && !m.type.isErroneous())
  2034                 log.error(a.pos(), "annotation.missing.default.value",
  2035                           a.type, m.name);
  2037         // special case: java.lang.annotation.Target must not have
  2038         // repeated values in its value member
  2039         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2040             a.args.tail == null)
  2041             return;
  2043         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  2044         JCAssign assign = (JCAssign) a.args.head;
  2045         Symbol m = TreeInfo.symbol(assign.lhs);
  2046         if (m.name != names.value) return;
  2047         JCTree rhs = assign.rhs;
  2048         if (rhs.getTag() != JCTree.NEWARRAY) return;
  2049         JCNewArray na = (JCNewArray) rhs;
  2050         Set<Symbol> targets = new HashSet<Symbol>();
  2051         for (JCTree elem : na.elems) {
  2052             if (!targets.add(TreeInfo.symbol(elem))) {
  2053                 log.error(elem.pos(), "repeated.annotation.target");
  2058     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2059         if (allowAnnotations &&
  2060             lint.isEnabled(Lint.LintCategory.DEP_ANN) &&
  2061             (s.flags() & DEPRECATED) != 0 &&
  2062             !syms.deprecatedType.isErroneous() &&
  2063             s.attribute(syms.deprecatedType.tsym) == null) {
  2064             log.warning(pos, "missing.deprecated.annotation");
  2068 /* *************************************************************************
  2069  * Check for recursive annotation elements.
  2070  **************************************************************************/
  2072     /** Check for cycles in the graph of annotation elements.
  2073      */
  2074     void checkNonCyclicElements(JCClassDecl tree) {
  2075         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2076         assert (tree.sym.flags_field & LOCKED) == 0;
  2077         try {
  2078             tree.sym.flags_field |= LOCKED;
  2079             for (JCTree def : tree.defs) {
  2080                 if (def.getTag() != JCTree.METHODDEF) continue;
  2081                 JCMethodDecl meth = (JCMethodDecl)def;
  2082                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2084         } finally {
  2085             tree.sym.flags_field &= ~LOCKED;
  2086             tree.sym.flags_field |= ACYCLIC_ANN;
  2090     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2091         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2092             return;
  2093         if ((tsym.flags_field & LOCKED) != 0) {
  2094             log.error(pos, "cyclic.annotation.element");
  2095             return;
  2097         try {
  2098             tsym.flags_field |= LOCKED;
  2099             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2100                 Symbol s = e.sym;
  2101                 if (s.kind != Kinds.MTH)
  2102                     continue;
  2103                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2105         } finally {
  2106             tsym.flags_field &= ~LOCKED;
  2107             tsym.flags_field |= ACYCLIC_ANN;
  2111     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2112         switch (type.tag) {
  2113         case TypeTags.CLASS:
  2114             if ((type.tsym.flags() & ANNOTATION) != 0)
  2115                 checkNonCyclicElementsInternal(pos, type.tsym);
  2116             break;
  2117         case TypeTags.ARRAY:
  2118             checkAnnotationResType(pos, types.elemtype(type));
  2119             break;
  2120         default:
  2121             break; // int etc
  2125 /* *************************************************************************
  2126  * Check for cycles in the constructor call graph.
  2127  **************************************************************************/
  2129     /** Check for cycles in the graph of constructors calling other
  2130      *  constructors.
  2131      */
  2132     void checkCyclicConstructors(JCClassDecl tree) {
  2133         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2135         // enter each constructor this-call into the map
  2136         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2137             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2138             if (app == null) continue;
  2139             JCMethodDecl meth = (JCMethodDecl) l.head;
  2140             if (TreeInfo.name(app.meth) == names._this) {
  2141                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2142             } else {
  2143                 meth.sym.flags_field |= ACYCLIC;
  2147         // Check for cycles in the map
  2148         Symbol[] ctors = new Symbol[0];
  2149         ctors = callMap.keySet().toArray(ctors);
  2150         for (Symbol caller : ctors) {
  2151             checkCyclicConstructor(tree, caller, callMap);
  2155     /** Look in the map to see if the given constructor is part of a
  2156      *  call cycle.
  2157      */
  2158     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2159                                         Map<Symbol,Symbol> callMap) {
  2160         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2161             if ((ctor.flags_field & LOCKED) != 0) {
  2162                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2163                           "recursive.ctor.invocation");
  2164             } else {
  2165                 ctor.flags_field |= LOCKED;
  2166                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2167                 ctor.flags_field &= ~LOCKED;
  2169             ctor.flags_field |= ACYCLIC;
  2173 /* *************************************************************************
  2174  * Miscellaneous
  2175  **************************************************************************/
  2177     /**
  2178      * Return the opcode of the operator but emit an error if it is an
  2179      * error.
  2180      * @param pos        position for error reporting.
  2181      * @param operator   an operator
  2182      * @param tag        a tree tag
  2183      * @param left       type of left hand side
  2184      * @param right      type of right hand side
  2185      */
  2186     int checkOperator(DiagnosticPosition pos,
  2187                        OperatorSymbol operator,
  2188                        int tag,
  2189                        Type left,
  2190                        Type right) {
  2191         if (operator.opcode == ByteCodes.error) {
  2192             log.error(pos,
  2193                       "operator.cant.be.applied",
  2194                       treeinfo.operatorName(tag),
  2195                       List.of(left, right));
  2197         return operator.opcode;
  2201     /**
  2202      *  Check for division by integer constant zero
  2203      *  @param pos           Position for error reporting.
  2204      *  @param operator      The operator for the expression
  2205      *  @param operand       The right hand operand for the expression
  2206      */
  2207     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2208         if (operand.constValue() != null
  2209             && lint.isEnabled(Lint.LintCategory.DIVZERO)
  2210             && operand.tag <= LONG
  2211             && ((Number) (operand.constValue())).longValue() == 0) {
  2212             int opc = ((OperatorSymbol)operator).opcode;
  2213             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2214                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2215                 log.warning(pos, "div.zero");
  2220     /**
  2221      * Check for empty statements after if
  2222      */
  2223     void checkEmptyIf(JCIf tree) {
  2224         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(Lint.LintCategory.EMPTY))
  2225             log.warning(tree.thenpart.pos(), "empty.if");
  2228     /** Check that symbol is unique in given scope.
  2229      *  @param pos           Position for error reporting.
  2230      *  @param sym           The symbol.
  2231      *  @param s             The scope.
  2232      */
  2233     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2234         if (sym.type.isErroneous())
  2235             return true;
  2236         if (sym.owner.name == names.any) return false;
  2237         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2238             if (sym != e.sym &&
  2239                 sym.kind == e.sym.kind &&
  2240                 sym.name != names.error &&
  2241                 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2242                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS))
  2243                     varargsDuplicateError(pos, sym, e.sym);
  2244                 else if (sym.kind == MTH && !types.overrideEquivalent(sym.type, e.sym.type))
  2245                     duplicateErasureError(pos, sym, e.sym);
  2246                 else
  2247                     duplicateError(pos, e.sym);
  2248                 return false;
  2251         return true;
  2253     //where
  2254     /** Report duplicate declaration error.
  2255      */
  2256     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2257         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2258             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2262     /** Check that single-type import is not already imported or top-level defined,
  2263      *  but make an exception for two single-type imports which denote the same type.
  2264      *  @param pos           Position for error reporting.
  2265      *  @param sym           The symbol.
  2266      *  @param s             The scope
  2267      */
  2268     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2269         return checkUniqueImport(pos, sym, s, false);
  2272     /** Check that static single-type import is not already imported or top-level defined,
  2273      *  but make an exception for two single-type imports which denote the same type.
  2274      *  @param pos           Position for error reporting.
  2275      *  @param sym           The symbol.
  2276      *  @param s             The scope
  2277      *  @param staticImport  Whether or not this was a static import
  2278      */
  2279     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2280         return checkUniqueImport(pos, sym, s, true);
  2283     /** Check that single-type import is not already imported or top-level defined,
  2284      *  but make an exception for two single-type imports which denote the same type.
  2285      *  @param pos           Position for error reporting.
  2286      *  @param sym           The symbol.
  2287      *  @param s             The scope.
  2288      *  @param staticImport  Whether or not this was a static import
  2289      */
  2290     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2291         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2292             // is encountered class entered via a class declaration?
  2293             boolean isClassDecl = e.scope == s;
  2294             if ((isClassDecl || sym != e.sym) &&
  2295                 sym.kind == e.sym.kind &&
  2296                 sym.name != names.error) {
  2297                 if (!e.sym.type.isErroneous()) {
  2298                     String what = e.sym.toString();
  2299                     if (!isClassDecl) {
  2300                         if (staticImport)
  2301                             log.error(pos, "already.defined.static.single.import", what);
  2302                         else
  2303                             log.error(pos, "already.defined.single.import", what);
  2305                     else if (sym != e.sym)
  2306                         log.error(pos, "already.defined.this.unit", what);
  2308                 return false;
  2311         return true;
  2314     /** Check that a qualified name is in canonical form (for import decls).
  2315      */
  2316     public void checkCanonical(JCTree tree) {
  2317         if (!isCanonical(tree))
  2318             log.error(tree.pos(), "import.requires.canonical",
  2319                       TreeInfo.symbol(tree));
  2321         // where
  2322         private boolean isCanonical(JCTree tree) {
  2323             while (tree.getTag() == JCTree.SELECT) {
  2324                 JCFieldAccess s = (JCFieldAccess) tree;
  2325                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2326                     return false;
  2327                 tree = s.selected;
  2329             return true;
  2332     private class ConversionWarner extends Warner {
  2333         final String key;
  2334         final Type found;
  2335         final Type expected;
  2336         public ConversionWarner(DiagnosticPosition pos, String key, Type found, Type expected) {
  2337             super(pos);
  2338             this.key = key;
  2339             this.found = found;
  2340             this.expected = expected;
  2343         @Override
  2344         public void warnUnchecked() {
  2345             boolean warned = this.warned;
  2346             super.warnUnchecked();
  2347             if (warned) return; // suppress redundant diagnostics
  2348             Object problem = diags.fragment(key);
  2349             Check.this.warnUnchecked(pos(), "prob.found.req", problem, found, expected);
  2353     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2354         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2357     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2358         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial