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

Tue, 06 Mar 2012 13:26:36 +0000

author
mcimadamore
date
Tue, 06 Mar 2012 13:26:36 +0000
changeset 1218
dda6a5b15580
parent 1216
6aafebe9a394
child 1219
48ee63caaa93
permissions
-rw-r--r--

7148622: Some diagnostic methods do not go through Log.report
Summary: Deferred lint diagnostics ignore Log settings such as deferred diagnostics
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. 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.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * 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.Flags.ANNOTATION;
    46 import static com.sun.tools.javac.code.Flags.SYNCHRONIZED;
    47 import static com.sun.tools.javac.code.Kinds.*;
    48 import static com.sun.tools.javac.code.TypeTags.*;
    49 import static com.sun.tools.javac.code.TypeTags.WILDCARD;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    53 /** Type checking helper class for the attribution phase.
    54  *
    55  *  <p><b>This is NOT part of any supported API.
    56  *  If you write code that depends on this, you do so at your own risk.
    57  *  This code and its internal interfaces are subject to change or
    58  *  deletion without notice.</b>
    59  */
    60 public class Check {
    61     protected static final Context.Key<Check> checkKey =
    62         new Context.Key<Check>();
    64     private final Names names;
    65     private final Log log;
    66     private final Symtab syms;
    67     private final Enter enter;
    68     private final Infer infer;
    69     private final Types types;
    70     private final JCDiagnostic.Factory diags;
    71     private final boolean skipAnnotations;
    72     private boolean warnOnSyntheticConflicts;
    73     private boolean suppressAbortOnBadClassFile;
    74     private boolean enableSunApiLintControl;
    75     private final TreeInfo treeinfo;
    77     // The set of lint options currently in effect. It is initialized
    78     // from the context, and then is set/reset as needed by Attr as it
    79     // visits all the various parts of the trees during attribution.
    80     private Lint lint;
    82     // The method being analyzed in Attr - it is set/reset as needed by
    83     // Attr as it visits new method declarations.
    84     private MethodSymbol method;
    86     public static Check instance(Context context) {
    87         Check instance = context.get(checkKey);
    88         if (instance == null)
    89             instance = new Check(context);
    90         return instance;
    91     }
    93     protected Check(Context context) {
    94         context.put(checkKey, this);
    96         names = Names.instance(context);
    97         log = Log.instance(context);
    98         syms = Symtab.instance(context);
    99         enter = Enter.instance(context);
   100         infer = Infer.instance(context);
   101         this.types = Types.instance(context);
   102         diags = JCDiagnostic.Factory.instance(context);
   103         Options options = Options.instance(context);
   104         lint = Lint.instance(context);
   105         treeinfo = TreeInfo.instance(context);
   107         Source source = Source.instance(context);
   108         allowGenerics = source.allowGenerics();
   109         allowAnnotations = source.allowAnnotations();
   110         allowCovariantReturns = source.allowCovariantReturns();
   111         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   112         complexInference = options.isSet("complexinference");
   113         skipAnnotations = options.isSet("skipAnnotations");
   114         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   115         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   116         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   118         Target target = Target.instance(context);
   119         syntheticNameChar = target.syntheticNameChar();
   121         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   122         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   123         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   124         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   126         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   127                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   128         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   129                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   130         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   131                 enforceMandatoryWarnings, "sunapi", null);
   133         deferredLintHandler = DeferredLintHandler.immediateHandler;
   134     }
   136     /** Switch: generics enabled?
   137      */
   138     boolean allowGenerics;
   140     /** Switch: annotations enabled?
   141      */
   142     boolean allowAnnotations;
   144     /** Switch: covariant returns enabled?
   145      */
   146     boolean allowCovariantReturns;
   148     /** Switch: simplified varargs enabled?
   149      */
   150     boolean allowSimplifiedVarargs;
   152     /** Switch: -complexinference option set?
   153      */
   154     boolean complexInference;
   156     /** Character for synthetic names
   157      */
   158     char syntheticNameChar;
   160     /** A table mapping flat names of all compiled classes in this run to their
   161      *  symbols; maintained from outside.
   162      */
   163     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   165     /** A handler for messages about deprecated usage.
   166      */
   167     private MandatoryWarningHandler deprecationHandler;
   169     /** A handler for messages about unchecked or unsafe usage.
   170      */
   171     private MandatoryWarningHandler uncheckedHandler;
   173     /** A handler for messages about using proprietary API.
   174      */
   175     private MandatoryWarningHandler sunApiHandler;
   177     /** A handler for deferred lint warnings.
   178      */
   179     private DeferredLintHandler deferredLintHandler;
   181 /* *************************************************************************
   182  * Errors and Warnings
   183  **************************************************************************/
   185     Lint setLint(Lint newLint) {
   186         Lint prev = lint;
   187         lint = newLint;
   188         return prev;
   189     }
   191     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   192         DeferredLintHandler prev = deferredLintHandler;
   193         deferredLintHandler = newDeferredLintHandler;
   194         return prev;
   195     }
   197     MethodSymbol setMethod(MethodSymbol newMethod) {
   198         MethodSymbol prev = method;
   199         method = newMethod;
   200         return prev;
   201     }
   203     /** Warn about deprecated symbol.
   204      *  @param pos        Position to be used for error reporting.
   205      *  @param sym        The deprecated symbol.
   206      */
   207     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   208         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   209             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   210     }
   212     /** Warn about unchecked operation.
   213      *  @param pos        Position to be used for error reporting.
   214      *  @param msg        A string describing the problem.
   215      */
   216     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   217         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   218             uncheckedHandler.report(pos, msg, args);
   219     }
   221     /** Warn about unsafe vararg method decl.
   222      *  @param pos        Position to be used for error reporting.
   223      *  @param sym        The deprecated symbol.
   224      */
   225     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   226         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   227             log.warning(LintCategory.VARARGS, pos, key, args);
   228     }
   230     /** Warn about using proprietary API.
   231      *  @param pos        Position to be used for error reporting.
   232      *  @param msg        A string describing the problem.
   233      */
   234     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   235         if (!lint.isSuppressed(LintCategory.SUNAPI))
   236             sunApiHandler.report(pos, msg, args);
   237     }
   239     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   240         if (lint.isEnabled(LintCategory.STATIC))
   241             log.warning(LintCategory.STATIC, pos, msg, args);
   242     }
   244     /**
   245      * Report any deferred diagnostics.
   246      */
   247     public void reportDeferredDiagnostics() {
   248         deprecationHandler.reportDeferredDiagnostic();
   249         uncheckedHandler.reportDeferredDiagnostic();
   250         sunApiHandler.reportDeferredDiagnostic();
   251     }
   254     /** Report a failure to complete a class.
   255      *  @param pos        Position to be used for error reporting.
   256      *  @param ex         The failure to report.
   257      */
   258     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   259         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   260         if (ex instanceof ClassReader.BadClassFile
   261                 && !suppressAbortOnBadClassFile) throw new Abort();
   262         else return syms.errType;
   263     }
   265     /** Report a type error.
   266      *  @param pos        Position to be used for error reporting.
   267      *  @param problem    A string describing the error.
   268      *  @param found      The type that was found.
   269      *  @param req        The type that was required.
   270      */
   271     Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
   272         log.error(pos, "prob.found.req",
   273                   problem, found, req);
   274         return types.createErrorType(found);
   275     }
   277     Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
   278         log.error(pos, "prob.found.req.1", problem, found, req, explanation);
   279         return types.createErrorType(found);
   280     }
   282     /** Report an error that wrong type tag was found.
   283      *  @param pos        Position to be used for error reporting.
   284      *  @param required   An internationalized string describing the type tag
   285      *                    required.
   286      *  @param found      The type that was found.
   287      */
   288     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   289         // this error used to be raised by the parser,
   290         // but has been delayed to this point:
   291         if (found instanceof Type && ((Type)found).tag == VOID) {
   292             log.error(pos, "illegal.start.of.type");
   293             return syms.errType;
   294         }
   295         log.error(pos, "type.found.req", found, required);
   296         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   297     }
   299     /** Report an error that symbol cannot be referenced before super
   300      *  has been called.
   301      *  @param pos        Position to be used for error reporting.
   302      *  @param sym        The referenced symbol.
   303      */
   304     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   305         log.error(pos, "cant.ref.before.ctor.called", sym);
   306     }
   308     /** Report duplicate declaration error.
   309      */
   310     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   311         if (!sym.type.isErroneous()) {
   312             Symbol location = sym.location();
   313             if (location.kind == MTH &&
   314                     ((MethodSymbol)location).isStaticOrInstanceInit()) {
   315                 log.error(pos, "already.defined.in.clinit", kindName(sym), sym,
   316                         kindName(sym.location()), kindName(sym.location().enclClass()),
   317                         sym.location().enclClass());
   318             } else {
   319                 log.error(pos, "already.defined", kindName(sym), sym,
   320                         kindName(sym.location()), sym.location());
   321             }
   322         }
   323     }
   325     /** Report array/varargs duplicate declaration
   326      */
   327     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   328         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   329             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   330         }
   331     }
   333 /* ************************************************************************
   334  * duplicate declaration checking
   335  *************************************************************************/
   337     /** Check that variable does not hide variable with same name in
   338      *  immediately enclosing local scope.
   339      *  @param pos           Position for error reporting.
   340      *  @param v             The symbol.
   341      *  @param s             The scope.
   342      */
   343     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   344         if (s.next != null) {
   345             for (Scope.Entry e = s.next.lookup(v.name);
   346                  e.scope != null && e.sym.owner == v.owner;
   347                  e = e.next()) {
   348                 if (e.sym.kind == VAR &&
   349                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   350                     v.name != names.error) {
   351                     duplicateError(pos, e.sym);
   352                     return;
   353                 }
   354             }
   355         }
   356     }
   358     /** Check that a class or interface does not hide a class or
   359      *  interface with same name in immediately enclosing local scope.
   360      *  @param pos           Position for error reporting.
   361      *  @param c             The symbol.
   362      *  @param s             The scope.
   363      */
   364     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   365         if (s.next != null) {
   366             for (Scope.Entry e = s.next.lookup(c.name);
   367                  e.scope != null && e.sym.owner == c.owner;
   368                  e = e.next()) {
   369                 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
   370                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   371                     c.name != names.error) {
   372                     duplicateError(pos, e.sym);
   373                     return;
   374                 }
   375             }
   376         }
   377     }
   379     /** Check that class does not have the same name as one of
   380      *  its enclosing classes, or as a class defined in its enclosing scope.
   381      *  return true if class is unique in its enclosing scope.
   382      *  @param pos           Position for error reporting.
   383      *  @param name          The class name.
   384      *  @param s             The enclosing scope.
   385      */
   386     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   387         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   388             if (e.sym.kind == TYP && e.sym.name != names.error) {
   389                 duplicateError(pos, e.sym);
   390                 return false;
   391             }
   392         }
   393         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   394             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   395                 duplicateError(pos, sym);
   396                 return true;
   397             }
   398         }
   399         return true;
   400     }
   402 /* *************************************************************************
   403  * Class name generation
   404  **************************************************************************/
   406     /** Return name of local class.
   407      *  This is of the form    <enclClass> $ n <classname>
   408      *  where
   409      *    enclClass is the flat name of the enclosing class,
   410      *    classname is the simple name of the local class
   411      */
   412     Name localClassName(ClassSymbol c) {
   413         for (int i=1; ; i++) {
   414             Name flatname = names.
   415                 fromString("" + c.owner.enclClass().flatname +
   416                            syntheticNameChar + i +
   417                            c.name);
   418             if (compiled.get(flatname) == null) return flatname;
   419         }
   420     }
   422 /* *************************************************************************
   423  * Type Checking
   424  **************************************************************************/
   426     /** Check that a given type is assignable to a given proto-type.
   427      *  If it is, return the type, otherwise return errType.
   428      *  @param pos        Position to be used for error reporting.
   429      *  @param found      The type that was found.
   430      *  @param req        The type that was required.
   431      */
   432     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   433         return checkType(pos, found, req, "incompatible.types");
   434     }
   436     Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
   437         if (req.tag == ERROR)
   438             return req;
   439         if (found.tag == FORALL)
   440             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   441         if (req.tag == NONE)
   442             return found;
   443         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   444             return found;
   445         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   446             return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
   447         if (found.isSuperBound()) {
   448             log.error(pos, "assignment.from.super-bound", found);
   449             return types.createErrorType(found);
   450         }
   451         if (req.isExtendsBound()) {
   452             log.error(pos, "assignment.to.extends-bound", req);
   453             return types.createErrorType(found);
   454         }
   455         return typeError(pos, diags.fragment(errKey), found, req);
   456     }
   458     /** Instantiate polymorphic type to some prototype, unless
   459      *  prototype is `anyPoly' in which case polymorphic type
   460      *  is returned unchanged.
   461      */
   462     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
   463         if (pt == Infer.anyPoly && complexInference) {
   464             return t;
   465         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   466             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   467             return instantiatePoly(pos, t, newpt, warn);
   468         } else if (pt.tag == ERROR) {
   469             return pt;
   470         } else {
   471             try {
   472                 return infer.instantiateExpr(t, pt, warn);
   473             } catch (Infer.NoInstanceException ex) {
   474                 if (ex.isAmbiguous) {
   475                     JCDiagnostic d = ex.getDiagnostic();
   476                     log.error(pos,
   477                               "undetermined.type" + (d!=null ? ".1" : ""),
   478                               t, d);
   479                     return types.createErrorType(pt);
   480                 } else {
   481                     JCDiagnostic d = ex.getDiagnostic();
   482                     return typeError(pos,
   483                                      diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   484                                      t, pt);
   485                 }
   486             } catch (Infer.InvalidInstanceException ex) {
   487                 JCDiagnostic d = ex.getDiagnostic();
   488                 log.error(pos, "invalid.inferred.types", t.tvars, d);
   489                 return types.createErrorType(pt);
   490             }
   491         }
   492     }
   494     /** Check that a given type can be cast to a given target type.
   495      *  Return the result of the cast.
   496      *  @param pos        Position to be used for error reporting.
   497      *  @param found      The type that is being cast.
   498      *  @param req        The target type of the cast.
   499      */
   500     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   501         if (found.tag == FORALL) {
   502             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   503             return req;
   504         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   505             return req;
   506         } else {
   507             return typeError(pos,
   508                              diags.fragment("inconvertible.types"),
   509                              found, req);
   510         }
   511     }
   512 //where
   513         /** Is type a type variable, or a (possibly multi-dimensional) array of
   514          *  type variables?
   515          */
   516         boolean isTypeVar(Type t) {
   517             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   518         }
   520     /** Check that a type is within some bounds.
   521      *
   522      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   523      *  type argument.
   524      *  @param pos           Position to be used for error reporting.
   525      *  @param a             The type that should be bounded by bs.
   526      *  @param bs            The bound.
   527      */
   528     private boolean checkExtends(Type a, Type bound) {
   529          if (a.isUnbound()) {
   530              return true;
   531          } else if (a.tag != WILDCARD) {
   532              a = types.upperBound(a);
   533              return types.isSubtype(a, bound);
   534          } else if (a.isExtendsBound()) {
   535              return types.isCastable(bound, types.upperBound(a), Warner.noWarnings);
   536          } else if (a.isSuperBound()) {
   537              return !types.notSoftSubtype(types.lowerBound(a), bound);
   538          }
   539          return true;
   540      }
   542     /** Check that type is different from 'void'.
   543      *  @param pos           Position to be used for error reporting.
   544      *  @param t             The type to be checked.
   545      */
   546     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   547         if (t.tag == VOID) {
   548             log.error(pos, "void.not.allowed.here");
   549             return types.createErrorType(t);
   550         } else {
   551             return t;
   552         }
   553     }
   555     /** Check that type is a class or interface type.
   556      *  @param pos           Position to be used for error reporting.
   557      *  @param t             The type to be checked.
   558      */
   559     Type checkClassType(DiagnosticPosition pos, Type t) {
   560         if (t.tag != CLASS && t.tag != ERROR)
   561             return typeTagError(pos,
   562                                 diags.fragment("type.req.class"),
   563                                 (t.tag == TYPEVAR)
   564                                 ? diags.fragment("type.parameter", t)
   565                                 : t);
   566         else
   567             return t;
   568     }
   570     /** Check that type is a class or interface type.
   571      *  @param pos           Position to be used for error reporting.
   572      *  @param t             The type to be checked.
   573      *  @param noBounds    True if type bounds are illegal here.
   574      */
   575     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   576         t = checkClassType(pos, t);
   577         if (noBounds && t.isParameterized()) {
   578             List<Type> args = t.getTypeArguments();
   579             while (args.nonEmpty()) {
   580                 if (args.head.tag == WILDCARD)
   581                     return typeTagError(pos,
   582                                         diags.fragment("type.req.exact"),
   583                                         args.head);
   584                 args = args.tail;
   585             }
   586         }
   587         return t;
   588     }
   590     /** Check that type is a reifiable class, interface or array type.
   591      *  @param pos           Position to be used for error reporting.
   592      *  @param t             The type to be checked.
   593      */
   594     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   595         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   596             return typeTagError(pos,
   597                                 diags.fragment("type.req.class.array"),
   598                                 t);
   599         } else if (!types.isReifiable(t)) {
   600             log.error(pos, "illegal.generic.type.for.instof");
   601             return types.createErrorType(t);
   602         } else {
   603             return t;
   604         }
   605     }
   607     /** Check that type is a reference type, i.e. a class, interface or array type
   608      *  or a type variable.
   609      *  @param pos           Position to be used for error reporting.
   610      *  @param t             The type to be checked.
   611      */
   612     Type checkRefType(DiagnosticPosition pos, Type t) {
   613         switch (t.tag) {
   614         case CLASS:
   615         case ARRAY:
   616         case TYPEVAR:
   617         case WILDCARD:
   618         case ERROR:
   619             return t;
   620         default:
   621             return typeTagError(pos,
   622                                 diags.fragment("type.req.ref"),
   623                                 t);
   624         }
   625     }
   627     /** Check that each type is a reference type, i.e. a class, interface or array type
   628      *  or a type variable.
   629      *  @param trees         Original trees, used for error reporting.
   630      *  @param types         The types to be checked.
   631      */
   632     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   633         List<JCExpression> tl = trees;
   634         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   635             l.head = checkRefType(tl.head.pos(), l.head);
   636             tl = tl.tail;
   637         }
   638         return types;
   639     }
   641     /** Check that type is a null or reference type.
   642      *  @param pos           Position to be used for error reporting.
   643      *  @param t             The type to be checked.
   644      */
   645     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   646         switch (t.tag) {
   647         case CLASS:
   648         case ARRAY:
   649         case TYPEVAR:
   650         case WILDCARD:
   651         case BOT:
   652         case ERROR:
   653             return t;
   654         default:
   655             return typeTagError(pos,
   656                                 diags.fragment("type.req.ref"),
   657                                 t);
   658         }
   659     }
   661     /** Check that flag set does not contain elements of two conflicting sets. s
   662      *  Return true if it doesn't.
   663      *  @param pos           Position to be used for error reporting.
   664      *  @param flags         The set of flags to be checked.
   665      *  @param set1          Conflicting flags set #1.
   666      *  @param set2          Conflicting flags set #2.
   667      */
   668     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   669         if ((flags & set1) != 0 && (flags & set2) != 0) {
   670             log.error(pos,
   671                       "illegal.combination.of.modifiers",
   672                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   673                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   674             return false;
   675         } else
   676             return true;
   677     }
   679     /** Check that usage of diamond operator is correct (i.e. diamond should not
   680      * be used with non-generic classes or in anonymous class creation expressions)
   681      */
   682     Type checkDiamond(JCNewClass tree, Type t) {
   683         if (!TreeInfo.isDiamond(tree) ||
   684                 t.isErroneous()) {
   685             return checkClassType(tree.clazz.pos(), t, true);
   686         } else if (tree.def != null) {
   687             log.error(tree.clazz.pos(),
   688                     "cant.apply.diamond.1",
   689                     t, diags.fragment("diamond.and.anon.class", t));
   690             return types.createErrorType(t);
   691         } else if (t.tsym.type.getTypeArguments().isEmpty()) {
   692             log.error(tree.clazz.pos(),
   693                 "cant.apply.diamond.1",
   694                 t, diags.fragment("diamond.non.generic", t));
   695             return types.createErrorType(t);
   696         } else if (tree.typeargs != null &&
   697                 tree.typeargs.nonEmpty()) {
   698             log.error(tree.clazz.pos(),
   699                 "cant.apply.diamond.1",
   700                 t, diags.fragment("diamond.and.explicit.params", t));
   701             return types.createErrorType(t);
   702         } else {
   703             return t;
   704         }
   705     }
   707     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   708         MethodSymbol m = tree.sym;
   709         if (!allowSimplifiedVarargs) return;
   710         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   711         Type varargElemType = null;
   712         if (m.isVarArgs()) {
   713             varargElemType = types.elemtype(tree.params.last().type);
   714         }
   715         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   716             if (varargElemType != null) {
   717                 log.error(tree,
   718                         "varargs.invalid.trustme.anno",
   719                         syms.trustMeType.tsym,
   720                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   721             } else {
   722                 log.error(tree,
   723                             "varargs.invalid.trustme.anno",
   724                             syms.trustMeType.tsym,
   725                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   726             }
   727         } else if (hasTrustMeAnno && varargElemType != null &&
   728                             types.isReifiable(varargElemType)) {
   729             warnUnsafeVararg(tree,
   730                             "varargs.redundant.trustme.anno",
   731                             syms.trustMeType.tsym,
   732                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   733         }
   734         else if (!hasTrustMeAnno && varargElemType != null &&
   735                 !types.isReifiable(varargElemType)) {
   736             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   737         }
   738     }
   739     //where
   740         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   741             return (s.flags() & VARARGS) != 0 &&
   742                 (s.isConstructor() ||
   743                     (s.flags() & (STATIC | FINAL)) != 0);
   744         }
   746     /**
   747      * Check that vararg method call is sound
   748      * @param pos Position to be used for error reporting.
   749      * @param argtypes Actual arguments supplied to vararg method.
   750      */
   751     void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
   752         Type argtype = argtypes.last();
   753         if (!types.isReifiable(argtype) &&
   754                 (!allowSimplifiedVarargs ||
   755                 msym.attribute(syms.trustMeType.tsym) == null ||
   756                 !isTrustMeAllowedOnMethod(msym))) {
   757             warnUnchecked(pos,
   758                               "unchecked.generic.array.creation",
   759                               argtype);
   760         }
   761     }
   763     /**
   764      * Check that type 't' is a valid instantiation of a generic class
   765      * (see JLS 4.5)
   766      *
   767      * @param t class type to be checked
   768      * @return true if 't' is well-formed
   769      */
   770     public boolean checkValidGenericType(Type t) {
   771         return firstIncompatibleTypeArg(t) == null;
   772     }
   773     //WHERE
   774         private Type firstIncompatibleTypeArg(Type type) {
   775             List<Type> formals = type.tsym.type.allparams();
   776             List<Type> actuals = type.allparams();
   777             List<Type> args = type.getTypeArguments();
   778             List<Type> forms = type.tsym.type.getTypeArguments();
   779             ListBuffer<Type> bounds_buf = new ListBuffer<Type>();
   781             // For matching pairs of actual argument types `a' and
   782             // formal type parameters with declared bound `b' ...
   783             while (args.nonEmpty() && forms.nonEmpty()) {
   784                 // exact type arguments needs to know their
   785                 // bounds (for upper and lower bound
   786                 // calculations).  So we create new bounds where
   787                 // type-parameters are replaced with actuals argument types.
   788                 bounds_buf.append(types.subst(forms.head.getUpperBound(), formals, actuals));
   789                 args = args.tail;
   790                 forms = forms.tail;
   791             }
   793             args = type.getTypeArguments();
   794             List<Type> tvars_cap = types.substBounds(formals,
   795                                       formals,
   796                                       types.capture(type).allparams());
   797             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   798                 // Let the actual arguments know their bound
   799                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   800                 args = args.tail;
   801                 tvars_cap = tvars_cap.tail;
   802             }
   804             args = type.getTypeArguments();
   805             List<Type> bounds = bounds_buf.toList();
   807             while (args.nonEmpty() && bounds.nonEmpty()) {
   808                 Type actual = args.head;
   809                 if (!isTypeArgErroneous(actual) &&
   810                         !bounds.head.isErroneous() &&
   811                         !checkExtends(actual, bounds.head)) {
   812                     return args.head;
   813                 }
   814                 args = args.tail;
   815                 bounds = bounds.tail;
   816             }
   818             args = type.getTypeArguments();
   819             bounds = bounds_buf.toList();
   821             for (Type arg : types.capture(type).getTypeArguments()) {
   822                 if (arg.tag == TYPEVAR &&
   823                         arg.getUpperBound().isErroneous() &&
   824                         !bounds.head.isErroneous() &&
   825                         !isTypeArgErroneous(args.head)) {
   826                     return args.head;
   827                 }
   828                 bounds = bounds.tail;
   829                 args = args.tail;
   830             }
   832             return null;
   833         }
   834         //where
   835         boolean isTypeArgErroneous(Type t) {
   836             return isTypeArgErroneous.visit(t);
   837         }
   839         Types.UnaryVisitor<Boolean> isTypeArgErroneous = new Types.UnaryVisitor<Boolean>() {
   840             public Boolean visitType(Type t, Void s) {
   841                 return t.isErroneous();
   842             }
   843             @Override
   844             public Boolean visitTypeVar(TypeVar t, Void s) {
   845                 return visit(t.getUpperBound());
   846             }
   847             @Override
   848             public Boolean visitCapturedType(CapturedType t, Void s) {
   849                 return visit(t.getUpperBound()) ||
   850                         visit(t.getLowerBound());
   851             }
   852             @Override
   853             public Boolean visitWildcardType(WildcardType t, Void s) {
   854                 return visit(t.type);
   855             }
   856         };
   858     /** Check that given modifiers are legal for given symbol and
   859      *  return modifiers together with any implicit modififiers for that symbol.
   860      *  Warning: we can't use flags() here since this method
   861      *  is called during class enter, when flags() would cause a premature
   862      *  completion.
   863      *  @param pos           Position to be used for error reporting.
   864      *  @param flags         The set of modifiers given in a definition.
   865      *  @param sym           The defined symbol.
   866      */
   867     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   868         long mask;
   869         long implicit = 0;
   870         switch (sym.kind) {
   871         case VAR:
   872             if (sym.owner.kind != TYP)
   873                 mask = LocalVarFlags;
   874             else if ((sym.owner.flags_field & INTERFACE) != 0)
   875                 mask = implicit = InterfaceVarFlags;
   876             else
   877                 mask = VarFlags;
   878             break;
   879         case MTH:
   880             if (sym.name == names.init) {
   881                 if ((sym.owner.flags_field & ENUM) != 0) {
   882                     // enum constructors cannot be declared public or
   883                     // protected and must be implicitly or explicitly
   884                     // private
   885                     implicit = PRIVATE;
   886                     mask = PRIVATE;
   887                 } else
   888                     mask = ConstructorFlags;
   889             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   890                 mask = implicit = InterfaceMethodFlags;
   891             else {
   892                 mask = MethodFlags;
   893             }
   894             // Imply STRICTFP if owner has STRICTFP set.
   895             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   896               implicit |= sym.owner.flags_field & STRICTFP;
   897             break;
   898         case TYP:
   899             if (sym.isLocal()) {
   900                 mask = LocalClassFlags;
   901                 if (sym.name.isEmpty()) { // Anonymous class
   902                     // Anonymous classes in static methods are themselves static;
   903                     // that's why we admit STATIC here.
   904                     mask |= STATIC;
   905                     // JLS: Anonymous classes are final.
   906                     implicit |= FINAL;
   907                 }
   908                 if ((sym.owner.flags_field & STATIC) == 0 &&
   909                     (flags & ENUM) != 0)
   910                     log.error(pos, "enums.must.be.static");
   911             } else if (sym.owner.kind == TYP) {
   912                 mask = MemberClassFlags;
   913                 if (sym.owner.owner.kind == PCK ||
   914                     (sym.owner.flags_field & STATIC) != 0)
   915                     mask |= STATIC;
   916                 else if ((flags & ENUM) != 0)
   917                     log.error(pos, "enums.must.be.static");
   918                 // Nested interfaces and enums are always STATIC (Spec ???)
   919                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   920             } else {
   921                 mask = ClassFlags;
   922             }
   923             // Interfaces are always ABSTRACT
   924             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   926             if ((flags & ENUM) != 0) {
   927                 // enums can't be declared abstract or final
   928                 mask &= ~(ABSTRACT | FINAL);
   929                 implicit |= implicitEnumFinalFlag(tree);
   930             }
   931             // Imply STRICTFP if owner has STRICTFP set.
   932             implicit |= sym.owner.flags_field & STRICTFP;
   933             break;
   934         default:
   935             throw new AssertionError();
   936         }
   937         long illegal = flags & StandardFlags & ~mask;
   938         if (illegal != 0) {
   939             if ((illegal & INTERFACE) != 0) {
   940                 log.error(pos, "intf.not.allowed.here");
   941                 mask |= INTERFACE;
   942             }
   943             else {
   944                 log.error(pos,
   945                           "mod.not.allowed.here", asFlagSet(illegal));
   946             }
   947         }
   948         else if ((sym.kind == TYP ||
   949                   // ISSUE: Disallowing abstract&private is no longer appropriate
   950                   // in the presence of inner classes. Should it be deleted here?
   951                   checkDisjoint(pos, flags,
   952                                 ABSTRACT,
   953                                 PRIVATE | STATIC))
   954                  &&
   955                  checkDisjoint(pos, flags,
   956                                ABSTRACT | INTERFACE,
   957                                FINAL | NATIVE | SYNCHRONIZED)
   958                  &&
   959                  checkDisjoint(pos, flags,
   960                                PUBLIC,
   961                                PRIVATE | PROTECTED)
   962                  &&
   963                  checkDisjoint(pos, flags,
   964                                PRIVATE,
   965                                PUBLIC | PROTECTED)
   966                  &&
   967                  checkDisjoint(pos, flags,
   968                                FINAL,
   969                                VOLATILE)
   970                  &&
   971                  (sym.kind == TYP ||
   972                   checkDisjoint(pos, flags,
   973                                 ABSTRACT | NATIVE,
   974                                 STRICTFP))) {
   975             // skip
   976         }
   977         return flags & (mask | ~StandardFlags) | implicit;
   978     }
   981     /** Determine if this enum should be implicitly final.
   982      *
   983      *  If the enum has no specialized enum contants, it is final.
   984      *
   985      *  If the enum does have specialized enum contants, it is
   986      *  <i>not</i> final.
   987      */
   988     private long implicitEnumFinalFlag(JCTree tree) {
   989         if (!tree.hasTag(CLASSDEF)) return 0;
   990         class SpecialTreeVisitor extends JCTree.Visitor {
   991             boolean specialized;
   992             SpecialTreeVisitor() {
   993                 this.specialized = false;
   994             };
   996             @Override
   997             public void visitTree(JCTree tree) { /* no-op */ }
   999             @Override
  1000             public void visitVarDef(JCVariableDecl tree) {
  1001                 if ((tree.mods.flags & ENUM) != 0) {
  1002                     if (tree.init instanceof JCNewClass &&
  1003                         ((JCNewClass) tree.init).def != null) {
  1004                         specialized = true;
  1010         SpecialTreeVisitor sts = new SpecialTreeVisitor();
  1011         JCClassDecl cdef = (JCClassDecl) tree;
  1012         for (JCTree defs: cdef.defs) {
  1013             defs.accept(sts);
  1014             if (sts.specialized) return 0;
  1016         return FINAL;
  1019 /* *************************************************************************
  1020  * Type Validation
  1021  **************************************************************************/
  1023     /** Validate a type expression. That is,
  1024      *  check that all type arguments of a parametric type are within
  1025      *  their bounds. This must be done in a second phase after type attributon
  1026      *  since a class might have a subclass as type parameter bound. E.g:
  1028      *  class B<A extends C> { ... }
  1029      *  class C extends B<C> { ... }
  1031      *  and we can't make sure that the bound is already attributed because
  1032      *  of possible cycles.
  1034      * Visitor method: Validate a type expression, if it is not null, catching
  1035      *  and reporting any completion failures.
  1036      */
  1037     void validate(JCTree tree, Env<AttrContext> env) {
  1038         validate(tree, env, true);
  1040     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1041         new Validator(env).validateTree(tree, checkRaw, true);
  1044     /** Visitor method: Validate a list of type expressions.
  1045      */
  1046     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1047         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1048             validate(l.head, env);
  1051     /** A visitor class for type validation.
  1052      */
  1053     class Validator extends JCTree.Visitor {
  1055         boolean isOuter;
  1056         Env<AttrContext> env;
  1058         Validator(Env<AttrContext> env) {
  1059             this.env = env;
  1062         @Override
  1063         public void visitTypeArray(JCArrayTypeTree tree) {
  1064             tree.elemtype.accept(this);
  1067         @Override
  1068         public void visitTypeApply(JCTypeApply tree) {
  1069             if (tree.type.tag == CLASS) {
  1070                 List<JCExpression> args = tree.arguments;
  1071                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1073                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1074                 if (incompatibleArg != null) {
  1075                     for (JCTree arg : tree.arguments) {
  1076                         if (arg.type == incompatibleArg) {
  1077                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1079                         forms = forms.tail;
  1083                 forms = tree.type.tsym.type.getTypeArguments();
  1085                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1087                 // For matching pairs of actual argument types `a' and
  1088                 // formal type parameters with declared bound `b' ...
  1089                 while (args.nonEmpty() && forms.nonEmpty()) {
  1090                     validateTree(args.head,
  1091                             !(isOuter && is_java_lang_Class),
  1092                             false);
  1093                     args = args.tail;
  1094                     forms = forms.tail;
  1097                 // Check that this type is either fully parameterized, or
  1098                 // not parameterized at all.
  1099                 if (tree.type.getEnclosingType().isRaw())
  1100                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1101                 if (tree.clazz.hasTag(SELECT))
  1102                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1106         @Override
  1107         public void visitTypeParameter(JCTypeParameter tree) {
  1108             validateTrees(tree.bounds, true, isOuter);
  1109             checkClassBounds(tree.pos(), tree.type);
  1112         @Override
  1113         public void visitWildcard(JCWildcard tree) {
  1114             if (tree.inner != null)
  1115                 validateTree(tree.inner, true, isOuter);
  1118         @Override
  1119         public void visitSelect(JCFieldAccess tree) {
  1120             if (tree.type.tag == CLASS) {
  1121                 visitSelectInternal(tree);
  1123                 // Check that this type is either fully parameterized, or
  1124                 // not parameterized at all.
  1125                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1126                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1130         public void visitSelectInternal(JCFieldAccess tree) {
  1131             if (tree.type.tsym.isStatic() &&
  1132                 tree.selected.type.isParameterized()) {
  1133                 // The enclosing type is not a class, so we are
  1134                 // looking at a static member type.  However, the
  1135                 // qualifying expression is parameterized.
  1136                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1137             } else {
  1138                 // otherwise validate the rest of the expression
  1139                 tree.selected.accept(this);
  1143         /** Default visitor method: do nothing.
  1144          */
  1145         @Override
  1146         public void visitTree(JCTree tree) {
  1149         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1150             try {
  1151                 if (tree != null) {
  1152                     this.isOuter = isOuter;
  1153                     tree.accept(this);
  1154                     if (checkRaw)
  1155                         checkRaw(tree, env);
  1157             } catch (CompletionFailure ex) {
  1158                 completionError(tree.pos(), ex);
  1162         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1163             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1164                 validateTree(l.head, checkRaw, isOuter);
  1167         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1168             if (lint.isEnabled(LintCategory.RAW) &&
  1169                 tree.type.tag == CLASS &&
  1170                 !TreeInfo.isDiamond(tree) &&
  1171                 !withinAnonConstr(env) &&
  1172                 tree.type.isRaw()) {
  1173                 log.warning(LintCategory.RAW,
  1174                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1178         boolean withinAnonConstr(Env<AttrContext> env) {
  1179             return env.enclClass.name.isEmpty() &&
  1180                     env.enclMethod != null && env.enclMethod.name == names.init;
  1184 /* *************************************************************************
  1185  * Exception checking
  1186  **************************************************************************/
  1188     /* The following methods treat classes as sets that contain
  1189      * the class itself and all their subclasses
  1190      */
  1192     /** Is given type a subtype of some of the types in given list?
  1193      */
  1194     boolean subset(Type t, List<Type> ts) {
  1195         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1196             if (types.isSubtype(t, l.head)) return true;
  1197         return false;
  1200     /** Is given type a subtype or supertype of
  1201      *  some of the types in given list?
  1202      */
  1203     boolean intersects(Type t, List<Type> ts) {
  1204         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1205             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1206         return false;
  1209     /** Add type set to given type list, unless it is a subclass of some class
  1210      *  in the list.
  1211      */
  1212     List<Type> incl(Type t, List<Type> ts) {
  1213         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1216     /** Remove type set from type set list.
  1217      */
  1218     List<Type> excl(Type t, List<Type> ts) {
  1219         if (ts.isEmpty()) {
  1220             return ts;
  1221         } else {
  1222             List<Type> ts1 = excl(t, ts.tail);
  1223             if (types.isSubtype(ts.head, t)) return ts1;
  1224             else if (ts1 == ts.tail) return ts;
  1225             else return ts1.prepend(ts.head);
  1229     /** Form the union of two type set lists.
  1230      */
  1231     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1232         List<Type> ts = ts1;
  1233         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1234             ts = incl(l.head, ts);
  1235         return ts;
  1238     /** Form the difference of two type lists.
  1239      */
  1240     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1241         List<Type> ts = ts1;
  1242         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1243             ts = excl(l.head, ts);
  1244         return ts;
  1247     /** Form the intersection of two type lists.
  1248      */
  1249     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1250         List<Type> ts = List.nil();
  1251         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1252             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1253         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1254             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1255         return ts;
  1258     /** Is exc an exception symbol that need not be declared?
  1259      */
  1260     boolean isUnchecked(ClassSymbol exc) {
  1261         return
  1262             exc.kind == ERR ||
  1263             exc.isSubClass(syms.errorType.tsym, types) ||
  1264             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1267     /** Is exc an exception type that need not be declared?
  1268      */
  1269     boolean isUnchecked(Type exc) {
  1270         return
  1271             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1272             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1273             exc.tag == BOT;
  1276     /** Same, but handling completion failures.
  1277      */
  1278     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1279         try {
  1280             return isUnchecked(exc);
  1281         } catch (CompletionFailure ex) {
  1282             completionError(pos, ex);
  1283             return true;
  1287     /** Is exc handled by given exception list?
  1288      */
  1289     boolean isHandled(Type exc, List<Type> handled) {
  1290         return isUnchecked(exc) || subset(exc, handled);
  1293     /** Return all exceptions in thrown list that are not in handled list.
  1294      *  @param thrown     The list of thrown exceptions.
  1295      *  @param handled    The list of handled exceptions.
  1296      */
  1297     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1298         List<Type> unhandled = List.nil();
  1299         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1300             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1301         return unhandled;
  1304 /* *************************************************************************
  1305  * Overriding/Implementation checking
  1306  **************************************************************************/
  1308     /** The level of access protection given by a flag set,
  1309      *  where PRIVATE is highest and PUBLIC is lowest.
  1310      */
  1311     static int protection(long flags) {
  1312         switch ((short)(flags & AccessFlags)) {
  1313         case PRIVATE: return 3;
  1314         case PROTECTED: return 1;
  1315         default:
  1316         case PUBLIC: return 0;
  1317         case 0: return 2;
  1321     /** A customized "cannot override" error message.
  1322      *  @param m      The overriding method.
  1323      *  @param other  The overridden method.
  1324      *  @return       An internationalized string.
  1325      */
  1326     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1327         String key;
  1328         if ((other.owner.flags() & INTERFACE) == 0)
  1329             key = "cant.override";
  1330         else if ((m.owner.flags() & INTERFACE) == 0)
  1331             key = "cant.implement";
  1332         else
  1333             key = "clashes.with";
  1334         return diags.fragment(key, m, m.location(), other, other.location());
  1337     /** A customized "override" warning message.
  1338      *  @param m      The overriding method.
  1339      *  @param other  The overridden method.
  1340      *  @return       An internationalized string.
  1341      */
  1342     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1343         String key;
  1344         if ((other.owner.flags() & INTERFACE) == 0)
  1345             key = "unchecked.override";
  1346         else if ((m.owner.flags() & INTERFACE) == 0)
  1347             key = "unchecked.implement";
  1348         else
  1349             key = "unchecked.clash.with";
  1350         return diags.fragment(key, m, m.location(), other, other.location());
  1353     /** A customized "override" warning message.
  1354      *  @param m      The overriding method.
  1355      *  @param other  The overridden method.
  1356      *  @return       An internationalized string.
  1357      */
  1358     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1359         String key;
  1360         if ((other.owner.flags() & INTERFACE) == 0)
  1361             key = "varargs.override";
  1362         else  if ((m.owner.flags() & INTERFACE) == 0)
  1363             key = "varargs.implement";
  1364         else
  1365             key = "varargs.clash.with";
  1366         return diags.fragment(key, m, m.location(), other, other.location());
  1369     /** Check that this method conforms with overridden method 'other'.
  1370      *  where `origin' is the class where checking started.
  1371      *  Complications:
  1372      *  (1) Do not check overriding of synthetic methods
  1373      *      (reason: they might be final).
  1374      *      todo: check whether this is still necessary.
  1375      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1376      *      than the method it implements. Augment the proxy methods with the
  1377      *      undeclared exceptions in this case.
  1378      *  (3) When generics are enabled, admit the case where an interface proxy
  1379      *      has a result type
  1380      *      extended by the result type of the method it implements.
  1381      *      Change the proxies result type to the smaller type in this case.
  1383      *  @param tree         The tree from which positions
  1384      *                      are extracted for errors.
  1385      *  @param m            The overriding method.
  1386      *  @param other        The overridden method.
  1387      *  @param origin       The class of which the overriding method
  1388      *                      is a member.
  1389      */
  1390     void checkOverride(JCTree tree,
  1391                        MethodSymbol m,
  1392                        MethodSymbol other,
  1393                        ClassSymbol origin) {
  1394         // Don't check overriding of synthetic methods or by bridge methods.
  1395         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1396             return;
  1399         // Error if static method overrides instance method (JLS 8.4.6.2).
  1400         if ((m.flags() & STATIC) != 0 &&
  1401                    (other.flags() & STATIC) == 0) {
  1402             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1403                       cannotOverride(m, other));
  1404             return;
  1407         // Error if instance method overrides static or final
  1408         // method (JLS 8.4.6.1).
  1409         if ((other.flags() & FINAL) != 0 ||
  1410                  (m.flags() & STATIC) == 0 &&
  1411                  (other.flags() & STATIC) != 0) {
  1412             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1413                       cannotOverride(m, other),
  1414                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1415             return;
  1418         if ((m.owner.flags() & ANNOTATION) != 0) {
  1419             // handled in validateAnnotationMethod
  1420             return;
  1423         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1424         if ((origin.flags() & INTERFACE) == 0 &&
  1425                  protection(m.flags()) > protection(other.flags())) {
  1426             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1427                       cannotOverride(m, other),
  1428                       other.flags() == 0 ?
  1429                           Flag.PACKAGE :
  1430                           asFlagSet(other.flags() & AccessFlags));
  1431             return;
  1434         Type mt = types.memberType(origin.type, m);
  1435         Type ot = types.memberType(origin.type, other);
  1436         // Error if overriding result type is different
  1437         // (or, in the case of generics mode, not a subtype) of
  1438         // overridden result type. We have to rename any type parameters
  1439         // before comparing types.
  1440         List<Type> mtvars = mt.getTypeArguments();
  1441         List<Type> otvars = ot.getTypeArguments();
  1442         Type mtres = mt.getReturnType();
  1443         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1445         overrideWarner.clear();
  1446         boolean resultTypesOK =
  1447             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1448         if (!resultTypesOK) {
  1449             if (!allowCovariantReturns &&
  1450                 m.owner != origin &&
  1451                 m.owner.isSubClass(other.owner, types)) {
  1452                 // allow limited interoperability with covariant returns
  1453             } else {
  1454                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1455                           "override.incompatible.ret",
  1456                           cannotOverride(m, other),
  1457                           mtres, otres);
  1458                 return;
  1460         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1461             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1462                     "override.unchecked.ret",
  1463                     uncheckedOverrides(m, other),
  1464                     mtres, otres);
  1467         // Error if overriding method throws an exception not reported
  1468         // by overridden method.
  1469         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1470         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1471         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1472         if (unhandledErased.nonEmpty()) {
  1473             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1474                       "override.meth.doesnt.throw",
  1475                       cannotOverride(m, other),
  1476                       unhandledUnerased.head);
  1477             return;
  1479         else if (unhandledUnerased.nonEmpty()) {
  1480             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1481                           "override.unchecked.thrown",
  1482                          cannotOverride(m, other),
  1483                          unhandledUnerased.head);
  1484             return;
  1487         // Optional warning if varargs don't agree
  1488         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1489             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1490             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1491                         ((m.flags() & Flags.VARARGS) != 0)
  1492                         ? "override.varargs.missing"
  1493                         : "override.varargs.extra",
  1494                         varargsOverrides(m, other));
  1497         // Warn if instance method overrides bridge method (compiler spec ??)
  1498         if ((other.flags() & BRIDGE) != 0) {
  1499             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1500                         uncheckedOverrides(m, other));
  1503         // Warn if a deprecated method overridden by a non-deprecated one.
  1504         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1505             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1508     // where
  1509         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1510             // If the method, m, is defined in an interface, then ignore the issue if the method
  1511             // is only inherited via a supertype and also implemented in the supertype,
  1512             // because in that case, we will rediscover the issue when examining the method
  1513             // in the supertype.
  1514             // If the method, m, is not defined in an interface, then the only time we need to
  1515             // address the issue is when the method is the supertype implemementation: any other
  1516             // case, we will have dealt with when examining the supertype classes
  1517             ClassSymbol mc = m.enclClass();
  1518             Type st = types.supertype(origin.type);
  1519             if (st.tag != CLASS)
  1520                 return true;
  1521             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1523             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1524                 List<Type> intfs = types.interfaces(origin.type);
  1525                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1527             else
  1528                 return (stimpl != m);
  1532     // used to check if there were any unchecked conversions
  1533     Warner overrideWarner = new Warner();
  1535     /** Check that a class does not inherit two concrete methods
  1536      *  with the same signature.
  1537      *  @param pos          Position to be used for error reporting.
  1538      *  @param site         The class type to be checked.
  1539      */
  1540     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1541         Type sup = types.supertype(site);
  1542         if (sup.tag != CLASS) return;
  1544         for (Type t1 = sup;
  1545              t1.tsym.type.isParameterized();
  1546              t1 = types.supertype(t1)) {
  1547             for (Scope.Entry e1 = t1.tsym.members().elems;
  1548                  e1 != null;
  1549                  e1 = e1.sibling) {
  1550                 Symbol s1 = e1.sym;
  1551                 if (s1.kind != MTH ||
  1552                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1553                     !s1.isInheritedIn(site.tsym, types) ||
  1554                     ((MethodSymbol)s1).implementation(site.tsym,
  1555                                                       types,
  1556                                                       true) != s1)
  1557                     continue;
  1558                 Type st1 = types.memberType(t1, s1);
  1559                 int s1ArgsLength = st1.getParameterTypes().length();
  1560                 if (st1 == s1.type) continue;
  1562                 for (Type t2 = sup;
  1563                      t2.tag == CLASS;
  1564                      t2 = types.supertype(t2)) {
  1565                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1566                          e2.scope != null;
  1567                          e2 = e2.next()) {
  1568                         Symbol s2 = e2.sym;
  1569                         if (s2 == s1 ||
  1570                             s2.kind != MTH ||
  1571                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1572                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1573                             !s2.isInheritedIn(site.tsym, types) ||
  1574                             ((MethodSymbol)s2).implementation(site.tsym,
  1575                                                               types,
  1576                                                               true) != s2)
  1577                             continue;
  1578                         Type st2 = types.memberType(t2, s2);
  1579                         if (types.overrideEquivalent(st1, st2))
  1580                             log.error(pos, "concrete.inheritance.conflict",
  1581                                       s1, t1, s2, t2, sup);
  1588     /** Check that classes (or interfaces) do not each define an abstract
  1589      *  method with same name and arguments but incompatible return types.
  1590      *  @param pos          Position to be used for error reporting.
  1591      *  @param t1           The first argument type.
  1592      *  @param t2           The second argument type.
  1593      */
  1594     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1595                                             Type t1,
  1596                                             Type t2) {
  1597         return checkCompatibleAbstracts(pos, t1, t2,
  1598                                         types.makeCompoundType(t1, t2));
  1601     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1602                                             Type t1,
  1603                                             Type t2,
  1604                                             Type site) {
  1605         return firstIncompatibility(pos, t1, t2, site) == null;
  1608     /** Return the first method which is defined with same args
  1609      *  but different return types in two given interfaces, or null if none
  1610      *  exists.
  1611      *  @param t1     The first type.
  1612      *  @param t2     The second type.
  1613      *  @param site   The most derived type.
  1614      *  @returns symbol from t2 that conflicts with one in t1.
  1615      */
  1616     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1617         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1618         closure(t1, interfaces1);
  1619         Map<TypeSymbol,Type> interfaces2;
  1620         if (t1 == t2)
  1621             interfaces2 = interfaces1;
  1622         else
  1623             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1625         for (Type t3 : interfaces1.values()) {
  1626             for (Type t4 : interfaces2.values()) {
  1627                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1628                 if (s != null) return s;
  1631         return null;
  1634     /** Compute all the supertypes of t, indexed by type symbol. */
  1635     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1636         if (t.tag != CLASS) return;
  1637         if (typeMap.put(t.tsym, t) == null) {
  1638             closure(types.supertype(t), typeMap);
  1639             for (Type i : types.interfaces(t))
  1640                 closure(i, typeMap);
  1644     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1645     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1646         if (t.tag != CLASS) return;
  1647         if (typesSkip.get(t.tsym) != null) return;
  1648         if (typeMap.put(t.tsym, t) == null) {
  1649             closure(types.supertype(t), typesSkip, typeMap);
  1650             for (Type i : types.interfaces(t))
  1651                 closure(i, typesSkip, typeMap);
  1655     /** Return the first method in t2 that conflicts with a method from t1. */
  1656     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1657         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1658             Symbol s1 = e1.sym;
  1659             Type st1 = null;
  1660             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1661             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1662             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1663             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1664                 Symbol s2 = e2.sym;
  1665                 if (s1 == s2) continue;
  1666                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1667                 if (st1 == null) st1 = types.memberType(t1, s1);
  1668                 Type st2 = types.memberType(t2, s2);
  1669                 if (types.overrideEquivalent(st1, st2)) {
  1670                     List<Type> tvars1 = st1.getTypeArguments();
  1671                     List<Type> tvars2 = st2.getTypeArguments();
  1672                     Type rt1 = st1.getReturnType();
  1673                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1674                     boolean compat =
  1675                         types.isSameType(rt1, rt2) ||
  1676                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1677                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1678                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1679                          checkCommonOverriderIn(s1,s2,site);
  1680                     if (!compat) {
  1681                         log.error(pos, "types.incompatible.diff.ret",
  1682                             t1, t2, s2.name +
  1683                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1684                         return s2;
  1686                 } else if (checkNameClash((ClassSymbol)site.tsym, s1, s2) &&
  1687                         !checkCommonOverriderIn(s1, s2, site)) {
  1688                     log.error(pos,
  1689                             "name.clash.same.erasure.no.override",
  1690                             s1, s1.location(),
  1691                             s2, s2.location());
  1692                     return s2;
  1696         return null;
  1698     //WHERE
  1699     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1700         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1701         Type st1 = types.memberType(site, s1);
  1702         Type st2 = types.memberType(site, s2);
  1703         closure(site, supertypes);
  1704         for (Type t : supertypes.values()) {
  1705             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1706                 Symbol s3 = e.sym;
  1707                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1708                 Type st3 = types.memberType(site,s3);
  1709                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1710                     if (s3.owner == site.tsym) {
  1711                         return true;
  1713                     List<Type> tvars1 = st1.getTypeArguments();
  1714                     List<Type> tvars2 = st2.getTypeArguments();
  1715                     List<Type> tvars3 = st3.getTypeArguments();
  1716                     Type rt1 = st1.getReturnType();
  1717                     Type rt2 = st2.getReturnType();
  1718                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1719                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1720                     boolean compat =
  1721                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1722                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1723                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1724                     if (compat)
  1725                         return true;
  1729         return false;
  1732     /** Check that a given method conforms with any method it overrides.
  1733      *  @param tree         The tree from which positions are extracted
  1734      *                      for errors.
  1735      *  @param m            The overriding method.
  1736      */
  1737     void checkOverride(JCTree tree, MethodSymbol m) {
  1738         ClassSymbol origin = (ClassSymbol)m.owner;
  1739         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1740             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1741                 log.error(tree.pos(), "enum.no.finalize");
  1742                 return;
  1744         for (Type t = origin.type; t.tag == CLASS;
  1745              t = types.supertype(t)) {
  1746             if (t != origin.type) {
  1747                 checkOverride(tree, t, origin, m);
  1749             for (Type t2 : types.interfaces(t)) {
  1750                 checkOverride(tree, t2, origin, m);
  1755     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1756         TypeSymbol c = site.tsym;
  1757         Scope.Entry e = c.members().lookup(m.name);
  1758         while (e.scope != null) {
  1759             if (m.overrides(e.sym, origin, types, false)) {
  1760                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1761                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1764             e = e.next();
  1768     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1769         ClashFilter cf = new ClashFilter(origin.type);
  1770         return (cf.accepts(s1) &&
  1771                 cf.accepts(s2) &&
  1772                 types.hasSameArgs(s1.erasure(types), s2.erasure(types)));
  1776     /** Check that all abstract members of given class have definitions.
  1777      *  @param pos          Position to be used for error reporting.
  1778      *  @param c            The class.
  1779      */
  1780     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1781         try {
  1782             MethodSymbol undef = firstUndef(c, c);
  1783             if (undef != null) {
  1784                 if ((c.flags() & ENUM) != 0 &&
  1785                     types.supertype(c.type).tsym == syms.enumSym &&
  1786                     (c.flags() & FINAL) == 0) {
  1787                     // add the ABSTRACT flag to an enum
  1788                     c.flags_field |= ABSTRACT;
  1789                 } else {
  1790                     MethodSymbol undef1 =
  1791                         new MethodSymbol(undef.flags(), undef.name,
  1792                                          types.memberType(c.type, undef), undef.owner);
  1793                     log.error(pos, "does.not.override.abstract",
  1794                               c, undef1, undef1.location());
  1797         } catch (CompletionFailure ex) {
  1798             completionError(pos, ex);
  1801 //where
  1802         /** Return first abstract member of class `c' that is not defined
  1803          *  in `impl', null if there is none.
  1804          */
  1805         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1806             MethodSymbol undef = null;
  1807             // Do not bother to search in classes that are not abstract,
  1808             // since they cannot have abstract members.
  1809             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1810                 Scope s = c.members();
  1811                 for (Scope.Entry e = s.elems;
  1812                      undef == null && e != null;
  1813                      e = e.sibling) {
  1814                     if (e.sym.kind == MTH &&
  1815                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1816                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1817                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1818                         if (implmeth == null || implmeth == absmeth)
  1819                             undef = absmeth;
  1822                 if (undef == null) {
  1823                     Type st = types.supertype(c.type);
  1824                     if (st.tag == CLASS)
  1825                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1827                 for (List<Type> l = types.interfaces(c.type);
  1828                      undef == null && l.nonEmpty();
  1829                      l = l.tail) {
  1830                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1833             return undef;
  1836     void checkNonCyclicDecl(JCClassDecl tree) {
  1837         CycleChecker cc = new CycleChecker();
  1838         cc.scan(tree);
  1839         if (!cc.errorFound && !cc.partialCheck) {
  1840             tree.sym.flags_field |= ACYCLIC;
  1844     class CycleChecker extends TreeScanner {
  1846         List<Symbol> seenClasses = List.nil();
  1847         boolean errorFound = false;
  1848         boolean partialCheck = false;
  1850         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  1851             if (sym != null && sym.kind == TYP) {
  1852                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  1853                 if (classEnv != null) {
  1854                     DiagnosticSource prevSource = log.currentSource();
  1855                     try {
  1856                         log.useSource(classEnv.toplevel.sourcefile);
  1857                         scan(classEnv.tree);
  1859                     finally {
  1860                         log.useSource(prevSource.getFile());
  1862                 } else if (sym.kind == TYP) {
  1863                     checkClass(pos, sym, List.<JCTree>nil());
  1865             } else {
  1866                 //not completed yet
  1867                 partialCheck = true;
  1871         @Override
  1872         public void visitSelect(JCFieldAccess tree) {
  1873             super.visitSelect(tree);
  1874             checkSymbol(tree.pos(), tree.sym);
  1877         @Override
  1878         public void visitIdent(JCIdent tree) {
  1879             checkSymbol(tree.pos(), tree.sym);
  1882         @Override
  1883         public void visitTypeApply(JCTypeApply tree) {
  1884             scan(tree.clazz);
  1887         @Override
  1888         public void visitTypeArray(JCArrayTypeTree tree) {
  1889             scan(tree.elemtype);
  1892         @Override
  1893         public void visitClassDef(JCClassDecl tree) {
  1894             List<JCTree> supertypes = List.nil();
  1895             if (tree.getExtendsClause() != null) {
  1896                 supertypes = supertypes.prepend(tree.getExtendsClause());
  1898             if (tree.getImplementsClause() != null) {
  1899                 for (JCTree intf : tree.getImplementsClause()) {
  1900                     supertypes = supertypes.prepend(intf);
  1903             checkClass(tree.pos(), tree.sym, supertypes);
  1906         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  1907             if ((c.flags_field & ACYCLIC) != 0)
  1908                 return;
  1909             if (seenClasses.contains(c)) {
  1910                 errorFound = true;
  1911                 noteCyclic(pos, (ClassSymbol)c);
  1912             } else if (!c.type.isErroneous()) {
  1913                 try {
  1914                     seenClasses = seenClasses.prepend(c);
  1915                     if (c.type.tag == CLASS) {
  1916                         if (supertypes.nonEmpty()) {
  1917                             scan(supertypes);
  1919                         else {
  1920                             ClassType ct = (ClassType)c.type;
  1921                             if (ct.supertype_field == null ||
  1922                                     ct.interfaces_field == null) {
  1923                                 //not completed yet
  1924                                 partialCheck = true;
  1925                                 return;
  1927                             checkSymbol(pos, ct.supertype_field.tsym);
  1928                             for (Type intf : ct.interfaces_field) {
  1929                                 checkSymbol(pos, intf.tsym);
  1932                         if (c.owner.kind == TYP) {
  1933                             checkSymbol(pos, c.owner);
  1936                 } finally {
  1937                     seenClasses = seenClasses.tail;
  1943     /** Check for cyclic references. Issue an error if the
  1944      *  symbol of the type referred to has a LOCKED flag set.
  1946      *  @param pos      Position to be used for error reporting.
  1947      *  @param t        The type referred to.
  1948      */
  1949     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1950         checkNonCyclicInternal(pos, t);
  1954     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1955         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1958     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1959         final TypeVar tv;
  1960         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1961             return;
  1962         if (seen.contains(t)) {
  1963             tv = (TypeVar)t;
  1964             tv.bound = types.createErrorType(t);
  1965             log.error(pos, "cyclic.inheritance", t);
  1966         } else if (t.tag == TYPEVAR) {
  1967             tv = (TypeVar)t;
  1968             seen = seen.prepend(tv);
  1969             for (Type b : types.getBounds(tv))
  1970                 checkNonCyclic1(pos, b, seen);
  1974     /** Check for cyclic references. Issue an error if the
  1975      *  symbol of the type referred to has a LOCKED flag set.
  1977      *  @param pos      Position to be used for error reporting.
  1978      *  @param t        The type referred to.
  1979      *  @returns        True if the check completed on all attributed classes
  1980      */
  1981     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1982         boolean complete = true; // was the check complete?
  1983         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1984         Symbol c = t.tsym;
  1985         if ((c.flags_field & ACYCLIC) != 0) return true;
  1987         if ((c.flags_field & LOCKED) != 0) {
  1988             noteCyclic(pos, (ClassSymbol)c);
  1989         } else if (!c.type.isErroneous()) {
  1990             try {
  1991                 c.flags_field |= LOCKED;
  1992                 if (c.type.tag == CLASS) {
  1993                     ClassType clazz = (ClassType)c.type;
  1994                     if (clazz.interfaces_field != null)
  1995                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1996                             complete &= checkNonCyclicInternal(pos, l.head);
  1997                     if (clazz.supertype_field != null) {
  1998                         Type st = clazz.supertype_field;
  1999                         if (st != null && st.tag == CLASS)
  2000                             complete &= checkNonCyclicInternal(pos, st);
  2002                     if (c.owner.kind == TYP)
  2003                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  2005             } finally {
  2006                 c.flags_field &= ~LOCKED;
  2009         if (complete)
  2010             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  2011         if (complete) c.flags_field |= ACYCLIC;
  2012         return complete;
  2015     /** Note that we found an inheritance cycle. */
  2016     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  2017         log.error(pos, "cyclic.inheritance", c);
  2018         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  2019             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  2020         Type st = types.supertype(c.type);
  2021         if (st.tag == CLASS)
  2022             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2023         c.type = types.createErrorType(c, c.type);
  2024         c.flags_field |= ACYCLIC;
  2027     /** Check that all methods which implement some
  2028      *  method conform to the method they implement.
  2029      *  @param tree         The class definition whose members are checked.
  2030      */
  2031     void checkImplementations(JCClassDecl tree) {
  2032         checkImplementations(tree, tree.sym);
  2034 //where
  2035         /** Check that all methods which implement some
  2036          *  method in `ic' conform to the method they implement.
  2037          */
  2038         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  2039             ClassSymbol origin = tree.sym;
  2040             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2041                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2042                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2043                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2044                         if (e.sym.kind == MTH &&
  2045                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2046                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2047                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2048                             if (implmeth != null && implmeth != absmeth &&
  2049                                 (implmeth.owner.flags() & INTERFACE) ==
  2050                                 (origin.flags() & INTERFACE)) {
  2051                                 // don't check if implmeth is in a class, yet
  2052                                 // origin is an interface. This case arises only
  2053                                 // if implmeth is declared in Object. The reason is
  2054                                 // that interfaces really don't inherit from
  2055                                 // Object it's just that the compiler represents
  2056                                 // things that way.
  2057                                 checkOverride(tree, implmeth, absmeth, origin);
  2065     /** Check that all abstract methods implemented by a class are
  2066      *  mutually compatible.
  2067      *  @param pos          Position to be used for error reporting.
  2068      *  @param c            The class whose interfaces are checked.
  2069      */
  2070     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2071         List<Type> supertypes = types.interfaces(c);
  2072         Type supertype = types.supertype(c);
  2073         if (supertype.tag == CLASS &&
  2074             (supertype.tsym.flags() & ABSTRACT) != 0)
  2075             supertypes = supertypes.prepend(supertype);
  2076         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2077             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2078                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2079                 return;
  2080             for (List<Type> m = supertypes; m != l; m = m.tail)
  2081                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2082                     return;
  2084         checkCompatibleConcretes(pos, c);
  2087     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2088         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2089             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2090                 // VM allows methods and variables with differing types
  2091                 if (sym.kind == e.sym.kind &&
  2092                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2093                     sym != e.sym &&
  2094                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2095                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2096                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2097                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2098                     return;
  2104     /** Check that all non-override equivalent methods accessible from 'site'
  2105      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2107      *  @param pos  Position to be used for error reporting.
  2108      *  @param site The class whose methods are checked.
  2109      *  @param sym  The method symbol to be checked.
  2110      */
  2111     void checkOverrideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2112          ClashFilter cf = new ClashFilter(site);
  2113         //for each method m1 that is overridden (directly or indirectly)
  2114         //by method 'sym' in 'site'...
  2115         for (Symbol m1 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2116             if (!sym.overrides(m1, site.tsym, types, false)) continue;
  2117              //...check each method m2 that is a member of 'site'
  2118              for (Symbol m2 : types.membersClosure(site, false).getElementsByName(sym.name, cf)) {
  2119                 if (m2 == m1) continue;
  2120                 //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2121                 //a member of 'site') and (ii) m1 has the same erasure as m2, issue an error
  2122                 if (!types.isSubSignature(sym.type, types.memberType(site, m2), false) &&
  2123                         types.hasSameArgs(m2.erasure(types), m1.erasure(types))) {
  2124                     sym.flags_field |= CLASH;
  2125                     String key = m1 == sym ?
  2126                             "name.clash.same.erasure.no.override" :
  2127                             "name.clash.same.erasure.no.override.1";
  2128                     log.error(pos,
  2129                             key,
  2130                             sym, sym.location(),
  2131                             m2, m2.location(),
  2132                             m1, m1.location());
  2133                     return;
  2141     /** Check that all static methods accessible from 'site' are
  2142      *  mutually compatible (JLS 8.4.8).
  2144      *  @param pos  Position to be used for error reporting.
  2145      *  @param site The class whose methods are checked.
  2146      *  @param sym  The method symbol to be checked.
  2147      */
  2148     void checkHideClashes(DiagnosticPosition pos, Type site, MethodSymbol sym) {
  2149         ClashFilter cf = new ClashFilter(site);
  2150         //for each method m1 that is a member of 'site'...
  2151         for (Symbol s : types.membersClosure(site, true).getElementsByName(sym.name, cf)) {
  2152             //if (i) the signature of 'sym' is not a subsignature of m1 (seen as
  2153             //a member of 'site') and (ii) 'sym' has the same erasure as m1, issue an error
  2154             if (!types.isSubSignature(sym.type, types.memberType(site, s), false) &&
  2155                     types.hasSameArgs(s.erasure(types), sym.erasure(types))) {
  2156                 log.error(pos,
  2157                         "name.clash.same.erasure.no.hide",
  2158                         sym, sym.location(),
  2159                         s, s.location());
  2160                 return;
  2165      //where
  2166      private class ClashFilter implements Filter<Symbol> {
  2168          Type site;
  2170          ClashFilter(Type site) {
  2171              this.site = site;
  2174          boolean shouldSkip(Symbol s) {
  2175              return (s.flags() & CLASH) != 0 &&
  2176                 s.owner == site.tsym;
  2179          public boolean accepts(Symbol s) {
  2180              return s.kind == MTH &&
  2181                      (s.flags() & SYNTHETIC) == 0 &&
  2182                      !shouldSkip(s) &&
  2183                      s.isInheritedIn(site.tsym, types) &&
  2184                      !s.isConstructor();
  2188     /** Report a conflict between a user symbol and a synthetic symbol.
  2189      */
  2190     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2191         if (!sym.type.isErroneous()) {
  2192             if (warnOnSyntheticConflicts) {
  2193                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2195             else {
  2196                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2201     /** Check that class c does not implement directly or indirectly
  2202      *  the same parameterized interface with two different argument lists.
  2203      *  @param pos          Position to be used for error reporting.
  2204      *  @param type         The type whose interfaces are checked.
  2205      */
  2206     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2207         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2209 //where
  2210         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2211          *  with their class symbol as key and their type as value. Make
  2212          *  sure no class is entered with two different types.
  2213          */
  2214         void checkClassBounds(DiagnosticPosition pos,
  2215                               Map<TypeSymbol,Type> seensofar,
  2216                               Type type) {
  2217             if (type.isErroneous()) return;
  2218             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2219                 Type it = l.head;
  2220                 Type oldit = seensofar.put(it.tsym, it);
  2221                 if (oldit != null) {
  2222                     List<Type> oldparams = oldit.allparams();
  2223                     List<Type> newparams = it.allparams();
  2224                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2225                         log.error(pos, "cant.inherit.diff.arg",
  2226                                   it.tsym, Type.toString(oldparams),
  2227                                   Type.toString(newparams));
  2229                 checkClassBounds(pos, seensofar, it);
  2231             Type st = types.supertype(type);
  2232             if (st != null) checkClassBounds(pos, seensofar, st);
  2235     /** Enter interface into into set.
  2236      *  If it existed already, issue a "repeated interface" error.
  2237      */
  2238     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2239         if (its.contains(it))
  2240             log.error(pos, "repeated.interface");
  2241         else {
  2242             its.add(it);
  2246 /* *************************************************************************
  2247  * Check annotations
  2248  **************************************************************************/
  2250     /**
  2251      * Recursively validate annotations values
  2252      */
  2253     void validateAnnotationTree(JCTree tree) {
  2254         class AnnotationValidator extends TreeScanner {
  2255             @Override
  2256             public void visitAnnotation(JCAnnotation tree) {
  2257                 if (!tree.type.isErroneous()) {
  2258                     super.visitAnnotation(tree);
  2259                     validateAnnotation(tree);
  2263         tree.accept(new AnnotationValidator());
  2266     /** Annotation types are restricted to primitives, String, an
  2267      *  enum, an annotation, Class, Class<?>, Class<? extends
  2268      *  Anything>, arrays of the preceding.
  2269      */
  2270     void validateAnnotationType(JCTree restype) {
  2271         // restype may be null if an error occurred, so don't bother validating it
  2272         if (restype != null) {
  2273             validateAnnotationType(restype.pos(), restype.type);
  2277     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2278         if (type.isPrimitive()) return;
  2279         if (types.isSameType(type, syms.stringType)) return;
  2280         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2281         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2282         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2283         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2284             validateAnnotationType(pos, types.elemtype(type));
  2285             return;
  2287         log.error(pos, "invalid.annotation.member.type");
  2290     /**
  2291      * "It is also a compile-time error if any method declared in an
  2292      * annotation type has a signature that is override-equivalent to
  2293      * that of any public or protected method declared in class Object
  2294      * or in the interface annotation.Annotation."
  2296      * @jls 9.6 Annotation Types
  2297      */
  2298     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2299         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2300             Scope s = sup.tsym.members();
  2301             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2302                 if (e.sym.kind == MTH &&
  2303                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2304                     types.overrideEquivalent(m.type, e.sym.type))
  2305                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2310     /** Check the annotations of a symbol.
  2311      */
  2312     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2313         if (skipAnnotations) return;
  2314         for (JCAnnotation a : annotations)
  2315             validateAnnotation(a, s);
  2318     /** Check an annotation of a symbol.
  2319      */
  2320     public void validateAnnotation(JCAnnotation a, Symbol s) {
  2321         validateAnnotationTree(a);
  2323         if (!annotationApplicable(a, s))
  2324             log.error(a.pos(), "annotation.type.not.applicable");
  2326         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2327             if (!isOverrider(s))
  2328                 log.error(a.pos(), "method.does.not.override.superclass");
  2332     /** Is s a method symbol that overrides a method in a superclass? */
  2333     boolean isOverrider(Symbol s) {
  2334         if (s.kind != MTH || s.isStatic())
  2335             return false;
  2336         MethodSymbol m = (MethodSymbol)s;
  2337         TypeSymbol owner = (TypeSymbol)m.owner;
  2338         for (Type sup : types.closure(owner.type)) {
  2339             if (sup == owner.type)
  2340                 continue; // skip "this"
  2341             Scope scope = sup.tsym.members();
  2342             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2343                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2344                     return true;
  2347         return false;
  2350     /** Is the annotation applicable to the symbol? */
  2351     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2352         Attribute.Compound atTarget =
  2353             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2354         if (atTarget == null) return true;
  2355         Attribute atValue = atTarget.member(names.value);
  2356         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2357         Attribute.Array arr = (Attribute.Array) atValue;
  2358         for (Attribute app : arr.values) {
  2359             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2360             Attribute.Enum e = (Attribute.Enum) app;
  2361             if (e.value.name == names.TYPE)
  2362                 { if (s.kind == TYP) return true; }
  2363             else if (e.value.name == names.FIELD)
  2364                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2365             else if (e.value.name == names.METHOD)
  2366                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2367             else if (e.value.name == names.PARAMETER)
  2368                 { if (s.kind == VAR &&
  2369                       s.owner.kind == MTH &&
  2370                       (s.flags() & PARAMETER) != 0)
  2371                     return true;
  2373             else if (e.value.name == names.CONSTRUCTOR)
  2374                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2375             else if (e.value.name == names.LOCAL_VARIABLE)
  2376                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2377                       (s.flags() & PARAMETER) == 0)
  2378                     return true;
  2380             else if (e.value.name == names.ANNOTATION_TYPE)
  2381                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2382                     return true;
  2384             else if (e.value.name == names.PACKAGE)
  2385                 { if (s.kind == PCK) return true; }
  2386             else if (e.value.name == names.TYPE_USE)
  2387                 { if (s.kind == TYP ||
  2388                       s.kind == VAR ||
  2389                       (s.kind == MTH && !s.isConstructor() &&
  2390                        s.type.getReturnType().tag != VOID))
  2391                     return true;
  2393             else
  2394                 return true; // recovery
  2396         return false;
  2399     /** Check an annotation value.
  2400      */
  2401     public void validateAnnotation(JCAnnotation a) {
  2402         // collect an inventory of the members (sorted alphabetically)
  2403         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2404             public int compare(Symbol t, Symbol t1) {
  2405                 return t.name.compareTo(t1.name);
  2407         });
  2408         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2409              e != null;
  2410              e = e.sibling)
  2411             if (e.sym.kind == MTH)
  2412                 members.add((MethodSymbol) e.sym);
  2414         // count them off as they're annotated
  2415         for (JCTree arg : a.args) {
  2416             if (!arg.hasTag(ASSIGN)) continue; // recovery
  2417             JCAssign assign = (JCAssign) arg;
  2418             Symbol m = TreeInfo.symbol(assign.lhs);
  2419             if (m == null || m.type.isErroneous()) continue;
  2420             if (!members.remove(m))
  2421                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2422                           m.name, a.type);
  2425         // all the remaining ones better have default values
  2426         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2427         for (MethodSymbol m : members) {
  2428             if (m.defaultValue == null && !m.type.isErroneous()) {
  2429                 missingDefaults.append(m.name);
  2432         if (missingDefaults.nonEmpty()) {
  2433             String key = (missingDefaults.size() > 1)
  2434                     ? "annotation.missing.default.value.1"
  2435                     : "annotation.missing.default.value";
  2436             log.error(a.pos(), key, a.type, missingDefaults);
  2439         // special case: java.lang.annotation.Target must not have
  2440         // repeated values in its value member
  2441         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2442             a.args.tail == null)
  2443             return;
  2445         if (!a.args.head.hasTag(ASSIGN)) return; // error recovery
  2446         JCAssign assign = (JCAssign) a.args.head;
  2447         Symbol m = TreeInfo.symbol(assign.lhs);
  2448         if (m.name != names.value) return;
  2449         JCTree rhs = assign.rhs;
  2450         if (!rhs.hasTag(NEWARRAY)) return;
  2451         JCNewArray na = (JCNewArray) rhs;
  2452         Set<Symbol> targets = new HashSet<Symbol>();
  2453         for (JCTree elem : na.elems) {
  2454             if (!targets.add(TreeInfo.symbol(elem))) {
  2455                 log.error(elem.pos(), "repeated.annotation.target");
  2460     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2461         if (allowAnnotations &&
  2462             lint.isEnabled(LintCategory.DEP_ANN) &&
  2463             (s.flags() & DEPRECATED) != 0 &&
  2464             !syms.deprecatedType.isErroneous() &&
  2465             s.attribute(syms.deprecatedType.tsym) == null) {
  2466             log.warning(LintCategory.DEP_ANN,
  2467                     pos, "missing.deprecated.annotation");
  2471     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2472         if ((s.flags() & DEPRECATED) != 0 &&
  2473                 (other.flags() & DEPRECATED) == 0 &&
  2474                 s.outermostClass() != other.outermostClass()) {
  2475             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2476                 @Override
  2477                 public void report() {
  2478                     warnDeprecated(pos, s);
  2480             });
  2484     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2485         if ((s.flags() & PROPRIETARY) != 0) {
  2486             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2487                 public void report() {
  2488                     if (enableSunApiLintControl)
  2489                       warnSunApi(pos, "sun.proprietary", s);
  2490                     else
  2491                       log.mandatoryWarning(pos, "sun.proprietary", s);
  2493             });
  2497 /* *************************************************************************
  2498  * Check for recursive annotation elements.
  2499  **************************************************************************/
  2501     /** Check for cycles in the graph of annotation elements.
  2502      */
  2503     void checkNonCyclicElements(JCClassDecl tree) {
  2504         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2505         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2506         try {
  2507             tree.sym.flags_field |= LOCKED;
  2508             for (JCTree def : tree.defs) {
  2509                 if (!def.hasTag(METHODDEF)) continue;
  2510                 JCMethodDecl meth = (JCMethodDecl)def;
  2511                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2513         } finally {
  2514             tree.sym.flags_field &= ~LOCKED;
  2515             tree.sym.flags_field |= ACYCLIC_ANN;
  2519     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2520         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2521             return;
  2522         if ((tsym.flags_field & LOCKED) != 0) {
  2523             log.error(pos, "cyclic.annotation.element");
  2524             return;
  2526         try {
  2527             tsym.flags_field |= LOCKED;
  2528             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2529                 Symbol s = e.sym;
  2530                 if (s.kind != Kinds.MTH)
  2531                     continue;
  2532                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2534         } finally {
  2535             tsym.flags_field &= ~LOCKED;
  2536             tsym.flags_field |= ACYCLIC_ANN;
  2540     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2541         switch (type.tag) {
  2542         case TypeTags.CLASS:
  2543             if ((type.tsym.flags() & ANNOTATION) != 0)
  2544                 checkNonCyclicElementsInternal(pos, type.tsym);
  2545             break;
  2546         case TypeTags.ARRAY:
  2547             checkAnnotationResType(pos, types.elemtype(type));
  2548             break;
  2549         default:
  2550             break; // int etc
  2554 /* *************************************************************************
  2555  * Check for cycles in the constructor call graph.
  2556  **************************************************************************/
  2558     /** Check for cycles in the graph of constructors calling other
  2559      *  constructors.
  2560      */
  2561     void checkCyclicConstructors(JCClassDecl tree) {
  2562         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2564         // enter each constructor this-call into the map
  2565         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2566             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2567             if (app == null) continue;
  2568             JCMethodDecl meth = (JCMethodDecl) l.head;
  2569             if (TreeInfo.name(app.meth) == names._this) {
  2570                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2571             } else {
  2572                 meth.sym.flags_field |= ACYCLIC;
  2576         // Check for cycles in the map
  2577         Symbol[] ctors = new Symbol[0];
  2578         ctors = callMap.keySet().toArray(ctors);
  2579         for (Symbol caller : ctors) {
  2580             checkCyclicConstructor(tree, caller, callMap);
  2584     /** Look in the map to see if the given constructor is part of a
  2585      *  call cycle.
  2586      */
  2587     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2588                                         Map<Symbol,Symbol> callMap) {
  2589         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2590             if ((ctor.flags_field & LOCKED) != 0) {
  2591                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2592                           "recursive.ctor.invocation");
  2593             } else {
  2594                 ctor.flags_field |= LOCKED;
  2595                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2596                 ctor.flags_field &= ~LOCKED;
  2598             ctor.flags_field |= ACYCLIC;
  2602 /* *************************************************************************
  2603  * Miscellaneous
  2604  **************************************************************************/
  2606     /**
  2607      * Return the opcode of the operator but emit an error if it is an
  2608      * error.
  2609      * @param pos        position for error reporting.
  2610      * @param operator   an operator
  2611      * @param tag        a tree tag
  2612      * @param left       type of left hand side
  2613      * @param right      type of right hand side
  2614      */
  2615     int checkOperator(DiagnosticPosition pos,
  2616                        OperatorSymbol operator,
  2617                        JCTree.Tag tag,
  2618                        Type left,
  2619                        Type right) {
  2620         if (operator.opcode == ByteCodes.error) {
  2621             log.error(pos,
  2622                       "operator.cant.be.applied.1",
  2623                       treeinfo.operatorName(tag),
  2624                       left, right);
  2626         return operator.opcode;
  2630     /**
  2631      *  Check for division by integer constant zero
  2632      *  @param pos           Position for error reporting.
  2633      *  @param operator      The operator for the expression
  2634      *  @param operand       The right hand operand for the expression
  2635      */
  2636     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2637         if (operand.constValue() != null
  2638             && lint.isEnabled(LintCategory.DIVZERO)
  2639             && operand.tag <= LONG
  2640             && ((Number) (operand.constValue())).longValue() == 0) {
  2641             int opc = ((OperatorSymbol)operator).opcode;
  2642             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2643                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2644                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  2649     /**
  2650      * Check for empty statements after if
  2651      */
  2652     void checkEmptyIf(JCIf tree) {
  2653         if (tree.thenpart.hasTag(SKIP) && tree.elsepart == null &&
  2654                 lint.isEnabled(LintCategory.EMPTY))
  2655             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  2658     /** Check that symbol is unique in given scope.
  2659      *  @param pos           Position for error reporting.
  2660      *  @param sym           The symbol.
  2661      *  @param s             The scope.
  2662      */
  2663     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2664         if (sym.type.isErroneous())
  2665             return true;
  2666         if (sym.owner.name == names.any) return false;
  2667         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2668             if (sym != e.sym &&
  2669                     (e.sym.flags() & CLASH) == 0 &&
  2670                     sym.kind == e.sym.kind &&
  2671                     sym.name != names.error &&
  2672                     (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2673                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  2674                     varargsDuplicateError(pos, sym, e.sym);
  2675                     return true;
  2676                 } else if (sym.kind == MTH && !types.hasSameArgs(sym.type, e.sym.type, false)) {
  2677                     duplicateErasureError(pos, sym, e.sym);
  2678                     sym.flags_field |= CLASH;
  2679                     return true;
  2680                 } else {
  2681                     duplicateError(pos, e.sym);
  2682                     return false;
  2686         return true;
  2689     /** Report duplicate declaration error.
  2690      */
  2691     void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2692         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2693             log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2697     /** Check that single-type import is not already imported or top-level defined,
  2698      *  but make an exception for two single-type imports which denote the same type.
  2699      *  @param pos           Position for error reporting.
  2700      *  @param sym           The symbol.
  2701      *  @param s             The scope
  2702      */
  2703     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2704         return checkUniqueImport(pos, sym, s, false);
  2707     /** Check that static single-type import is not already imported or top-level defined,
  2708      *  but make an exception for two single-type imports which denote the same type.
  2709      *  @param pos           Position for error reporting.
  2710      *  @param sym           The symbol.
  2711      *  @param s             The scope
  2712      *  @param staticImport  Whether or not this was a static import
  2713      */
  2714     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2715         return checkUniqueImport(pos, sym, s, true);
  2718     /** Check that single-type import is not already imported or top-level defined,
  2719      *  but make an exception for two single-type imports which denote the same type.
  2720      *  @param pos           Position for error reporting.
  2721      *  @param sym           The symbol.
  2722      *  @param s             The scope.
  2723      *  @param staticImport  Whether or not this was a static import
  2724      */
  2725     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2726         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2727             // is encountered class entered via a class declaration?
  2728             boolean isClassDecl = e.scope == s;
  2729             if ((isClassDecl || sym != e.sym) &&
  2730                 sym.kind == e.sym.kind &&
  2731                 sym.name != names.error) {
  2732                 if (!e.sym.type.isErroneous()) {
  2733                     String what = e.sym.toString();
  2734                     if (!isClassDecl) {
  2735                         if (staticImport)
  2736                             log.error(pos, "already.defined.static.single.import", what);
  2737                         else
  2738                             log.error(pos, "already.defined.single.import", what);
  2740                     else if (sym != e.sym)
  2741                         log.error(pos, "already.defined.this.unit", what);
  2743                 return false;
  2746         return true;
  2749     /** Check that a qualified name is in canonical form (for import decls).
  2750      */
  2751     public void checkCanonical(JCTree tree) {
  2752         if (!isCanonical(tree))
  2753             log.error(tree.pos(), "import.requires.canonical",
  2754                       TreeInfo.symbol(tree));
  2756         // where
  2757         private boolean isCanonical(JCTree tree) {
  2758             while (tree.hasTag(SELECT)) {
  2759                 JCFieldAccess s = (JCFieldAccess) tree;
  2760                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2761                     return false;
  2762                 tree = s.selected;
  2764             return true;
  2767     private class ConversionWarner extends Warner {
  2768         final String uncheckedKey;
  2769         final Type found;
  2770         final Type expected;
  2771         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  2772             super(pos);
  2773             this.uncheckedKey = uncheckedKey;
  2774             this.found = found;
  2775             this.expected = expected;
  2778         @Override
  2779         public void warn(LintCategory lint) {
  2780             boolean warned = this.warned;
  2781             super.warn(lint);
  2782             if (warned) return; // suppress redundant diagnostics
  2783             switch (lint) {
  2784                 case UNCHECKED:
  2785                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  2786                     break;
  2787                 case VARARGS:
  2788                     if (method != null &&
  2789                             method.attribute(syms.trustMeType.tsym) != null &&
  2790                             isTrustMeAllowedOnMethod(method) &&
  2791                             !types.isReifiable(method.type.getParameterTypes().last())) {
  2792                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  2794                     break;
  2795                 default:
  2796                     throw new AssertionError("Unexpected lint: " + lint);
  2801     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2802         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2805     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2806         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial