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

Thu, 03 Feb 2011 09:35:21 +0000

author
mcimadamore
date
Thu, 03 Feb 2011 09:35:21 +0000
changeset 852
899f7c3d9426
parent 845
5a43b245aed1
child 853
875262e89b52
permissions
-rw-r--r--

6594914: @SuppressWarnings("deprecation") does not not work for the type of a variable
Summary: Lint warnings generated during MemberEnter might ignore @SuppressWarnings annotations
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2011, 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.Kinds.*;
    46 import static com.sun.tools.javac.code.TypeTags.*;
    48 import static com.sun.tools.javac.main.OptionName.*;
    50 /** Type checking helper class for the attribution phase.
    51  *
    52  *  <p><b>This is NOT part of any supported API.
    53  *  If you write code that depends on this, you do so at your own risk.
    54  *  This code and its internal interfaces are subject to change or
    55  *  deletion without notice.</b>
    56  */
    57 public class Check {
    58     protected static final Context.Key<Check> checkKey =
    59         new Context.Key<Check>();
    61     private final Names names;
    62     private final Log log;
    63     private final Symtab syms;
    64     private final Enter enter;
    65     private final Infer infer;
    66     private final Types types;
    67     private final JCDiagnostic.Factory diags;
    68     private final boolean skipAnnotations;
    69     private boolean warnOnSyntheticConflicts;
    70     private boolean suppressAbortOnBadClassFile;
    71     private boolean enableSunApiLintControl;
    72     private final TreeInfo treeinfo;
    74     // The set of lint options currently in effect. It is initialized
    75     // from the context, and then is set/reset as needed by Attr as it
    76     // visits all the various parts of the trees during attribution.
    77     private Lint lint;
    79     // The method being analyzed in Attr - it is set/reset as needed by
    80     // Attr as it visits new method declarations.
    81     private MethodSymbol method;
    83     public static Check instance(Context context) {
    84         Check instance = context.get(checkKey);
    85         if (instance == null)
    86             instance = new Check(context);
    87         return instance;
    88     }
    90     protected Check(Context context) {
    91         context.put(checkKey, this);
    93         names = Names.instance(context);
    94         log = Log.instance(context);
    95         syms = Symtab.instance(context);
    96         enter = Enter.instance(context);
    97         infer = Infer.instance(context);
    98         this.types = Types.instance(context);
    99         diags = JCDiagnostic.Factory.instance(context);
   100         Options options = Options.instance(context);
   101         lint = Lint.instance(context);
   102         treeinfo = TreeInfo.instance(context);
   104         Source source = Source.instance(context);
   105         allowGenerics = source.allowGenerics();
   106         allowAnnotations = source.allowAnnotations();
   107         allowCovariantReturns = source.allowCovariantReturns();
   108         allowSimplifiedVarargs = source.allowSimplifiedVarargs();
   109         complexInference = options.isSet(COMPLEXINFERENCE);
   110         skipAnnotations = options.isSet("skipAnnotations");
   111         warnOnSyntheticConflicts = options.isSet("warnOnSyntheticConflicts");
   112         suppressAbortOnBadClassFile = options.isSet("suppressAbortOnBadClassFile");
   113         enableSunApiLintControl = options.isSet("enableSunApiLintControl");
   115         Target target = Target.instance(context);
   116         syntheticNameChar = target.syntheticNameChar();
   118         boolean verboseDeprecated = lint.isEnabled(LintCategory.DEPRECATION);
   119         boolean verboseUnchecked = lint.isEnabled(LintCategory.UNCHECKED);
   120         boolean verboseSunApi = lint.isEnabled(LintCategory.SUNAPI);
   121         boolean enforceMandatoryWarnings = source.enforceMandatoryWarnings();
   123         deprecationHandler = new MandatoryWarningHandler(log, verboseDeprecated,
   124                 enforceMandatoryWarnings, "deprecated", LintCategory.DEPRECATION);
   125         uncheckedHandler = new MandatoryWarningHandler(log, verboseUnchecked,
   126                 enforceMandatoryWarnings, "unchecked", LintCategory.UNCHECKED);
   127         sunApiHandler = new MandatoryWarningHandler(log, verboseSunApi,
   128                 enforceMandatoryWarnings, "sunapi", null);
   130         deferredLintHandler = DeferredLintHandler.immediateHandler;
   131     }
   133     /** Switch: generics enabled?
   134      */
   135     boolean allowGenerics;
   137     /** Switch: annotations enabled?
   138      */
   139     boolean allowAnnotations;
   141     /** Switch: covariant returns enabled?
   142      */
   143     boolean allowCovariantReturns;
   145     /** Switch: simplified varargs enabled?
   146      */
   147     boolean allowSimplifiedVarargs;
   149     /** Switch: -complexinference option set?
   150      */
   151     boolean complexInference;
   153     /** Character for synthetic names
   154      */
   155     char syntheticNameChar;
   157     /** A table mapping flat names of all compiled classes in this run to their
   158      *  symbols; maintained from outside.
   159      */
   160     public Map<Name,ClassSymbol> compiled = new HashMap<Name, ClassSymbol>();
   162     /** A handler for messages about deprecated usage.
   163      */
   164     private MandatoryWarningHandler deprecationHandler;
   166     /** A handler for messages about unchecked or unsafe usage.
   167      */
   168     private MandatoryWarningHandler uncheckedHandler;
   170     /** A handler for messages about using proprietary API.
   171      */
   172     private MandatoryWarningHandler sunApiHandler;
   174     /** A handler for deferred lint warnings.
   175      */
   176     private DeferredLintHandler deferredLintHandler;
   178 /* *************************************************************************
   179  * Errors and Warnings
   180  **************************************************************************/
   182     Lint setLint(Lint newLint) {
   183         Lint prev = lint;
   184         lint = newLint;
   185         return prev;
   186     }
   188     DeferredLintHandler setDeferredLintHandler(DeferredLintHandler newDeferredLintHandler) {
   189         DeferredLintHandler prev = deferredLintHandler;
   190         deferredLintHandler = newDeferredLintHandler;
   191         return prev;
   192     }
   194     MethodSymbol setMethod(MethodSymbol newMethod) {
   195         MethodSymbol prev = method;
   196         method = newMethod;
   197         return prev;
   198     }
   200     /** Warn about deprecated symbol.
   201      *  @param pos        Position to be used for error reporting.
   202      *  @param sym        The deprecated symbol.
   203      */
   204     void warnDeprecated(DiagnosticPosition pos, Symbol sym) {
   205         if (!lint.isSuppressed(LintCategory.DEPRECATION))
   206             deprecationHandler.report(pos, "has.been.deprecated", sym, sym.location());
   207     }
   209     /** Warn about unchecked operation.
   210      *  @param pos        Position to be used for error reporting.
   211      *  @param msg        A string describing the problem.
   212      */
   213     public void warnUnchecked(DiagnosticPosition pos, String msg, Object... args) {
   214         if (!lint.isSuppressed(LintCategory.UNCHECKED))
   215             uncheckedHandler.report(pos, msg, args);
   216     }
   218     /** Warn about unsafe vararg method decl.
   219      *  @param pos        Position to be used for error reporting.
   220      *  @param sym        The deprecated symbol.
   221      */
   222     void warnUnsafeVararg(DiagnosticPosition pos, String key, Object... args) {
   223         if (lint.isEnabled(LintCategory.VARARGS) && allowSimplifiedVarargs)
   224             log.warning(LintCategory.VARARGS, pos, key, args);
   225     }
   227     /** Warn about using proprietary API.
   228      *  @param pos        Position to be used for error reporting.
   229      *  @param msg        A string describing the problem.
   230      */
   231     public void warnSunApi(DiagnosticPosition pos, String msg, Object... args) {
   232         if (!lint.isSuppressed(LintCategory.SUNAPI))
   233             sunApiHandler.report(pos, msg, args);
   234     }
   236     public void warnStatic(DiagnosticPosition pos, String msg, Object... args) {
   237         if (lint.isEnabled(LintCategory.STATIC))
   238             log.warning(LintCategory.STATIC, pos, msg, args);
   239     }
   241     /**
   242      * Report any deferred diagnostics.
   243      */
   244     public void reportDeferredDiagnostics() {
   245         deprecationHandler.reportDeferredDiagnostic();
   246         uncheckedHandler.reportDeferredDiagnostic();
   247         sunApiHandler.reportDeferredDiagnostic();
   248     }
   251     /** Report a failure to complete a class.
   252      *  @param pos        Position to be used for error reporting.
   253      *  @param ex         The failure to report.
   254      */
   255     public Type completionError(DiagnosticPosition pos, CompletionFailure ex) {
   256         log.error(pos, "cant.access", ex.sym, ex.getDetailValue());
   257         if (ex instanceof ClassReader.BadClassFile
   258                 && !suppressAbortOnBadClassFile) throw new Abort();
   259         else return syms.errType;
   260     }
   262     /** Report a type error.
   263      *  @param pos        Position to be used for error reporting.
   264      *  @param problem    A string describing the error.
   265      *  @param found      The type that was found.
   266      *  @param req        The type that was required.
   267      */
   268     Type typeError(DiagnosticPosition pos, Object problem, Type found, Type req) {
   269         log.error(pos, "prob.found.req",
   270                   problem, found, req);
   271         return types.createErrorType(found);
   272     }
   274     Type typeError(DiagnosticPosition pos, String problem, Type found, Type req, Object explanation) {
   275         log.error(pos, "prob.found.req.1", problem, found, req, explanation);
   276         return types.createErrorType(found);
   277     }
   279     /** Report an error that wrong type tag was found.
   280      *  @param pos        Position to be used for error reporting.
   281      *  @param required   An internationalized string describing the type tag
   282      *                    required.
   283      *  @param found      The type that was found.
   284      */
   285     Type typeTagError(DiagnosticPosition pos, Object required, Object found) {
   286         // this error used to be raised by the parser,
   287         // but has been delayed to this point:
   288         if (found instanceof Type && ((Type)found).tag == VOID) {
   289             log.error(pos, "illegal.start.of.type");
   290             return syms.errType;
   291         }
   292         log.error(pos, "type.found.req", found, required);
   293         return types.createErrorType(found instanceof Type ? (Type)found : syms.errType);
   294     }
   296     /** Report an error that symbol cannot be referenced before super
   297      *  has been called.
   298      *  @param pos        Position to be used for error reporting.
   299      *  @param sym        The referenced symbol.
   300      */
   301     void earlyRefError(DiagnosticPosition pos, Symbol sym) {
   302         log.error(pos, "cant.ref.before.ctor.called", sym);
   303     }
   305     /** Report duplicate declaration error.
   306      */
   307     void duplicateError(DiagnosticPosition pos, Symbol sym) {
   308         if (!sym.type.isErroneous()) {
   309             log.error(pos, "already.defined", sym, sym.location());
   310         }
   311     }
   313     /** Report array/varargs duplicate declaration
   314      */
   315     void varargsDuplicateError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
   316         if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
   317             log.error(pos, "array.and.varargs", sym1, sym2, sym2.location());
   318         }
   319     }
   321 /* ************************************************************************
   322  * duplicate declaration checking
   323  *************************************************************************/
   325     /** Check that variable does not hide variable with same name in
   326      *  immediately enclosing local scope.
   327      *  @param pos           Position for error reporting.
   328      *  @param v             The symbol.
   329      *  @param s             The scope.
   330      */
   331     void checkTransparentVar(DiagnosticPosition pos, VarSymbol v, Scope s) {
   332         if (s.next != null) {
   333             for (Scope.Entry e = s.next.lookup(v.name);
   334                  e.scope != null && e.sym.owner == v.owner;
   335                  e = e.next()) {
   336                 if (e.sym.kind == VAR &&
   337                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   338                     v.name != names.error) {
   339                     duplicateError(pos, e.sym);
   340                     return;
   341                 }
   342             }
   343         }
   344     }
   346     /** Check that a class or interface does not hide a class or
   347      *  interface with same name in immediately enclosing local scope.
   348      *  @param pos           Position for error reporting.
   349      *  @param c             The symbol.
   350      *  @param s             The scope.
   351      */
   352     void checkTransparentClass(DiagnosticPosition pos, ClassSymbol c, Scope s) {
   353         if (s.next != null) {
   354             for (Scope.Entry e = s.next.lookup(c.name);
   355                  e.scope != null && e.sym.owner == c.owner;
   356                  e = e.next()) {
   357                 if (e.sym.kind == TYP && e.sym.type.tag != TYPEVAR &&
   358                     (e.sym.owner.kind & (VAR | MTH)) != 0 &&
   359                     c.name != names.error) {
   360                     duplicateError(pos, e.sym);
   361                     return;
   362                 }
   363             }
   364         }
   365     }
   367     /** Check that class does not have the same name as one of
   368      *  its enclosing classes, or as a class defined in its enclosing scope.
   369      *  return true if class is unique in its enclosing scope.
   370      *  @param pos           Position for error reporting.
   371      *  @param name          The class name.
   372      *  @param s             The enclosing scope.
   373      */
   374     boolean checkUniqueClassName(DiagnosticPosition pos, Name name, Scope s) {
   375         for (Scope.Entry e = s.lookup(name); e.scope == s; e = e.next()) {
   376             if (e.sym.kind == TYP && e.sym.name != names.error) {
   377                 duplicateError(pos, e.sym);
   378                 return false;
   379             }
   380         }
   381         for (Symbol sym = s.owner; sym != null; sym = sym.owner) {
   382             if (sym.kind == TYP && sym.name == name && sym.name != names.error) {
   383                 duplicateError(pos, sym);
   384                 return true;
   385             }
   386         }
   387         return true;
   388     }
   390 /* *************************************************************************
   391  * Class name generation
   392  **************************************************************************/
   394     /** Return name of local class.
   395      *  This is of the form    <enclClass> $ n <classname>
   396      *  where
   397      *    enclClass is the flat name of the enclosing class,
   398      *    classname is the simple name of the local class
   399      */
   400     Name localClassName(ClassSymbol c) {
   401         for (int i=1; ; i++) {
   402             Name flatname = names.
   403                 fromString("" + c.owner.enclClass().flatname +
   404                            syntheticNameChar + i +
   405                            c.name);
   406             if (compiled.get(flatname) == null) return flatname;
   407         }
   408     }
   410 /* *************************************************************************
   411  * Type Checking
   412  **************************************************************************/
   414     /** Check that a given type is assignable to a given proto-type.
   415      *  If it is, return the type, otherwise return errType.
   416      *  @param pos        Position to be used for error reporting.
   417      *  @param found      The type that was found.
   418      *  @param req        The type that was required.
   419      */
   420     Type checkType(DiagnosticPosition pos, Type found, Type req) {
   421         return checkType(pos, found, req, "incompatible.types");
   422     }
   424     Type checkType(DiagnosticPosition pos, Type found, Type req, String errKey) {
   425         if (req.tag == ERROR)
   426             return req;
   427         if (found.tag == FORALL)
   428             return instantiatePoly(pos, (ForAll)found, req, convertWarner(pos, found, req));
   429         if (req.tag == NONE)
   430             return found;
   431         if (types.isAssignable(found, req, convertWarner(pos, found, req)))
   432             return found;
   433         if (found.tag <= DOUBLE && req.tag <= DOUBLE)
   434             return typeError(pos, diags.fragment("possible.loss.of.precision"), found, req);
   435         if (found.isSuperBound()) {
   436             log.error(pos, "assignment.from.super-bound", found);
   437             return types.createErrorType(found);
   438         }
   439         if (req.isExtendsBound()) {
   440             log.error(pos, "assignment.to.extends-bound", req);
   441             return types.createErrorType(found);
   442         }
   443         return typeError(pos, diags.fragment(errKey), found, req);
   444     }
   446     /** Instantiate polymorphic type to some prototype, unless
   447      *  prototype is `anyPoly' in which case polymorphic type
   448      *  is returned unchanged.
   449      */
   450     Type instantiatePoly(DiagnosticPosition pos, ForAll t, Type pt, Warner warn) throws Infer.NoInstanceException {
   451         if (pt == Infer.anyPoly && complexInference) {
   452             return t;
   453         } else if (pt == Infer.anyPoly || pt.tag == NONE) {
   454             Type newpt = t.qtype.tag <= VOID ? t.qtype : syms.objectType;
   455             return instantiatePoly(pos, t, newpt, warn);
   456         } else if (pt.tag == ERROR) {
   457             return pt;
   458         } else {
   459             try {
   460                 return infer.instantiateExpr(t, pt, warn);
   461             } catch (Infer.NoInstanceException ex) {
   462                 if (ex.isAmbiguous) {
   463                     JCDiagnostic d = ex.getDiagnostic();
   464                     log.error(pos,
   465                               "undetermined.type" + (d!=null ? ".1" : ""),
   466                               t, d);
   467                     return types.createErrorType(pt);
   468                 } else {
   469                     JCDiagnostic d = ex.getDiagnostic();
   470                     return typeError(pos,
   471                                      diags.fragment("incompatible.types" + (d!=null ? ".1" : ""), d),
   472                                      t, pt);
   473                 }
   474             } catch (Infer.InvalidInstanceException ex) {
   475                 JCDiagnostic d = ex.getDiagnostic();
   476                 log.error(pos, "invalid.inferred.types", t.tvars, d);
   477                 return types.createErrorType(pt);
   478             }
   479         }
   480     }
   482     /** Check that a given type can be cast to a given target type.
   483      *  Return the result of the cast.
   484      *  @param pos        Position to be used for error reporting.
   485      *  @param found      The type that is being cast.
   486      *  @param req        The target type of the cast.
   487      */
   488     Type checkCastable(DiagnosticPosition pos, Type found, Type req) {
   489         if (found.tag == FORALL) {
   490             instantiatePoly(pos, (ForAll) found, req, castWarner(pos, found, req));
   491             return req;
   492         } else if (types.isCastable(found, req, castWarner(pos, found, req))) {
   493             return req;
   494         } else {
   495             return typeError(pos,
   496                              diags.fragment("inconvertible.types"),
   497                              found, req);
   498         }
   499     }
   500 //where
   501         /** Is type a type variable, or a (possibly multi-dimensional) array of
   502          *  type variables?
   503          */
   504         boolean isTypeVar(Type t) {
   505             return t.tag == TYPEVAR || t.tag == ARRAY && isTypeVar(types.elemtype(t));
   506         }
   508     /** Check that a type is within some bounds.
   509      *
   510      *  Used in TypeApply to verify that, e.g., X in V<X> is a valid
   511      *  type argument.
   512      *  @param pos           Position to be used for error reporting.
   513      *  @param a             The type that should be bounded by bs.
   514      *  @param bs            The bound.
   515      */
   516     private boolean checkExtends(Type a, TypeVar bs) {
   517          if (a.isUnbound()) {
   518              return true;
   519          } else if (a.tag != WILDCARD) {
   520              a = types.upperBound(a);
   521              return types.isSubtype(a, bs.bound);
   522          } else if (a.isExtendsBound()) {
   523              return types.isCastable(bs.getUpperBound(), types.upperBound(a), Warner.noWarnings);
   524          } else if (a.isSuperBound()) {
   525              return !types.notSoftSubtype(types.lowerBound(a), bs.getUpperBound());
   526          }
   527          return true;
   528      }
   530     /** Check that type is different from 'void'.
   531      *  @param pos           Position to be used for error reporting.
   532      *  @param t             The type to be checked.
   533      */
   534     Type checkNonVoid(DiagnosticPosition pos, Type t) {
   535         if (t.tag == VOID) {
   536             log.error(pos, "void.not.allowed.here");
   537             return types.createErrorType(t);
   538         } else {
   539             return t;
   540         }
   541     }
   543     /** Check that type is a class or interface type.
   544      *  @param pos           Position to be used for error reporting.
   545      *  @param t             The type to be checked.
   546      */
   547     Type checkClassType(DiagnosticPosition pos, Type t) {
   548         if (t.tag != CLASS && t.tag != ERROR)
   549             return typeTagError(pos,
   550                                 diags.fragment("type.req.class"),
   551                                 (t.tag == TYPEVAR)
   552                                 ? diags.fragment("type.parameter", t)
   553                                 : t);
   554         else
   555             return t;
   556     }
   558     /** Check that type is a class or interface type.
   559      *  @param pos           Position to be used for error reporting.
   560      *  @param t             The type to be checked.
   561      *  @param noBounds    True if type bounds are illegal here.
   562      */
   563     Type checkClassType(DiagnosticPosition pos, Type t, boolean noBounds) {
   564         t = checkClassType(pos, t);
   565         if (noBounds && t.isParameterized()) {
   566             List<Type> args = t.getTypeArguments();
   567             while (args.nonEmpty()) {
   568                 if (args.head.tag == WILDCARD)
   569                     return typeTagError(pos,
   570                                         diags.fragment("type.req.exact"),
   571                                         args.head);
   572                 args = args.tail;
   573             }
   574         }
   575         return t;
   576     }
   578     /** Check that type is a reifiable class, interface or array type.
   579      *  @param pos           Position to be used for error reporting.
   580      *  @param t             The type to be checked.
   581      */
   582     Type checkReifiableReferenceType(DiagnosticPosition pos, Type t) {
   583         if (t.tag != CLASS && t.tag != ARRAY && t.tag != ERROR) {
   584             return typeTagError(pos,
   585                                 diags.fragment("type.req.class.array"),
   586                                 t);
   587         } else if (!types.isReifiable(t)) {
   588             log.error(pos, "illegal.generic.type.for.instof");
   589             return types.createErrorType(t);
   590         } else {
   591             return t;
   592         }
   593     }
   595     /** Check that type is a reference type, i.e. a class, interface or array type
   596      *  or a type variable.
   597      *  @param pos           Position to be used for error reporting.
   598      *  @param t             The type to be checked.
   599      */
   600     Type checkRefType(DiagnosticPosition pos, Type t) {
   601         switch (t.tag) {
   602         case CLASS:
   603         case ARRAY:
   604         case TYPEVAR:
   605         case WILDCARD:
   606         case ERROR:
   607             return t;
   608         default:
   609             return typeTagError(pos,
   610                                 diags.fragment("type.req.ref"),
   611                                 t);
   612         }
   613     }
   615     /** Check that each type is a reference type, i.e. a class, interface or array type
   616      *  or a type variable.
   617      *  @param trees         Original trees, used for error reporting.
   618      *  @param types         The types to be checked.
   619      */
   620     List<Type> checkRefTypes(List<JCExpression> trees, List<Type> types) {
   621         List<JCExpression> tl = trees;
   622         for (List<Type> l = types; l.nonEmpty(); l = l.tail) {
   623             l.head = checkRefType(tl.head.pos(), l.head);
   624             tl = tl.tail;
   625         }
   626         return types;
   627     }
   629     /** Check that type is a null or reference type.
   630      *  @param pos           Position to be used for error reporting.
   631      *  @param t             The type to be checked.
   632      */
   633     Type checkNullOrRefType(DiagnosticPosition pos, Type t) {
   634         switch (t.tag) {
   635         case CLASS:
   636         case ARRAY:
   637         case TYPEVAR:
   638         case WILDCARD:
   639         case BOT:
   640         case ERROR:
   641             return t;
   642         default:
   643             return typeTagError(pos,
   644                                 diags.fragment("type.req.ref"),
   645                                 t);
   646         }
   647     }
   649     /** Check that flag set does not contain elements of two conflicting sets. s
   650      *  Return true if it doesn't.
   651      *  @param pos           Position to be used for error reporting.
   652      *  @param flags         The set of flags to be checked.
   653      *  @param set1          Conflicting flags set #1.
   654      *  @param set2          Conflicting flags set #2.
   655      */
   656     boolean checkDisjoint(DiagnosticPosition pos, long flags, long set1, long set2) {
   657         if ((flags & set1) != 0 && (flags & set2) != 0) {
   658             log.error(pos,
   659                       "illegal.combination.of.modifiers",
   660                       asFlagSet(TreeInfo.firstFlag(flags & set1)),
   661                       asFlagSet(TreeInfo.firstFlag(flags & set2)));
   662             return false;
   663         } else
   664             return true;
   665     }
   667     /** Check that the type inferred using the diamond operator does not contain
   668      *  non-denotable types such as captured types or intersection types.
   669      *  @param t the type inferred using the diamond operator
   670      */
   671     List<Type> checkDiamond(ClassType t) {
   672         DiamondTypeChecker dtc = new DiamondTypeChecker();
   673         ListBuffer<Type> buf = ListBuffer.lb();
   674         for (Type arg : t.getTypeArguments()) {
   675             if (!dtc.visit(arg, null)) {
   676                 buf.append(arg);
   677             }
   678         }
   679         return buf.toList();
   680     }
   682     static class DiamondTypeChecker extends Types.SimpleVisitor<Boolean, Void> {
   683         public Boolean visitType(Type t, Void s) {
   684             return true;
   685         }
   686         @Override
   687         public Boolean visitClassType(ClassType t, Void s) {
   688             if (t.isCompound()) {
   689                 return false;
   690             }
   691             for (Type targ : t.getTypeArguments()) {
   692                 if (!visit(targ, s)) {
   693                     return false;
   694                 }
   695             }
   696             return true;
   697         }
   698         @Override
   699         public Boolean visitCapturedType(CapturedType t, Void s) {
   700             return false;
   701         }
   702     }
   704     void checkVarargsMethodDecl(Env<AttrContext> env, JCMethodDecl tree) {
   705         MethodSymbol m = tree.sym;
   706         if (!allowSimplifiedVarargs) return;
   707         boolean hasTrustMeAnno = m.attribute(syms.trustMeType.tsym) != null;
   708         Type varargElemType = null;
   709         if (m.isVarArgs()) {
   710             varargElemType = types.elemtype(tree.params.last().type);
   711         }
   712         if (hasTrustMeAnno && !isTrustMeAllowedOnMethod(m)) {
   713             if (varargElemType != null) {
   714                 log.error(tree,
   715                         "varargs.invalid.trustme.anno",
   716                         syms.trustMeType.tsym,
   717                         diags.fragment("varargs.trustme.on.virtual.varargs", m));
   718             } else {
   719                 log.error(tree,
   720                             "varargs.invalid.trustme.anno",
   721                             syms.trustMeType.tsym,
   722                             diags.fragment("varargs.trustme.on.non.varargs.meth", m));
   723             }
   724         } else if (hasTrustMeAnno && varargElemType != null &&
   725                             types.isReifiable(varargElemType)) {
   726             warnUnsafeVararg(tree,
   727                             "varargs.redundant.trustme.anno",
   728                             syms.trustMeType.tsym,
   729                             diags.fragment("varargs.trustme.on.reifiable.varargs", varargElemType));
   730         }
   731         else if (!hasTrustMeAnno && varargElemType != null &&
   732                 !types.isReifiable(varargElemType)) {
   733             warnUnchecked(tree.params.head.pos(), "unchecked.varargs.non.reifiable.type", varargElemType);
   734         }
   735     }
   736     //where
   737         private boolean isTrustMeAllowedOnMethod(Symbol s) {
   738             return (s.flags() & VARARGS) != 0 &&
   739                 (s.isConstructor() ||
   740                     (s.flags() & (STATIC | FINAL)) != 0);
   741         }
   743     /**
   744      * Check that vararg method call is sound
   745      * @param pos Position to be used for error reporting.
   746      * @param argtypes Actual arguments supplied to vararg method.
   747      */
   748     void checkVararg(DiagnosticPosition pos, List<Type> argtypes, Symbol msym) {
   749         Type argtype = argtypes.last();
   750         if (!types.isReifiable(argtype) &&
   751                 (!allowSimplifiedVarargs ||
   752                 msym.attribute(syms.trustMeType.tsym) == null ||
   753                 !isTrustMeAllowedOnMethod(msym))) {
   754             warnUnchecked(pos,
   755                               "unchecked.generic.array.creation",
   756                               argtype);
   757         }
   758     }
   760     /**
   761      * Check that type 't' is a valid instantiation of a generic class
   762      * (see JLS 4.5)
   763      *
   764      * @param t class type to be checked
   765      * @return true if 't' is well-formed
   766      */
   767     public boolean checkValidGenericType(Type t) {
   768         return firstIncompatibleTypeArg(t) == null;
   769     }
   770     //WHERE
   771         private Type firstIncompatibleTypeArg(Type type) {
   772             List<Type> formals = type.tsym.type.allparams();
   773             List<Type> actuals = type.allparams();
   774             List<Type> args = type.getTypeArguments();
   775             List<Type> forms = type.tsym.type.getTypeArguments();
   776             ListBuffer<Type> tvars_buf = new ListBuffer<Type>();
   778             // For matching pairs of actual argument types `a' and
   779             // formal type parameters with declared bound `b' ...
   780             while (args.nonEmpty() && forms.nonEmpty()) {
   781                 // exact type arguments needs to know their
   782                 // bounds (for upper and lower bound
   783                 // calculations).  So we create new TypeVars with
   784                 // bounds substed with actuals.
   785                 tvars_buf.append(types.substBound(((TypeVar)forms.head),
   786                                                   formals,
   787                                                   actuals));
   788                 args = args.tail;
   789                 forms = forms.tail;
   790             }
   792             args = type.getTypeArguments();
   793             List<Type> tvars_cap = types.substBounds(formals,
   794                                       formals,
   795                                       types.capture(type).allparams());
   796             while (args.nonEmpty() && tvars_cap.nonEmpty()) {
   797                 // Let the actual arguments know their bound
   798                 args.head.withTypeVar((TypeVar)tvars_cap.head);
   799                 args = args.tail;
   800                 tvars_cap = tvars_cap.tail;
   801             }
   803             args = type.getTypeArguments();
   804             List<Type> tvars = tvars_buf.toList();
   806             while (args.nonEmpty() && tvars.nonEmpty()) {
   807                 Type actual = types.subst(args.head,
   808                     type.tsym.type.getTypeArguments(),
   809                     tvars_buf.toList());
   810                 if (!checkExtends(actual, (TypeVar)tvars.head) &&
   811                         !tvars.head.getUpperBound().isErroneous()) {
   812                     return args.head;
   813                 }
   814                 args = args.tail;
   815                 tvars = tvars.tail;
   816             }
   818             args = type.getTypeArguments();
   819             tvars = tvars_buf.toList();
   821             for (Type arg : types.capture(type).getTypeArguments()) {
   822                 if (arg.tag == TYPEVAR &&
   823                         arg.getUpperBound().isErroneous() &&
   824                         !tvars.head.getUpperBound().isErroneous()) {
   825                     return args.head;
   826                 }
   827                 tvars = tvars.tail;
   828             }
   830             return null;
   831         }
   833     /** Check that given modifiers are legal for given symbol and
   834      *  return modifiers together with any implicit modififiers for that symbol.
   835      *  Warning: we can't use flags() here since this method
   836      *  is called during class enter, when flags() would cause a premature
   837      *  completion.
   838      *  @param pos           Position to be used for error reporting.
   839      *  @param flags         The set of modifiers given in a definition.
   840      *  @param sym           The defined symbol.
   841      */
   842     long checkFlags(DiagnosticPosition pos, long flags, Symbol sym, JCTree tree) {
   843         long mask;
   844         long implicit = 0;
   845         switch (sym.kind) {
   846         case VAR:
   847             if (sym.owner.kind != TYP)
   848                 mask = LocalVarFlags;
   849             else if ((sym.owner.flags_field & INTERFACE) != 0)
   850                 mask = implicit = InterfaceVarFlags;
   851             else
   852                 mask = VarFlags;
   853             break;
   854         case MTH:
   855             if (sym.name == names.init) {
   856                 if ((sym.owner.flags_field & ENUM) != 0) {
   857                     // enum constructors cannot be declared public or
   858                     // protected and must be implicitly or explicitly
   859                     // private
   860                     implicit = PRIVATE;
   861                     mask = PRIVATE;
   862                 } else
   863                     mask = ConstructorFlags;
   864             }  else if ((sym.owner.flags_field & INTERFACE) != 0)
   865                 mask = implicit = InterfaceMethodFlags;
   866             else {
   867                 mask = MethodFlags;
   868             }
   869             // Imply STRICTFP if owner has STRICTFP set.
   870             if (((flags|implicit) & Flags.ABSTRACT) == 0)
   871               implicit |= sym.owner.flags_field & STRICTFP;
   872             break;
   873         case TYP:
   874             if (sym.isLocal()) {
   875                 mask = LocalClassFlags;
   876                 if (sym.name.isEmpty()) { // Anonymous class
   877                     // Anonymous classes in static methods are themselves static;
   878                     // that's why we admit STATIC here.
   879                     mask |= STATIC;
   880                     // JLS: Anonymous classes are final.
   881                     implicit |= FINAL;
   882                 }
   883                 if ((sym.owner.flags_field & STATIC) == 0 &&
   884                     (flags & ENUM) != 0)
   885                     log.error(pos, "enums.must.be.static");
   886             } else if (sym.owner.kind == TYP) {
   887                 mask = MemberClassFlags;
   888                 if (sym.owner.owner.kind == PCK ||
   889                     (sym.owner.flags_field & STATIC) != 0)
   890                     mask |= STATIC;
   891                 else if ((flags & ENUM) != 0)
   892                     log.error(pos, "enums.must.be.static");
   893                 // Nested interfaces and enums are always STATIC (Spec ???)
   894                 if ((flags & (INTERFACE | ENUM)) != 0 ) implicit = STATIC;
   895             } else {
   896                 mask = ClassFlags;
   897             }
   898             // Interfaces are always ABSTRACT
   899             if ((flags & INTERFACE) != 0) implicit |= ABSTRACT;
   901             if ((flags & ENUM) != 0) {
   902                 // enums can't be declared abstract or final
   903                 mask &= ~(ABSTRACT | FINAL);
   904                 implicit |= implicitEnumFinalFlag(tree);
   905             }
   906             // Imply STRICTFP if owner has STRICTFP set.
   907             implicit |= sym.owner.flags_field & STRICTFP;
   908             break;
   909         default:
   910             throw new AssertionError();
   911         }
   912         long illegal = flags & StandardFlags & ~mask;
   913         if (illegal != 0) {
   914             if ((illegal & INTERFACE) != 0) {
   915                 log.error(pos, "intf.not.allowed.here");
   916                 mask |= INTERFACE;
   917             }
   918             else {
   919                 log.error(pos,
   920                           "mod.not.allowed.here", asFlagSet(illegal));
   921             }
   922         }
   923         else if ((sym.kind == TYP ||
   924                   // ISSUE: Disallowing abstract&private is no longer appropriate
   925                   // in the presence of inner classes. Should it be deleted here?
   926                   checkDisjoint(pos, flags,
   927                                 ABSTRACT,
   928                                 PRIVATE | STATIC))
   929                  &&
   930                  checkDisjoint(pos, flags,
   931                                ABSTRACT | INTERFACE,
   932                                FINAL | NATIVE | SYNCHRONIZED)
   933                  &&
   934                  checkDisjoint(pos, flags,
   935                                PUBLIC,
   936                                PRIVATE | PROTECTED)
   937                  &&
   938                  checkDisjoint(pos, flags,
   939                                PRIVATE,
   940                                PUBLIC | PROTECTED)
   941                  &&
   942                  checkDisjoint(pos, flags,
   943                                FINAL,
   944                                VOLATILE)
   945                  &&
   946                  (sym.kind == TYP ||
   947                   checkDisjoint(pos, flags,
   948                                 ABSTRACT | NATIVE,
   949                                 STRICTFP))) {
   950             // skip
   951         }
   952         return flags & (mask | ~StandardFlags) | implicit;
   953     }
   956     /** Determine if this enum should be implicitly final.
   957      *
   958      *  If the enum has no specialized enum contants, it is final.
   959      *
   960      *  If the enum does have specialized enum contants, it is
   961      *  <i>not</i> final.
   962      */
   963     private long implicitEnumFinalFlag(JCTree tree) {
   964         if (tree.getTag() != JCTree.CLASSDEF) return 0;
   965         class SpecialTreeVisitor extends JCTree.Visitor {
   966             boolean specialized;
   967             SpecialTreeVisitor() {
   968                 this.specialized = false;
   969             };
   971             @Override
   972             public void visitTree(JCTree tree) { /* no-op */ }
   974             @Override
   975             public void visitVarDef(JCVariableDecl tree) {
   976                 if ((tree.mods.flags & ENUM) != 0) {
   977                     if (tree.init instanceof JCNewClass &&
   978                         ((JCNewClass) tree.init).def != null) {
   979                         specialized = true;
   980                     }
   981                 }
   982             }
   983         }
   985         SpecialTreeVisitor sts = new SpecialTreeVisitor();
   986         JCClassDecl cdef = (JCClassDecl) tree;
   987         for (JCTree defs: cdef.defs) {
   988             defs.accept(sts);
   989             if (sts.specialized) return 0;
   990         }
   991         return FINAL;
   992     }
   994 /* *************************************************************************
   995  * Type Validation
   996  **************************************************************************/
   998     /** Validate a type expression. That is,
   999      *  check that all type arguments of a parametric type are within
  1000      *  their bounds. This must be done in a second phase after type attributon
  1001      *  since a class might have a subclass as type parameter bound. E.g:
  1003      *  class B<A extends C> { ... }
  1004      *  class C extends B<C> { ... }
  1006      *  and we can't make sure that the bound is already attributed because
  1007      *  of possible cycles.
  1009      * Visitor method: Validate a type expression, if it is not null, catching
  1010      *  and reporting any completion failures.
  1011      */
  1012     void validate(JCTree tree, Env<AttrContext> env) {
  1013         validate(tree, env, true);
  1015     void validate(JCTree tree, Env<AttrContext> env, boolean checkRaw) {
  1016         new Validator(env).validateTree(tree, checkRaw, true);
  1019     /** Visitor method: Validate a list of type expressions.
  1020      */
  1021     void validate(List<? extends JCTree> trees, Env<AttrContext> env) {
  1022         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1023             validate(l.head, env);
  1026     /** A visitor class for type validation.
  1027      */
  1028     class Validator extends JCTree.Visitor {
  1030         boolean isOuter;
  1031         Env<AttrContext> env;
  1033         Validator(Env<AttrContext> env) {
  1034             this.env = env;
  1037         @Override
  1038         public void visitTypeArray(JCArrayTypeTree tree) {
  1039             tree.elemtype.accept(this);
  1042         @Override
  1043         public void visitTypeApply(JCTypeApply tree) {
  1044             if (tree.type.tag == CLASS) {
  1045                 List<JCExpression> args = tree.arguments;
  1046                 List<Type> forms = tree.type.tsym.type.getTypeArguments();
  1048                 Type incompatibleArg = firstIncompatibleTypeArg(tree.type);
  1049                 if (incompatibleArg != null) {
  1050                     for (JCTree arg : tree.arguments) {
  1051                         if (arg.type == incompatibleArg) {
  1052                             log.error(arg, "not.within.bounds", incompatibleArg, forms.head);
  1054                         forms = forms.tail;
  1058                 forms = tree.type.tsym.type.getTypeArguments();
  1060                 boolean is_java_lang_Class = tree.type.tsym.flatName() == names.java_lang_Class;
  1062                 // For matching pairs of actual argument types `a' and
  1063                 // formal type parameters with declared bound `b' ...
  1064                 while (args.nonEmpty() && forms.nonEmpty()) {
  1065                     validateTree(args.head,
  1066                             !(isOuter && is_java_lang_Class),
  1067                             false);
  1068                     args = args.tail;
  1069                     forms = forms.tail;
  1072                 // Check that this type is either fully parameterized, or
  1073                 // not parameterized at all.
  1074                 if (tree.type.getEnclosingType().isRaw())
  1075                     log.error(tree.pos(), "improperly.formed.type.inner.raw.param");
  1076                 if (tree.clazz.getTag() == JCTree.SELECT)
  1077                     visitSelectInternal((JCFieldAccess)tree.clazz);
  1081         @Override
  1082         public void visitTypeParameter(JCTypeParameter tree) {
  1083             validateTrees(tree.bounds, true, isOuter);
  1084             checkClassBounds(tree.pos(), tree.type);
  1087         @Override
  1088         public void visitWildcard(JCWildcard tree) {
  1089             if (tree.inner != null)
  1090                 validateTree(tree.inner, true, isOuter);
  1093         @Override
  1094         public void visitSelect(JCFieldAccess tree) {
  1095             if (tree.type.tag == CLASS) {
  1096                 visitSelectInternal(tree);
  1098                 // Check that this type is either fully parameterized, or
  1099                 // not parameterized at all.
  1100                 if (tree.selected.type.isParameterized() && tree.type.tsym.type.getTypeArguments().nonEmpty())
  1101                     log.error(tree.pos(), "improperly.formed.type.param.missing");
  1105         public void visitSelectInternal(JCFieldAccess tree) {
  1106             if (tree.type.tsym.isStatic() &&
  1107                 tree.selected.type.isParameterized()) {
  1108                 // The enclosing type is not a class, so we are
  1109                 // looking at a static member type.  However, the
  1110                 // qualifying expression is parameterized.
  1111                 log.error(tree.pos(), "cant.select.static.class.from.param.type");
  1112             } else {
  1113                 // otherwise validate the rest of the expression
  1114                 tree.selected.accept(this);
  1118         /** Default visitor method: do nothing.
  1119          */
  1120         @Override
  1121         public void visitTree(JCTree tree) {
  1124         public void validateTree(JCTree tree, boolean checkRaw, boolean isOuter) {
  1125             try {
  1126                 if (tree != null) {
  1127                     this.isOuter = isOuter;
  1128                     tree.accept(this);
  1129                     if (checkRaw)
  1130                         checkRaw(tree, env);
  1132             } catch (CompletionFailure ex) {
  1133                 completionError(tree.pos(), ex);
  1137         public void validateTrees(List<? extends JCTree> trees, boolean checkRaw, boolean isOuter) {
  1138             for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
  1139                 validateTree(l.head, checkRaw, isOuter);
  1142         void checkRaw(JCTree tree, Env<AttrContext> env) {
  1143             if (lint.isEnabled(LintCategory.RAW) &&
  1144                 tree.type.tag == CLASS &&
  1145                 !TreeInfo.isDiamond(tree) &&
  1146                 !env.enclClass.name.isEmpty() &&  //anonymous or intersection
  1147                 tree.type.isRaw()) {
  1148                 log.warning(LintCategory.RAW,
  1149                         tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
  1154 /* *************************************************************************
  1155  * Exception checking
  1156  **************************************************************************/
  1158     /* The following methods treat classes as sets that contain
  1159      * the class itself and all their subclasses
  1160      */
  1162     /** Is given type a subtype of some of the types in given list?
  1163      */
  1164     boolean subset(Type t, List<Type> ts) {
  1165         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1166             if (types.isSubtype(t, l.head)) return true;
  1167         return false;
  1170     /** Is given type a subtype or supertype of
  1171      *  some of the types in given list?
  1172      */
  1173     boolean intersects(Type t, List<Type> ts) {
  1174         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
  1175             if (types.isSubtype(t, l.head) || types.isSubtype(l.head, t)) return true;
  1176         return false;
  1179     /** Add type set to given type list, unless it is a subclass of some class
  1180      *  in the list.
  1181      */
  1182     List<Type> incl(Type t, List<Type> ts) {
  1183         return subset(t, ts) ? ts : excl(t, ts).prepend(t);
  1186     /** Remove type set from type set list.
  1187      */
  1188     List<Type> excl(Type t, List<Type> ts) {
  1189         if (ts.isEmpty()) {
  1190             return ts;
  1191         } else {
  1192             List<Type> ts1 = excl(t, ts.tail);
  1193             if (types.isSubtype(ts.head, t)) return ts1;
  1194             else if (ts1 == ts.tail) return ts;
  1195             else return ts1.prepend(ts.head);
  1199     /** Form the union of two type set lists.
  1200      */
  1201     List<Type> union(List<Type> ts1, List<Type> ts2) {
  1202         List<Type> ts = ts1;
  1203         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1204             ts = incl(l.head, ts);
  1205         return ts;
  1208     /** Form the difference of two type lists.
  1209      */
  1210     List<Type> diff(List<Type> ts1, List<Type> ts2) {
  1211         List<Type> ts = ts1;
  1212         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1213             ts = excl(l.head, ts);
  1214         return ts;
  1217     /** Form the intersection of two type lists.
  1218      */
  1219     public List<Type> intersect(List<Type> ts1, List<Type> ts2) {
  1220         List<Type> ts = List.nil();
  1221         for (List<Type> l = ts1; l.nonEmpty(); l = l.tail)
  1222             if (subset(l.head, ts2)) ts = incl(l.head, ts);
  1223         for (List<Type> l = ts2; l.nonEmpty(); l = l.tail)
  1224             if (subset(l.head, ts1)) ts = incl(l.head, ts);
  1225         return ts;
  1228     /** Is exc an exception symbol that need not be declared?
  1229      */
  1230     boolean isUnchecked(ClassSymbol exc) {
  1231         return
  1232             exc.kind == ERR ||
  1233             exc.isSubClass(syms.errorType.tsym, types) ||
  1234             exc.isSubClass(syms.runtimeExceptionType.tsym, types);
  1237     /** Is exc an exception type that need not be declared?
  1238      */
  1239     boolean isUnchecked(Type exc) {
  1240         return
  1241             (exc.tag == TYPEVAR) ? isUnchecked(types.supertype(exc)) :
  1242             (exc.tag == CLASS) ? isUnchecked((ClassSymbol)exc.tsym) :
  1243             exc.tag == BOT;
  1246     /** Same, but handling completion failures.
  1247      */
  1248     boolean isUnchecked(DiagnosticPosition pos, Type exc) {
  1249         try {
  1250             return isUnchecked(exc);
  1251         } catch (CompletionFailure ex) {
  1252             completionError(pos, ex);
  1253             return true;
  1257     /** Is exc handled by given exception list?
  1258      */
  1259     boolean isHandled(Type exc, List<Type> handled) {
  1260         return isUnchecked(exc) || subset(exc, handled);
  1263     /** Return all exceptions in thrown list that are not in handled list.
  1264      *  @param thrown     The list of thrown exceptions.
  1265      *  @param handled    The list of handled exceptions.
  1266      */
  1267     List<Type> unhandled(List<Type> thrown, List<Type> handled) {
  1268         List<Type> unhandled = List.nil();
  1269         for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
  1270             if (!isHandled(l.head, handled)) unhandled = unhandled.prepend(l.head);
  1271         return unhandled;
  1274 /* *************************************************************************
  1275  * Overriding/Implementation checking
  1276  **************************************************************************/
  1278     /** The level of access protection given by a flag set,
  1279      *  where PRIVATE is highest and PUBLIC is lowest.
  1280      */
  1281     static int protection(long flags) {
  1282         switch ((short)(flags & AccessFlags)) {
  1283         case PRIVATE: return 3;
  1284         case PROTECTED: return 1;
  1285         default:
  1286         case PUBLIC: return 0;
  1287         case 0: return 2;
  1291     /** A customized "cannot override" error message.
  1292      *  @param m      The overriding method.
  1293      *  @param other  The overridden method.
  1294      *  @return       An internationalized string.
  1295      */
  1296     Object cannotOverride(MethodSymbol m, MethodSymbol other) {
  1297         String key;
  1298         if ((other.owner.flags() & INTERFACE) == 0)
  1299             key = "cant.override";
  1300         else if ((m.owner.flags() & INTERFACE) == 0)
  1301             key = "cant.implement";
  1302         else
  1303             key = "clashes.with";
  1304         return diags.fragment(key, m, m.location(), other, other.location());
  1307     /** A customized "override" warning message.
  1308      *  @param m      The overriding method.
  1309      *  @param other  The overridden method.
  1310      *  @return       An internationalized string.
  1311      */
  1312     Object uncheckedOverrides(MethodSymbol m, MethodSymbol other) {
  1313         String key;
  1314         if ((other.owner.flags() & INTERFACE) == 0)
  1315             key = "unchecked.override";
  1316         else if ((m.owner.flags() & INTERFACE) == 0)
  1317             key = "unchecked.implement";
  1318         else
  1319             key = "unchecked.clash.with";
  1320         return diags.fragment(key, m, m.location(), other, other.location());
  1323     /** A customized "override" warning message.
  1324      *  @param m      The overriding method.
  1325      *  @param other  The overridden method.
  1326      *  @return       An internationalized string.
  1327      */
  1328     Object varargsOverrides(MethodSymbol m, MethodSymbol other) {
  1329         String key;
  1330         if ((other.owner.flags() & INTERFACE) == 0)
  1331             key = "varargs.override";
  1332         else  if ((m.owner.flags() & INTERFACE) == 0)
  1333             key = "varargs.implement";
  1334         else
  1335             key = "varargs.clash.with";
  1336         return diags.fragment(key, m, m.location(), other, other.location());
  1339     /** Check that this method conforms with overridden method 'other'.
  1340      *  where `origin' is the class where checking started.
  1341      *  Complications:
  1342      *  (1) Do not check overriding of synthetic methods
  1343      *      (reason: they might be final).
  1344      *      todo: check whether this is still necessary.
  1345      *  (2) Admit the case where an interface proxy throws fewer exceptions
  1346      *      than the method it implements. Augment the proxy methods with the
  1347      *      undeclared exceptions in this case.
  1348      *  (3) When generics are enabled, admit the case where an interface proxy
  1349      *      has a result type
  1350      *      extended by the result type of the method it implements.
  1351      *      Change the proxies result type to the smaller type in this case.
  1353      *  @param tree         The tree from which positions
  1354      *                      are extracted for errors.
  1355      *  @param m            The overriding method.
  1356      *  @param other        The overridden method.
  1357      *  @param origin       The class of which the overriding method
  1358      *                      is a member.
  1359      */
  1360     void checkOverride(JCTree tree,
  1361                        MethodSymbol m,
  1362                        MethodSymbol other,
  1363                        ClassSymbol origin) {
  1364         // Don't check overriding of synthetic methods or by bridge methods.
  1365         if ((m.flags() & (SYNTHETIC|BRIDGE)) != 0 || (other.flags() & SYNTHETIC) != 0) {
  1366             return;
  1369         // Error if static method overrides instance method (JLS 8.4.6.2).
  1370         if ((m.flags() & STATIC) != 0 &&
  1371                    (other.flags() & STATIC) == 0) {
  1372             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.static",
  1373                       cannotOverride(m, other));
  1374             return;
  1377         // Error if instance method overrides static or final
  1378         // method (JLS 8.4.6.1).
  1379         if ((other.flags() & FINAL) != 0 ||
  1380                  (m.flags() & STATIC) == 0 &&
  1381                  (other.flags() & STATIC) != 0) {
  1382             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.meth",
  1383                       cannotOverride(m, other),
  1384                       asFlagSet(other.flags() & (FINAL | STATIC)));
  1385             return;
  1388         if ((m.owner.flags() & ANNOTATION) != 0) {
  1389             // handled in validateAnnotationMethod
  1390             return;
  1393         // Error if overriding method has weaker access (JLS 8.4.6.3).
  1394         if ((origin.flags() & INTERFACE) == 0 &&
  1395                  protection(m.flags()) > protection(other.flags())) {
  1396             log.error(TreeInfo.diagnosticPositionFor(m, tree), "override.weaker.access",
  1397                       cannotOverride(m, other),
  1398                       other.flags() == 0 ?
  1399                           Flag.PACKAGE :
  1400                           asFlagSet(other.flags() & AccessFlags));
  1401             return;
  1404         Type mt = types.memberType(origin.type, m);
  1405         Type ot = types.memberType(origin.type, other);
  1406         // Error if overriding result type is different
  1407         // (or, in the case of generics mode, not a subtype) of
  1408         // overridden result type. We have to rename any type parameters
  1409         // before comparing types.
  1410         List<Type> mtvars = mt.getTypeArguments();
  1411         List<Type> otvars = ot.getTypeArguments();
  1412         Type mtres = mt.getReturnType();
  1413         Type otres = types.subst(ot.getReturnType(), otvars, mtvars);
  1415         overrideWarner.clear();
  1416         boolean resultTypesOK =
  1417             types.returnTypeSubstitutable(mt, ot, otres, overrideWarner);
  1418         if (!resultTypesOK) {
  1419             if (!allowCovariantReturns &&
  1420                 m.owner != origin &&
  1421                 m.owner.isSubClass(other.owner, types)) {
  1422                 // allow limited interoperability with covariant returns
  1423             } else {
  1424                 log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1425                           "override.incompatible.ret",
  1426                           cannotOverride(m, other),
  1427                           mtres, otres);
  1428                 return;
  1430         } else if (overrideWarner.hasNonSilentLint(LintCategory.UNCHECKED)) {
  1431             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1432                     "override.unchecked.ret",
  1433                     uncheckedOverrides(m, other),
  1434                     mtres, otres);
  1437         // Error if overriding method throws an exception not reported
  1438         // by overridden method.
  1439         List<Type> otthrown = types.subst(ot.getThrownTypes(), otvars, mtvars);
  1440         List<Type> unhandledErased = unhandled(mt.getThrownTypes(), types.erasure(otthrown));
  1441         List<Type> unhandledUnerased = unhandled(mt.getThrownTypes(), otthrown);
  1442         if (unhandledErased.nonEmpty()) {
  1443             log.error(TreeInfo.diagnosticPositionFor(m, tree),
  1444                       "override.meth.doesnt.throw",
  1445                       cannotOverride(m, other),
  1446                       unhandledUnerased.head);
  1447             return;
  1449         else if (unhandledUnerased.nonEmpty()) {
  1450             warnUnchecked(TreeInfo.diagnosticPositionFor(m, tree),
  1451                           "override.unchecked.thrown",
  1452                          cannotOverride(m, other),
  1453                          unhandledUnerased.head);
  1454             return;
  1457         // Optional warning if varargs don't agree
  1458         if ((((m.flags() ^ other.flags()) & Flags.VARARGS) != 0)
  1459             && lint.isEnabled(LintCategory.OVERRIDES)) {
  1460             log.warning(TreeInfo.diagnosticPositionFor(m, tree),
  1461                         ((m.flags() & Flags.VARARGS) != 0)
  1462                         ? "override.varargs.missing"
  1463                         : "override.varargs.extra",
  1464                         varargsOverrides(m, other));
  1467         // Warn if instance method overrides bridge method (compiler spec ??)
  1468         if ((other.flags() & BRIDGE) != 0) {
  1469             log.warning(TreeInfo.diagnosticPositionFor(m, tree), "override.bridge",
  1470                         uncheckedOverrides(m, other));
  1473         // Warn if a deprecated method overridden by a non-deprecated one.
  1474         if (!isDeprecatedOverrideIgnorable(other, origin)) {
  1475             checkDeprecated(TreeInfo.diagnosticPositionFor(m, tree), m, other);
  1478     // where
  1479         private boolean isDeprecatedOverrideIgnorable(MethodSymbol m, ClassSymbol origin) {
  1480             // If the method, m, is defined in an interface, then ignore the issue if the method
  1481             // is only inherited via a supertype and also implemented in the supertype,
  1482             // because in that case, we will rediscover the issue when examining the method
  1483             // in the supertype.
  1484             // If the method, m, is not defined in an interface, then the only time we need to
  1485             // address the issue is when the method is the supertype implemementation: any other
  1486             // case, we will have dealt with when examining the supertype classes
  1487             ClassSymbol mc = m.enclClass();
  1488             Type st = types.supertype(origin.type);
  1489             if (st.tag != CLASS)
  1490                 return true;
  1491             MethodSymbol stimpl = m.implementation((ClassSymbol)st.tsym, types, false);
  1493             if (mc != null && ((mc.flags() & INTERFACE) != 0)) {
  1494                 List<Type> intfs = types.interfaces(origin.type);
  1495                 return (intfs.contains(mc.type) ? false : (stimpl != null));
  1497             else
  1498                 return (stimpl != m);
  1502     // used to check if there were any unchecked conversions
  1503     Warner overrideWarner = new Warner();
  1505     /** Check that a class does not inherit two concrete methods
  1506      *  with the same signature.
  1507      *  @param pos          Position to be used for error reporting.
  1508      *  @param site         The class type to be checked.
  1509      */
  1510     public void checkCompatibleConcretes(DiagnosticPosition pos, Type site) {
  1511         Type sup = types.supertype(site);
  1512         if (sup.tag != CLASS) return;
  1514         for (Type t1 = sup;
  1515              t1.tsym.type.isParameterized();
  1516              t1 = types.supertype(t1)) {
  1517             for (Scope.Entry e1 = t1.tsym.members().elems;
  1518                  e1 != null;
  1519                  e1 = e1.sibling) {
  1520                 Symbol s1 = e1.sym;
  1521                 if (s1.kind != MTH ||
  1522                     (s1.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1523                     !s1.isInheritedIn(site.tsym, types) ||
  1524                     ((MethodSymbol)s1).implementation(site.tsym,
  1525                                                       types,
  1526                                                       true) != s1)
  1527                     continue;
  1528                 Type st1 = types.memberType(t1, s1);
  1529                 int s1ArgsLength = st1.getParameterTypes().length();
  1530                 if (st1 == s1.type) continue;
  1532                 for (Type t2 = sup;
  1533                      t2.tag == CLASS;
  1534                      t2 = types.supertype(t2)) {
  1535                     for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name);
  1536                          e2.scope != null;
  1537                          e2 = e2.next()) {
  1538                         Symbol s2 = e2.sym;
  1539                         if (s2 == s1 ||
  1540                             s2.kind != MTH ||
  1541                             (s2.flags() & (STATIC|SYNTHETIC|BRIDGE)) != 0 ||
  1542                             s2.type.getParameterTypes().length() != s1ArgsLength ||
  1543                             !s2.isInheritedIn(site.tsym, types) ||
  1544                             ((MethodSymbol)s2).implementation(site.tsym,
  1545                                                               types,
  1546                                                               true) != s2)
  1547                             continue;
  1548                         Type st2 = types.memberType(t2, s2);
  1549                         if (types.overrideEquivalent(st1, st2))
  1550                             log.error(pos, "concrete.inheritance.conflict",
  1551                                       s1, t1, s2, t2, sup);
  1558     /** Check that classes (or interfaces) do not each define an abstract
  1559      *  method with same name and arguments but incompatible return types.
  1560      *  @param pos          Position to be used for error reporting.
  1561      *  @param t1           The first argument type.
  1562      *  @param t2           The second argument type.
  1563      */
  1564     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1565                                             Type t1,
  1566                                             Type t2) {
  1567         return checkCompatibleAbstracts(pos, t1, t2,
  1568                                         types.makeCompoundType(t1, t2));
  1571     public boolean checkCompatibleAbstracts(DiagnosticPosition pos,
  1572                                             Type t1,
  1573                                             Type t2,
  1574                                             Type site) {
  1575         return firstIncompatibility(pos, t1, t2, site) == null;
  1578     /** Return the first method which is defined with same args
  1579      *  but different return types in two given interfaces, or null if none
  1580      *  exists.
  1581      *  @param t1     The first type.
  1582      *  @param t2     The second type.
  1583      *  @param site   The most derived type.
  1584      *  @returns symbol from t2 that conflicts with one in t1.
  1585      */
  1586     private Symbol firstIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1587         Map<TypeSymbol,Type> interfaces1 = new HashMap<TypeSymbol,Type>();
  1588         closure(t1, interfaces1);
  1589         Map<TypeSymbol,Type> interfaces2;
  1590         if (t1 == t2)
  1591             interfaces2 = interfaces1;
  1592         else
  1593             closure(t2, interfaces1, interfaces2 = new HashMap<TypeSymbol,Type>());
  1595         for (Type t3 : interfaces1.values()) {
  1596             for (Type t4 : interfaces2.values()) {
  1597                 Symbol s = firstDirectIncompatibility(pos, t3, t4, site);
  1598                 if (s != null) return s;
  1601         return null;
  1604     /** Compute all the supertypes of t, indexed by type symbol. */
  1605     private void closure(Type t, Map<TypeSymbol,Type> typeMap) {
  1606         if (t.tag != CLASS) return;
  1607         if (typeMap.put(t.tsym, t) == null) {
  1608             closure(types.supertype(t), typeMap);
  1609             for (Type i : types.interfaces(t))
  1610                 closure(i, typeMap);
  1614     /** Compute all the supertypes of t, indexed by type symbol (except thise in typesSkip). */
  1615     private void closure(Type t, Map<TypeSymbol,Type> typesSkip, Map<TypeSymbol,Type> typeMap) {
  1616         if (t.tag != CLASS) return;
  1617         if (typesSkip.get(t.tsym) != null) return;
  1618         if (typeMap.put(t.tsym, t) == null) {
  1619             closure(types.supertype(t), typesSkip, typeMap);
  1620             for (Type i : types.interfaces(t))
  1621                 closure(i, typesSkip, typeMap);
  1625     /** Return the first method in t2 that conflicts with a method from t1. */
  1626     private Symbol firstDirectIncompatibility(DiagnosticPosition pos, Type t1, Type t2, Type site) {
  1627         for (Scope.Entry e1 = t1.tsym.members().elems; e1 != null; e1 = e1.sibling) {
  1628             Symbol s1 = e1.sym;
  1629             Type st1 = null;
  1630             if (s1.kind != MTH || !s1.isInheritedIn(site.tsym, types)) continue;
  1631             Symbol impl = ((MethodSymbol)s1).implementation(site.tsym, types, false);
  1632             if (impl != null && (impl.flags() & ABSTRACT) == 0) continue;
  1633             for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name); e2.scope != null; e2 = e2.next()) {
  1634                 Symbol s2 = e2.sym;
  1635                 if (s1 == s2) continue;
  1636                 if (s2.kind != MTH || !s2.isInheritedIn(site.tsym, types)) continue;
  1637                 if (st1 == null) st1 = types.memberType(t1, s1);
  1638                 Type st2 = types.memberType(t2, s2);
  1639                 if (types.overrideEquivalent(st1, st2)) {
  1640                     List<Type> tvars1 = st1.getTypeArguments();
  1641                     List<Type> tvars2 = st2.getTypeArguments();
  1642                     Type rt1 = st1.getReturnType();
  1643                     Type rt2 = types.subst(st2.getReturnType(), tvars2, tvars1);
  1644                     boolean compat =
  1645                         types.isSameType(rt1, rt2) ||
  1646                         rt1.tag >= CLASS && rt2.tag >= CLASS &&
  1647                         (types.covariantReturnType(rt1, rt2, Warner.noWarnings) ||
  1648                          types.covariantReturnType(rt2, rt1, Warner.noWarnings)) ||
  1649                          checkCommonOverriderIn(s1,s2,site);
  1650                     if (!compat) {
  1651                         log.error(pos, "types.incompatible.diff.ret",
  1652                             t1, t2, s2.name +
  1653                             "(" + types.memberType(t2, s2).getParameterTypes() + ")");
  1654                         return s2;
  1656                 } else if (!checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
  1657                     log.error(pos,
  1658                             "name.clash.same.erasure.no.override",
  1659                             s1, s1.location(),
  1660                             s2, s2.location());
  1661                     return s2;
  1665         return null;
  1667     //WHERE
  1668     boolean checkCommonOverriderIn(Symbol s1, Symbol s2, Type site) {
  1669         Map<TypeSymbol,Type> supertypes = new HashMap<TypeSymbol,Type>();
  1670         Type st1 = types.memberType(site, s1);
  1671         Type st2 = types.memberType(site, s2);
  1672         closure(site, supertypes);
  1673         for (Type t : supertypes.values()) {
  1674             for (Scope.Entry e = t.tsym.members().lookup(s1.name); e.scope != null; e = e.next()) {
  1675                 Symbol s3 = e.sym;
  1676                 if (s3 == s1 || s3 == s2 || s3.kind != MTH || (s3.flags() & (BRIDGE|SYNTHETIC)) != 0) continue;
  1677                 Type st3 = types.memberType(site,s3);
  1678                 if (types.overrideEquivalent(st3, st1) && types.overrideEquivalent(st3, st2)) {
  1679                     if (s3.owner == site.tsym) {
  1680                         return true;
  1682                     List<Type> tvars1 = st1.getTypeArguments();
  1683                     List<Type> tvars2 = st2.getTypeArguments();
  1684                     List<Type> tvars3 = st3.getTypeArguments();
  1685                     Type rt1 = st1.getReturnType();
  1686                     Type rt2 = st2.getReturnType();
  1687                     Type rt13 = types.subst(st3.getReturnType(), tvars3, tvars1);
  1688                     Type rt23 = types.subst(st3.getReturnType(), tvars3, tvars2);
  1689                     boolean compat =
  1690                         rt13.tag >= CLASS && rt23.tag >= CLASS &&
  1691                         (types.covariantReturnType(rt13, rt1, Warner.noWarnings) &&
  1692                          types.covariantReturnType(rt23, rt2, Warner.noWarnings));
  1693                     if (compat)
  1694                         return true;
  1698         return false;
  1701     /** Check that a given method conforms with any method it overrides.
  1702      *  @param tree         The tree from which positions are extracted
  1703      *                      for errors.
  1704      *  @param m            The overriding method.
  1705      */
  1706     void checkOverride(JCTree tree, MethodSymbol m) {
  1707         ClassSymbol origin = (ClassSymbol)m.owner;
  1708         if ((origin.flags() & ENUM) != 0 && names.finalize.equals(m.name))
  1709             if (m.overrides(syms.enumFinalFinalize, origin, types, false)) {
  1710                 log.error(tree.pos(), "enum.no.finalize");
  1711                 return;
  1713         for (Type t = origin.type; t.tag == CLASS;
  1714              t = types.supertype(t)) {
  1715             if (t != origin.type) {
  1716                 checkOverride(tree, t, origin, m);
  1718             for (Type t2 : types.interfaces(t)) {
  1719                 checkOverride(tree, t2, origin, m);
  1724     void checkOverride(JCTree tree, Type site, ClassSymbol origin, MethodSymbol m) {
  1725         TypeSymbol c = site.tsym;
  1726         Scope.Entry e = c.members().lookup(m.name);
  1727         while (e.scope != null) {
  1728             if (m.overrides(e.sym, origin, types, false)) {
  1729                 if ((e.sym.flags() & ABSTRACT) == 0) {
  1730                     checkOverride(tree, m, (MethodSymbol)e.sym, origin);
  1733             e = e.next();
  1737     private boolean checkNameClash(ClassSymbol origin, Symbol s1, Symbol s2) {
  1738         if (s1.kind == MTH &&
  1739                     s1.isInheritedIn(origin, types) &&
  1740                     (s1.flags() & SYNTHETIC) == 0 &&
  1741                     !s2.isConstructor()) {
  1742             Type er1 = s2.erasure(types);
  1743             Type er2 = s1.erasure(types);
  1744             if (types.isSameTypes(er1.getParameterTypes(),
  1745                     er2.getParameterTypes())) {
  1746                     return false;
  1749         return true;
  1753     /** Check that all abstract members of given class have definitions.
  1754      *  @param pos          Position to be used for error reporting.
  1755      *  @param c            The class.
  1756      */
  1757     void checkAllDefined(DiagnosticPosition pos, ClassSymbol c) {
  1758         try {
  1759             MethodSymbol undef = firstUndef(c, c);
  1760             if (undef != null) {
  1761                 if ((c.flags() & ENUM) != 0 &&
  1762                     types.supertype(c.type).tsym == syms.enumSym &&
  1763                     (c.flags() & FINAL) == 0) {
  1764                     // add the ABSTRACT flag to an enum
  1765                     c.flags_field |= ABSTRACT;
  1766                 } else {
  1767                     MethodSymbol undef1 =
  1768                         new MethodSymbol(undef.flags(), undef.name,
  1769                                          types.memberType(c.type, undef), undef.owner);
  1770                     log.error(pos, "does.not.override.abstract",
  1771                               c, undef1, undef1.location());
  1774         } catch (CompletionFailure ex) {
  1775             completionError(pos, ex);
  1778 //where
  1779         /** Return first abstract member of class `c' that is not defined
  1780          *  in `impl', null if there is none.
  1781          */
  1782         private MethodSymbol firstUndef(ClassSymbol impl, ClassSymbol c) {
  1783             MethodSymbol undef = null;
  1784             // Do not bother to search in classes that are not abstract,
  1785             // since they cannot have abstract members.
  1786             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
  1787                 Scope s = c.members();
  1788                 for (Scope.Entry e = s.elems;
  1789                      undef == null && e != null;
  1790                      e = e.sibling) {
  1791                     if (e.sym.kind == MTH &&
  1792                         (e.sym.flags() & (ABSTRACT|IPROXY)) == ABSTRACT) {
  1793                         MethodSymbol absmeth = (MethodSymbol)e.sym;
  1794                         MethodSymbol implmeth = absmeth.implementation(impl, types, true);
  1795                         if (implmeth == null || implmeth == absmeth)
  1796                             undef = absmeth;
  1799                 if (undef == null) {
  1800                     Type st = types.supertype(c.type);
  1801                     if (st.tag == CLASS)
  1802                         undef = firstUndef(impl, (ClassSymbol)st.tsym);
  1804                 for (List<Type> l = types.interfaces(c.type);
  1805                      undef == null && l.nonEmpty();
  1806                      l = l.tail) {
  1807                     undef = firstUndef(impl, (ClassSymbol)l.head.tsym);
  1810             return undef;
  1813     void checkNonCyclicDecl(JCClassDecl tree) {
  1814         CycleChecker cc = new CycleChecker();
  1815         cc.scan(tree);
  1816         if (!cc.errorFound && !cc.partialCheck) {
  1817             tree.sym.flags_field |= ACYCLIC;
  1821     class CycleChecker extends TreeScanner {
  1823         List<Symbol> seenClasses = List.nil();
  1824         boolean errorFound = false;
  1825         boolean partialCheck = false;
  1827         private void checkSymbol(DiagnosticPosition pos, Symbol sym) {
  1828             if (sym != null && sym.kind == TYP) {
  1829                 Env<AttrContext> classEnv = enter.getEnv((TypeSymbol)sym);
  1830                 if (classEnv != null) {
  1831                     DiagnosticSource prevSource = log.currentSource();
  1832                     try {
  1833                         log.useSource(classEnv.toplevel.sourcefile);
  1834                         scan(classEnv.tree);
  1836                     finally {
  1837                         log.useSource(prevSource.getFile());
  1839                 } else if (sym.kind == TYP) {
  1840                     checkClass(pos, sym, List.<JCTree>nil());
  1842             } else {
  1843                 //not completed yet
  1844                 partialCheck = true;
  1848         @Override
  1849         public void visitSelect(JCFieldAccess tree) {
  1850             super.visitSelect(tree);
  1851             checkSymbol(tree.pos(), tree.sym);
  1854         @Override
  1855         public void visitIdent(JCIdent tree) {
  1856             checkSymbol(tree.pos(), tree.sym);
  1859         @Override
  1860         public void visitTypeApply(JCTypeApply tree) {
  1861             scan(tree.clazz);
  1864         @Override
  1865         public void visitTypeArray(JCArrayTypeTree tree) {
  1866             scan(tree.elemtype);
  1869         @Override
  1870         public void visitClassDef(JCClassDecl tree) {
  1871             List<JCTree> supertypes = List.nil();
  1872             if (tree.getExtendsClause() != null) {
  1873                 supertypes = supertypes.prepend(tree.getExtendsClause());
  1875             if (tree.getImplementsClause() != null) {
  1876                 for (JCTree intf : tree.getImplementsClause()) {
  1877                     supertypes = supertypes.prepend(intf);
  1880             checkClass(tree.pos(), tree.sym, supertypes);
  1883         void checkClass(DiagnosticPosition pos, Symbol c, List<JCTree> supertypes) {
  1884             if ((c.flags_field & ACYCLIC) != 0)
  1885                 return;
  1886             if (seenClasses.contains(c)) {
  1887                 errorFound = true;
  1888                 noteCyclic(pos, (ClassSymbol)c);
  1889             } else if (!c.type.isErroneous()) {
  1890                 try {
  1891                     seenClasses = seenClasses.prepend(c);
  1892                     if (c.type.tag == CLASS) {
  1893                         if (supertypes.nonEmpty()) {
  1894                             scan(supertypes);
  1896                         else {
  1897                             ClassType ct = (ClassType)c.type;
  1898                             if (ct.supertype_field == null ||
  1899                                     ct.interfaces_field == null) {
  1900                                 //not completed yet
  1901                                 partialCheck = true;
  1902                                 return;
  1904                             checkSymbol(pos, ct.supertype_field.tsym);
  1905                             for (Type intf : ct.interfaces_field) {
  1906                                 checkSymbol(pos, intf.tsym);
  1909                         if (c.owner.kind == TYP) {
  1910                             checkSymbol(pos, c.owner);
  1913                 } finally {
  1914                     seenClasses = seenClasses.tail;
  1920     /** Check for cyclic references. Issue an error if the
  1921      *  symbol of the type referred to has a LOCKED flag set.
  1923      *  @param pos      Position to be used for error reporting.
  1924      *  @param t        The type referred to.
  1925      */
  1926     void checkNonCyclic(DiagnosticPosition pos, Type t) {
  1927         checkNonCyclicInternal(pos, t);
  1931     void checkNonCyclic(DiagnosticPosition pos, TypeVar t) {
  1932         checkNonCyclic1(pos, t, List.<TypeVar>nil());
  1935     private void checkNonCyclic1(DiagnosticPosition pos, Type t, List<TypeVar> seen) {
  1936         final TypeVar tv;
  1937         if  (t.tag == TYPEVAR && (t.tsym.flags() & UNATTRIBUTED) != 0)
  1938             return;
  1939         if (seen.contains(t)) {
  1940             tv = (TypeVar)t;
  1941             tv.bound = types.createErrorType(t);
  1942             log.error(pos, "cyclic.inheritance", t);
  1943         } else if (t.tag == TYPEVAR) {
  1944             tv = (TypeVar)t;
  1945             seen = seen.prepend(tv);
  1946             for (Type b : types.getBounds(tv))
  1947                 checkNonCyclic1(pos, b, seen);
  1951     /** Check for cyclic references. Issue an error if the
  1952      *  symbol of the type referred to has a LOCKED flag set.
  1954      *  @param pos      Position to be used for error reporting.
  1955      *  @param t        The type referred to.
  1956      *  @returns        True if the check completed on all attributed classes
  1957      */
  1958     private boolean checkNonCyclicInternal(DiagnosticPosition pos, Type t) {
  1959         boolean complete = true; // was the check complete?
  1960         //- System.err.println("checkNonCyclicInternal("+t+");");//DEBUG
  1961         Symbol c = t.tsym;
  1962         if ((c.flags_field & ACYCLIC) != 0) return true;
  1964         if ((c.flags_field & LOCKED) != 0) {
  1965             noteCyclic(pos, (ClassSymbol)c);
  1966         } else if (!c.type.isErroneous()) {
  1967             try {
  1968                 c.flags_field |= LOCKED;
  1969                 if (c.type.tag == CLASS) {
  1970                     ClassType clazz = (ClassType)c.type;
  1971                     if (clazz.interfaces_field != null)
  1972                         for (List<Type> l=clazz.interfaces_field; l.nonEmpty(); l=l.tail)
  1973                             complete &= checkNonCyclicInternal(pos, l.head);
  1974                     if (clazz.supertype_field != null) {
  1975                         Type st = clazz.supertype_field;
  1976                         if (st != null && st.tag == CLASS)
  1977                             complete &= checkNonCyclicInternal(pos, st);
  1979                     if (c.owner.kind == TYP)
  1980                         complete &= checkNonCyclicInternal(pos, c.owner.type);
  1982             } finally {
  1983                 c.flags_field &= ~LOCKED;
  1986         if (complete)
  1987             complete = ((c.flags_field & UNATTRIBUTED) == 0) && c.completer == null;
  1988         if (complete) c.flags_field |= ACYCLIC;
  1989         return complete;
  1992     /** Note that we found an inheritance cycle. */
  1993     private void noteCyclic(DiagnosticPosition pos, ClassSymbol c) {
  1994         log.error(pos, "cyclic.inheritance", c);
  1995         for (List<Type> l=types.interfaces(c.type); l.nonEmpty(); l=l.tail)
  1996             l.head = types.createErrorType((ClassSymbol)l.head.tsym, Type.noType);
  1997         Type st = types.supertype(c.type);
  1998         if (st.tag == CLASS)
  1999             ((ClassType)c.type).supertype_field = types.createErrorType((ClassSymbol)st.tsym, Type.noType);
  2000         c.type = types.createErrorType(c, c.type);
  2001         c.flags_field |= ACYCLIC;
  2004     /** Check that all methods which implement some
  2005      *  method conform to the method they implement.
  2006      *  @param tree         The class definition whose members are checked.
  2007      */
  2008     void checkImplementations(JCClassDecl tree) {
  2009         checkImplementations(tree, tree.sym);
  2011 //where
  2012         /** Check that all methods which implement some
  2013          *  method in `ic' conform to the method they implement.
  2014          */
  2015         void checkImplementations(JCClassDecl tree, ClassSymbol ic) {
  2016             ClassSymbol origin = tree.sym;
  2017             for (List<Type> l = types.closure(ic.type); l.nonEmpty(); l = l.tail) {
  2018                 ClassSymbol lc = (ClassSymbol)l.head.tsym;
  2019                 if ((allowGenerics || origin != lc) && (lc.flags() & ABSTRACT) != 0) {
  2020                     for (Scope.Entry e=lc.members().elems; e != null; e=e.sibling) {
  2021                         if (e.sym.kind == MTH &&
  2022                             (e.sym.flags() & (STATIC|ABSTRACT)) == ABSTRACT) {
  2023                             MethodSymbol absmeth = (MethodSymbol)e.sym;
  2024                             MethodSymbol implmeth = absmeth.implementation(origin, types, false);
  2025                             if (implmeth != null && implmeth != absmeth &&
  2026                                 (implmeth.owner.flags() & INTERFACE) ==
  2027                                 (origin.flags() & INTERFACE)) {
  2028                                 // don't check if implmeth is in a class, yet
  2029                                 // origin is an interface. This case arises only
  2030                                 // if implmeth is declared in Object. The reason is
  2031                                 // that interfaces really don't inherit from
  2032                                 // Object it's just that the compiler represents
  2033                                 // things that way.
  2034                                 checkOverride(tree, implmeth, absmeth, origin);
  2042     /** Check that all abstract methods implemented by a class are
  2043      *  mutually compatible.
  2044      *  @param pos          Position to be used for error reporting.
  2045      *  @param c            The class whose interfaces are checked.
  2046      */
  2047     void checkCompatibleSupertypes(DiagnosticPosition pos, Type c) {
  2048         List<Type> supertypes = types.interfaces(c);
  2049         Type supertype = types.supertype(c);
  2050         if (supertype.tag == CLASS &&
  2051             (supertype.tsym.flags() & ABSTRACT) != 0)
  2052             supertypes = supertypes.prepend(supertype);
  2053         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2054             if (allowGenerics && !l.head.getTypeArguments().isEmpty() &&
  2055                 !checkCompatibleAbstracts(pos, l.head, l.head, c))
  2056                 return;
  2057             for (List<Type> m = supertypes; m != l; m = m.tail)
  2058                 if (!checkCompatibleAbstracts(pos, l.head, m.head, c))
  2059                     return;
  2061         checkCompatibleConcretes(pos, c);
  2064     void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) {
  2065         for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) {
  2066             for (Scope.Entry e = ct.tsym.members().lookup(sym.name); e.scope == ct.tsym.members(); e = e.next()) {
  2067                 // VM allows methods and variables with differing types
  2068                 if (sym.kind == e.sym.kind &&
  2069                     types.isSameType(types.erasure(sym.type), types.erasure(e.sym.type)) &&
  2070                     sym != e.sym &&
  2071                     (sym.flags() & Flags.SYNTHETIC) != (e.sym.flags() & Flags.SYNTHETIC) &&
  2072                     (sym.flags() & IPROXY) == 0 && (e.sym.flags() & IPROXY) == 0 &&
  2073                     (sym.flags() & BRIDGE) == 0 && (e.sym.flags() & BRIDGE) == 0) {
  2074                     syntheticError(pos, (e.sym.flags() & SYNTHETIC) == 0 ? e.sym : sym);
  2075                     return;
  2081     /** Check that all non-override equivalent methods accessible from 'site'
  2082      *  are mutually compatible (JLS 8.4.8/9.4.1).
  2084      *  @param pos  Position to be used for error reporting.
  2085      *  @param site The class whose methods are checked.
  2086      *  @param sym  The method symbol to be checked.
  2087      */
  2088     void checkClashes(DiagnosticPosition pos, Type site, Symbol sym) {
  2089         List<Type> supertypes = types.closure(site);
  2090         for (List<Type> l = supertypes; l.nonEmpty(); l = l.tail) {
  2091             for (List<Type> m = supertypes; m.nonEmpty(); m = m.tail) {
  2092                 checkClashes(pos, l.head, m.head, site, sym);
  2097     /** Reports an error whenever 'sym' seen as a member of type 't1' clashes with
  2098      *  some unrelated method defined in 't2'.
  2099      */
  2100     private void checkClashes(DiagnosticPosition pos, Type t1, Type t2, Type site, Symbol s1) {
  2101         ClashFilter cf = new ClashFilter(site);
  2102         s1 = ((MethodSymbol)s1).implementedIn(t1.tsym, types);
  2103         if (s1 == null) return;
  2104         Type st1 = types.memberType(site, s1);
  2105         for (Scope.Entry e2 = t2.tsym.members().lookup(s1.name, cf); e2.scope != null; e2 = e2.next(cf)) {
  2106             Symbol s2 = e2.sym;
  2107             if (s1 == s2) continue;
  2108             Type st2 = types.memberType(site, s2);
  2109             if (!types.overrideEquivalent(st1, st2) &&
  2110                     !checkNameClash((ClassSymbol)site.tsym, s1, s2)) {
  2111                 log.error(pos,
  2112                         "name.clash.same.erasure.no.override",
  2113                         s1, s1.location(),
  2114                         s2, s2.location());
  2118     //where
  2119     private class ClashFilter implements Filter<Symbol> {
  2121         Type site;
  2123         ClashFilter(Type site) {
  2124             this.site = site;
  2127         public boolean accepts(Symbol s) {
  2128             return s.kind == MTH &&
  2129                     (s.flags() & (SYNTHETIC | CLASH)) == 0 &&
  2130                     s.isInheritedIn(site.tsym, types) &&
  2131                     !s.isConstructor();
  2135     /** Report a conflict between a user symbol and a synthetic symbol.
  2136      */
  2137     private void syntheticError(DiagnosticPosition pos, Symbol sym) {
  2138         if (!sym.type.isErroneous()) {
  2139             if (warnOnSyntheticConflicts) {
  2140                 log.warning(pos, "synthetic.name.conflict", sym, sym.location());
  2142             else {
  2143                 log.error(pos, "synthetic.name.conflict", sym, sym.location());
  2148     /** Check that class c does not implement directly or indirectly
  2149      *  the same parameterized interface with two different argument lists.
  2150      *  @param pos          Position to be used for error reporting.
  2151      *  @param type         The type whose interfaces are checked.
  2152      */
  2153     void checkClassBounds(DiagnosticPosition pos, Type type) {
  2154         checkClassBounds(pos, new HashMap<TypeSymbol,Type>(), type);
  2156 //where
  2157         /** Enter all interfaces of type `type' into the hash table `seensofar'
  2158          *  with their class symbol as key and their type as value. Make
  2159          *  sure no class is entered with two different types.
  2160          */
  2161         void checkClassBounds(DiagnosticPosition pos,
  2162                               Map<TypeSymbol,Type> seensofar,
  2163                               Type type) {
  2164             if (type.isErroneous()) return;
  2165             for (List<Type> l = types.interfaces(type); l.nonEmpty(); l = l.tail) {
  2166                 Type it = l.head;
  2167                 Type oldit = seensofar.put(it.tsym, it);
  2168                 if (oldit != null) {
  2169                     List<Type> oldparams = oldit.allparams();
  2170                     List<Type> newparams = it.allparams();
  2171                     if (!types.containsTypeEquivalent(oldparams, newparams))
  2172                         log.error(pos, "cant.inherit.diff.arg",
  2173                                   it.tsym, Type.toString(oldparams),
  2174                                   Type.toString(newparams));
  2176                 checkClassBounds(pos, seensofar, it);
  2178             Type st = types.supertype(type);
  2179             if (st != null) checkClassBounds(pos, seensofar, st);
  2182     /** Enter interface into into set.
  2183      *  If it existed already, issue a "repeated interface" error.
  2184      */
  2185     void checkNotRepeated(DiagnosticPosition pos, Type it, Set<Type> its) {
  2186         if (its.contains(it))
  2187             log.error(pos, "repeated.interface");
  2188         else {
  2189             its.add(it);
  2193 /* *************************************************************************
  2194  * Check annotations
  2195  **************************************************************************/
  2197     /**
  2198      * Recursively validate annotations values
  2199      */
  2200     void validateAnnotationTree(JCTree tree) {
  2201         class AnnotationValidator extends TreeScanner {
  2202             @Override
  2203             public void visitAnnotation(JCAnnotation tree) {
  2204                 super.visitAnnotation(tree);
  2205                 validateAnnotation(tree);
  2208         tree.accept(new AnnotationValidator());
  2211     /** Annotation types are restricted to primitives, String, an
  2212      *  enum, an annotation, Class, Class<?>, Class<? extends
  2213      *  Anything>, arrays of the preceding.
  2214      */
  2215     void validateAnnotationType(JCTree restype) {
  2216         // restype may be null if an error occurred, so don't bother validating it
  2217         if (restype != null) {
  2218             validateAnnotationType(restype.pos(), restype.type);
  2222     void validateAnnotationType(DiagnosticPosition pos, Type type) {
  2223         if (type.isPrimitive()) return;
  2224         if (types.isSameType(type, syms.stringType)) return;
  2225         if ((type.tsym.flags() & Flags.ENUM) != 0) return;
  2226         if ((type.tsym.flags() & Flags.ANNOTATION) != 0) return;
  2227         if (types.lowerBound(type).tsym == syms.classType.tsym) return;
  2228         if (types.isArray(type) && !types.isArray(types.elemtype(type))) {
  2229             validateAnnotationType(pos, types.elemtype(type));
  2230             return;
  2232         log.error(pos, "invalid.annotation.member.type");
  2235     /**
  2236      * "It is also a compile-time error if any method declared in an
  2237      * annotation type has a signature that is override-equivalent to
  2238      * that of any public or protected method declared in class Object
  2239      * or in the interface annotation.Annotation."
  2241      * @jls3 9.6 Annotation Types
  2242      */
  2243     void validateAnnotationMethod(DiagnosticPosition pos, MethodSymbol m) {
  2244         for (Type sup = syms.annotationType; sup.tag == CLASS; sup = types.supertype(sup)) {
  2245             Scope s = sup.tsym.members();
  2246             for (Scope.Entry e = s.lookup(m.name); e.scope != null; e = e.next()) {
  2247                 if (e.sym.kind == MTH &&
  2248                     (e.sym.flags() & (PUBLIC | PROTECTED)) != 0 &&
  2249                     types.overrideEquivalent(m.type, e.sym.type))
  2250                     log.error(pos, "intf.annotation.member.clash", e.sym, sup);
  2255     /** Check the annotations of a symbol.
  2256      */
  2257     public void validateAnnotations(List<JCAnnotation> annotations, Symbol s) {
  2258         if (skipAnnotations) return;
  2259         for (JCAnnotation a : annotations)
  2260             validateAnnotation(a, s);
  2263     /** Check an annotation of a symbol.
  2264      */
  2265     public void validateAnnotation(JCAnnotation a, Symbol s) {
  2266         validateAnnotationTree(a);
  2268         if (!annotationApplicable(a, s))
  2269             log.error(a.pos(), "annotation.type.not.applicable");
  2271         if (a.annotationType.type.tsym == syms.overrideType.tsym) {
  2272             if (!isOverrider(s))
  2273                 log.error(a.pos(), "method.does.not.override.superclass");
  2277     /** Is s a method symbol that overrides a method in a superclass? */
  2278     boolean isOverrider(Symbol s) {
  2279         if (s.kind != MTH || s.isStatic())
  2280             return false;
  2281         MethodSymbol m = (MethodSymbol)s;
  2282         TypeSymbol owner = (TypeSymbol)m.owner;
  2283         for (Type sup : types.closure(owner.type)) {
  2284             if (sup == owner.type)
  2285                 continue; // skip "this"
  2286             Scope scope = sup.tsym.members();
  2287             for (Scope.Entry e = scope.lookup(m.name); e.scope != null; e = e.next()) {
  2288                 if (!e.sym.isStatic() && m.overrides(e.sym, owner, types, true))
  2289                     return true;
  2292         return false;
  2295     /** Is the annotation applicable to the symbol? */
  2296     boolean annotationApplicable(JCAnnotation a, Symbol s) {
  2297         Attribute.Compound atTarget =
  2298             a.annotationType.type.tsym.attribute(syms.annotationTargetType.tsym);
  2299         if (atTarget == null) return true;
  2300         Attribute atValue = atTarget.member(names.value);
  2301         if (!(atValue instanceof Attribute.Array)) return true; // error recovery
  2302         Attribute.Array arr = (Attribute.Array) atValue;
  2303         for (Attribute app : arr.values) {
  2304             if (!(app instanceof Attribute.Enum)) return true; // recovery
  2305             Attribute.Enum e = (Attribute.Enum) app;
  2306             if (e.value.name == names.TYPE)
  2307                 { if (s.kind == TYP) return true; }
  2308             else if (e.value.name == names.FIELD)
  2309                 { if (s.kind == VAR && s.owner.kind != MTH) return true; }
  2310             else if (e.value.name == names.METHOD)
  2311                 { if (s.kind == MTH && !s.isConstructor()) return true; }
  2312             else if (e.value.name == names.PARAMETER)
  2313                 { if (s.kind == VAR &&
  2314                       s.owner.kind == MTH &&
  2315                       (s.flags() & PARAMETER) != 0)
  2316                     return true;
  2318             else if (e.value.name == names.CONSTRUCTOR)
  2319                 { if (s.kind == MTH && s.isConstructor()) return true; }
  2320             else if (e.value.name == names.LOCAL_VARIABLE)
  2321                 { if (s.kind == VAR && s.owner.kind == MTH &&
  2322                       (s.flags() & PARAMETER) == 0)
  2323                     return true;
  2325             else if (e.value.name == names.ANNOTATION_TYPE)
  2326                 { if (s.kind == TYP && (s.flags() & ANNOTATION) != 0)
  2327                     return true;
  2329             else if (e.value.name == names.PACKAGE)
  2330                 { if (s.kind == PCK) return true; }
  2331             else if (e.value.name == names.TYPE_USE)
  2332                 { if (s.kind == TYP ||
  2333                       s.kind == VAR ||
  2334                       (s.kind == MTH && !s.isConstructor() &&
  2335                        s.type.getReturnType().tag != VOID))
  2336                     return true;
  2338             else
  2339                 return true; // recovery
  2341         return false;
  2344     /** Check an annotation value.
  2345      */
  2346     public void validateAnnotation(JCAnnotation a) {
  2347         if (a.type.isErroneous()) return;
  2349         // collect an inventory of the members (sorted alphabetically)
  2350         Set<MethodSymbol> members = new TreeSet<MethodSymbol>(new Comparator<Symbol>() {
  2351             public int compare(Symbol t, Symbol t1) {
  2352                 return t.name.compareTo(t1.name);
  2354         });
  2355         for (Scope.Entry e = a.annotationType.type.tsym.members().elems;
  2356              e != null;
  2357              e = e.sibling)
  2358             if (e.sym.kind == MTH)
  2359                 members.add((MethodSymbol) e.sym);
  2361         // count them off as they're annotated
  2362         for (JCTree arg : a.args) {
  2363             if (arg.getTag() != JCTree.ASSIGN) continue; // recovery
  2364             JCAssign assign = (JCAssign) arg;
  2365             Symbol m = TreeInfo.symbol(assign.lhs);
  2366             if (m == null || m.type.isErroneous()) continue;
  2367             if (!members.remove(m))
  2368                 log.error(assign.lhs.pos(), "duplicate.annotation.member.value",
  2369                           m.name, a.type);
  2372         // all the remaining ones better have default values
  2373         ListBuffer<Name> missingDefaults = ListBuffer.lb();
  2374         for (MethodSymbol m : members) {
  2375             if (m.defaultValue == null && !m.type.isErroneous()) {
  2376                 missingDefaults.append(m.name);
  2379         if (missingDefaults.nonEmpty()) {
  2380             String key = (missingDefaults.size() > 1)
  2381                     ? "annotation.missing.default.value.1"
  2382                     : "annotation.missing.default.value";
  2383             log.error(a.pos(), key, a.type, missingDefaults);
  2386         // special case: java.lang.annotation.Target must not have
  2387         // repeated values in its value member
  2388         if (a.annotationType.type.tsym != syms.annotationTargetType.tsym ||
  2389             a.args.tail == null)
  2390             return;
  2392         if (a.args.head.getTag() != JCTree.ASSIGN) return; // error recovery
  2393         JCAssign assign = (JCAssign) a.args.head;
  2394         Symbol m = TreeInfo.symbol(assign.lhs);
  2395         if (m.name != names.value) return;
  2396         JCTree rhs = assign.rhs;
  2397         if (rhs.getTag() != JCTree.NEWARRAY) return;
  2398         JCNewArray na = (JCNewArray) rhs;
  2399         Set<Symbol> targets = new HashSet<Symbol>();
  2400         for (JCTree elem : na.elems) {
  2401             if (!targets.add(TreeInfo.symbol(elem))) {
  2402                 log.error(elem.pos(), "repeated.annotation.target");
  2407     void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
  2408         if (allowAnnotations &&
  2409             lint.isEnabled(LintCategory.DEP_ANN) &&
  2410             (s.flags() & DEPRECATED) != 0 &&
  2411             !syms.deprecatedType.isErroneous() &&
  2412             s.attribute(syms.deprecatedType.tsym) == null) {
  2413             log.warning(LintCategory.DEP_ANN,
  2414                     pos, "missing.deprecated.annotation");
  2418     void checkDeprecated(final DiagnosticPosition pos, final Symbol other, final Symbol s) {
  2419         if ((s.flags() & DEPRECATED) != 0 &&
  2420                 (other.flags() & DEPRECATED) == 0 &&
  2421                 s.outermostClass() != other.outermostClass()) {
  2422             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2423                 @Override
  2424                 public void report() {
  2425                     warnDeprecated(pos, s);
  2427             });
  2428         };
  2431     void checkSunAPI(final DiagnosticPosition pos, final Symbol s) {
  2432         if ((s.flags() & PROPRIETARY) != 0) {
  2433             deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
  2434                 public void report() {
  2435                     if (enableSunApiLintControl)
  2436                       warnSunApi(pos, "sun.proprietary", s);
  2437                     else
  2438                       log.strictWarning(pos, "sun.proprietary", s);
  2440             });
  2444 /* *************************************************************************
  2445  * Check for recursive annotation elements.
  2446  **************************************************************************/
  2448     /** Check for cycles in the graph of annotation elements.
  2449      */
  2450     void checkNonCyclicElements(JCClassDecl tree) {
  2451         if ((tree.sym.flags_field & ANNOTATION) == 0) return;
  2452         Assert.check((tree.sym.flags_field & LOCKED) == 0);
  2453         try {
  2454             tree.sym.flags_field |= LOCKED;
  2455             for (JCTree def : tree.defs) {
  2456                 if (def.getTag() != JCTree.METHODDEF) continue;
  2457                 JCMethodDecl meth = (JCMethodDecl)def;
  2458                 checkAnnotationResType(meth.pos(), meth.restype.type);
  2460         } finally {
  2461             tree.sym.flags_field &= ~LOCKED;
  2462             tree.sym.flags_field |= ACYCLIC_ANN;
  2466     void checkNonCyclicElementsInternal(DiagnosticPosition pos, TypeSymbol tsym) {
  2467         if ((tsym.flags_field & ACYCLIC_ANN) != 0)
  2468             return;
  2469         if ((tsym.flags_field & LOCKED) != 0) {
  2470             log.error(pos, "cyclic.annotation.element");
  2471             return;
  2473         try {
  2474             tsym.flags_field |= LOCKED;
  2475             for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
  2476                 Symbol s = e.sym;
  2477                 if (s.kind != Kinds.MTH)
  2478                     continue;
  2479                 checkAnnotationResType(pos, ((MethodSymbol)s).type.getReturnType());
  2481         } finally {
  2482             tsym.flags_field &= ~LOCKED;
  2483             tsym.flags_field |= ACYCLIC_ANN;
  2487     void checkAnnotationResType(DiagnosticPosition pos, Type type) {
  2488         switch (type.tag) {
  2489         case TypeTags.CLASS:
  2490             if ((type.tsym.flags() & ANNOTATION) != 0)
  2491                 checkNonCyclicElementsInternal(pos, type.tsym);
  2492             break;
  2493         case TypeTags.ARRAY:
  2494             checkAnnotationResType(pos, types.elemtype(type));
  2495             break;
  2496         default:
  2497             break; // int etc
  2501 /* *************************************************************************
  2502  * Check for cycles in the constructor call graph.
  2503  **************************************************************************/
  2505     /** Check for cycles in the graph of constructors calling other
  2506      *  constructors.
  2507      */
  2508     void checkCyclicConstructors(JCClassDecl tree) {
  2509         Map<Symbol,Symbol> callMap = new HashMap<Symbol, Symbol>();
  2511         // enter each constructor this-call into the map
  2512         for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
  2513             JCMethodInvocation app = TreeInfo.firstConstructorCall(l.head);
  2514             if (app == null) continue;
  2515             JCMethodDecl meth = (JCMethodDecl) l.head;
  2516             if (TreeInfo.name(app.meth) == names._this) {
  2517                 callMap.put(meth.sym, TreeInfo.symbol(app.meth));
  2518             } else {
  2519                 meth.sym.flags_field |= ACYCLIC;
  2523         // Check for cycles in the map
  2524         Symbol[] ctors = new Symbol[0];
  2525         ctors = callMap.keySet().toArray(ctors);
  2526         for (Symbol caller : ctors) {
  2527             checkCyclicConstructor(tree, caller, callMap);
  2531     /** Look in the map to see if the given constructor is part of a
  2532      *  call cycle.
  2533      */
  2534     private void checkCyclicConstructor(JCClassDecl tree, Symbol ctor,
  2535                                         Map<Symbol,Symbol> callMap) {
  2536         if (ctor != null && (ctor.flags_field & ACYCLIC) == 0) {
  2537             if ((ctor.flags_field & LOCKED) != 0) {
  2538                 log.error(TreeInfo.diagnosticPositionFor(ctor, tree),
  2539                           "recursive.ctor.invocation");
  2540             } else {
  2541                 ctor.flags_field |= LOCKED;
  2542                 checkCyclicConstructor(tree, callMap.remove(ctor), callMap);
  2543                 ctor.flags_field &= ~LOCKED;
  2545             ctor.flags_field |= ACYCLIC;
  2549 /* *************************************************************************
  2550  * Miscellaneous
  2551  **************************************************************************/
  2553     /**
  2554      * Return the opcode of the operator but emit an error if it is an
  2555      * error.
  2556      * @param pos        position for error reporting.
  2557      * @param operator   an operator
  2558      * @param tag        a tree tag
  2559      * @param left       type of left hand side
  2560      * @param right      type of right hand side
  2561      */
  2562     int checkOperator(DiagnosticPosition pos,
  2563                        OperatorSymbol operator,
  2564                        int tag,
  2565                        Type left,
  2566                        Type right) {
  2567         if (operator.opcode == ByteCodes.error) {
  2568             log.error(pos,
  2569                       "operator.cant.be.applied",
  2570                       treeinfo.operatorName(tag),
  2571                       List.of(left, right));
  2573         return operator.opcode;
  2577     /**
  2578      *  Check for division by integer constant zero
  2579      *  @param pos           Position for error reporting.
  2580      *  @param operator      The operator for the expression
  2581      *  @param operand       The right hand operand for the expression
  2582      */
  2583     void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
  2584         if (operand.constValue() != null
  2585             && lint.isEnabled(LintCategory.DIVZERO)
  2586             && operand.tag <= LONG
  2587             && ((Number) (operand.constValue())).longValue() == 0) {
  2588             int opc = ((OperatorSymbol)operator).opcode;
  2589             if (opc == ByteCodes.idiv || opc == ByteCodes.imod
  2590                 || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
  2591                 log.warning(LintCategory.DIVZERO, pos, "div.zero");
  2596     /**
  2597      * Check for empty statements after if
  2598      */
  2599     void checkEmptyIf(JCIf tree) {
  2600         if (tree.thenpart.getTag() == JCTree.SKIP && tree.elsepart == null && lint.isEnabled(LintCategory.EMPTY))
  2601             log.warning(LintCategory.EMPTY, tree.thenpart.pos(), "empty.if");
  2604     /** Check that symbol is unique in given scope.
  2605      *  @param pos           Position for error reporting.
  2606      *  @param sym           The symbol.
  2607      *  @param s             The scope.
  2608      */
  2609     boolean checkUnique(DiagnosticPosition pos, Symbol sym, Scope s) {
  2610         if (sym.type.isErroneous())
  2611             return true;
  2612         if (sym.owner.name == names.any) return false;
  2613         for (Scope.Entry e = s.lookup(sym.name); e.scope == s; e = e.next()) {
  2614             if (sym != e.sym &&
  2615                 (e.sym.flags() & CLASH) == 0 &&
  2616                 sym.kind == e.sym.kind &&
  2617                 sym.name != names.error &&
  2618                 (sym.kind != MTH || types.hasSameArgs(types.erasure(sym.type), types.erasure(e.sym.type)))) {
  2619                 if ((sym.flags() & VARARGS) != (e.sym.flags() & VARARGS)) {
  2620                     varargsDuplicateError(pos, sym, e.sym);
  2621                     return true;
  2622                 } else if (sym.kind == MTH && !hasSameSignature(sym.type, e.sym.type)) {
  2623                     duplicateErasureError(pos, sym, e.sym);
  2624                     sym.flags_field |= CLASH;
  2625                     return true;
  2626                 } else {
  2627                     duplicateError(pos, e.sym);
  2628                     return false;
  2632         return true;
  2634     //where
  2635         boolean hasSameSignature(Type mt1, Type mt2) {
  2636             if (mt1.tag == FORALL && mt2.tag == FORALL) {
  2637                 ForAll fa1 = (ForAll)mt1;
  2638                 ForAll fa2 = (ForAll)mt2;
  2639                 mt2 = types.subst(fa2, fa2.tvars, fa1.tvars);
  2641             return types.hasSameArgs(mt1.asMethodType(), mt2.asMethodType());
  2644         /** Report duplicate declaration error.
  2645          */
  2646         void duplicateErasureError(DiagnosticPosition pos, Symbol sym1, Symbol sym2) {
  2647             if (!sym1.type.isErroneous() && !sym2.type.isErroneous()) {
  2648                 log.error(pos, "name.clash.same.erasure", sym1, sym2);
  2652     /** Check that single-type import is not already imported or top-level defined,
  2653      *  but make an exception for two single-type imports which denote the same type.
  2654      *  @param pos           Position for error reporting.
  2655      *  @param sym           The symbol.
  2656      *  @param s             The scope
  2657      */
  2658     boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2659         return checkUniqueImport(pos, sym, s, false);
  2662     /** Check that static single-type import is not already imported or top-level defined,
  2663      *  but make an exception for two single-type imports which denote the same type.
  2664      *  @param pos           Position for error reporting.
  2665      *  @param sym           The symbol.
  2666      *  @param s             The scope
  2667      *  @param staticImport  Whether or not this was a static import
  2668      */
  2669     boolean checkUniqueStaticImport(DiagnosticPosition pos, Symbol sym, Scope s) {
  2670         return checkUniqueImport(pos, sym, s, true);
  2673     /** Check that single-type import is not already imported or top-level defined,
  2674      *  but make an exception for two single-type imports which denote the same type.
  2675      *  @param pos           Position for error reporting.
  2676      *  @param sym           The symbol.
  2677      *  @param s             The scope.
  2678      *  @param staticImport  Whether or not this was a static import
  2679      */
  2680     private boolean checkUniqueImport(DiagnosticPosition pos, Symbol sym, Scope s, boolean staticImport) {
  2681         for (Scope.Entry e = s.lookup(sym.name); e.scope != null; e = e.next()) {
  2682             // is encountered class entered via a class declaration?
  2683             boolean isClassDecl = e.scope == s;
  2684             if ((isClassDecl || sym != e.sym) &&
  2685                 sym.kind == e.sym.kind &&
  2686                 sym.name != names.error) {
  2687                 if (!e.sym.type.isErroneous()) {
  2688                     String what = e.sym.toString();
  2689                     if (!isClassDecl) {
  2690                         if (staticImport)
  2691                             log.error(pos, "already.defined.static.single.import", what);
  2692                         else
  2693                             log.error(pos, "already.defined.single.import", what);
  2695                     else if (sym != e.sym)
  2696                         log.error(pos, "already.defined.this.unit", what);
  2698                 return false;
  2701         return true;
  2704     /** Check that a qualified name is in canonical form (for import decls).
  2705      */
  2706     public void checkCanonical(JCTree tree) {
  2707         if (!isCanonical(tree))
  2708             log.error(tree.pos(), "import.requires.canonical",
  2709                       TreeInfo.symbol(tree));
  2711         // where
  2712         private boolean isCanonical(JCTree tree) {
  2713             while (tree.getTag() == JCTree.SELECT) {
  2714                 JCFieldAccess s = (JCFieldAccess) tree;
  2715                 if (s.sym.owner != TreeInfo.symbol(s.selected))
  2716                     return false;
  2717                 tree = s.selected;
  2719             return true;
  2722     private class ConversionWarner extends Warner {
  2723         final String uncheckedKey;
  2724         final Type found;
  2725         final Type expected;
  2726         public ConversionWarner(DiagnosticPosition pos, String uncheckedKey, Type found, Type expected) {
  2727             super(pos);
  2728             this.uncheckedKey = uncheckedKey;
  2729             this.found = found;
  2730             this.expected = expected;
  2733         @Override
  2734         public void warn(LintCategory lint) {
  2735             boolean warned = this.warned;
  2736             super.warn(lint);
  2737             if (warned) return; // suppress redundant diagnostics
  2738             switch (lint) {
  2739                 case UNCHECKED:
  2740                     Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
  2741                     break;
  2742                 case VARARGS:
  2743                     if (method != null &&
  2744                             method.attribute(syms.trustMeType.tsym) != null &&
  2745                             isTrustMeAllowedOnMethod(method) &&
  2746                             !types.isReifiable(method.type.getParameterTypes().last())) {
  2747                         Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
  2749                     break;
  2750                 default:
  2751                     throw new AssertionError("Unexpected lint: " + lint);
  2756     public Warner castWarner(DiagnosticPosition pos, Type found, Type expected) {
  2757         return new ConversionWarner(pos, "unchecked.cast.to.type", found, expected);
  2760     public Warner convertWarner(DiagnosticPosition pos, Type found, Type expected) {
  2761         return new ConversionWarner(pos, "unchecked.assign", found, expected);

mercurial